Querying Data
Before querying the data from the database, we need to create the database in the postgres.
Source
Sample data is stored at https://github.com/syedjaferk/postgres_sample_database/blob/main/dvd_rental/dvdrental.tar
location.
Steps to import the database
- Download the tar file from the given link.
- Login to the postgres db using
psql postgres
and create the databasedvdrental
- Verify if the database is created using
\l
- Disconnect the postgres using
exit
- Load the dataset into the database using
pg_restore
- Login to the postgres with the database as dvdrental and verify the database is loaded.
SELECT Query
The SELECT statement is an SQL command used to retrieve data from the database.
1. Basic SELECT Statement

2. SELECT statement with multiple columns

Remember that we should not use *
in the select query because it leads to the following issues
1. Performance issues : Retrieving all the columns will make database operations slow if the retrieving data is huge.
2. Application overhead : If we are retrieving the data which is unnecessary for application operation will lead to more traffic/load to the application.
3. Application break : If you are using *
in the query, application may break in case of database structure changed after the application deployed in the production.
So, if we don't know the table structure, we can use *
to find out the table columns.
Also, if we are troubleshooting, then we can use *
in the select statement. Other than this, we cannot use *
in any other situation. It is not a good practice.
Example: Instead of this
Do this,ALIAS
The main purpose of column aliases is to make the headings of the output more meaningful. This is temporary during the execution of the query.
1. Assigning alias to a column
2. Assigning alias to an expression

Order By
The ORDER BY clause allows you to sort rows returned by a SELECT clause in ascending or descending order based on a sort expression. The ORDER BY uses ASC (Ascending) by default.
SELECT
column name
FROM
table_name
ORDER BY
sort_expression1 [ASC | DESC],
sort_expression2 [ASC | DESC];
1. ORDER BY clause to sort rows by one column
2. ORDER BY clause to sort rows by multiple columns
3. ORDER BY clause to sort rows by expressions
SELECT DISTINCT
The SELECT DISTINCT removes duplicate rows from a result set. The SELECT DISTINCT clause can be applied to one or more columns in the select list of the SELECT statement.
1. SELECT DISTINCT with one column
2. SELECT DISTINCT on multiple columns