PostgreSQL Query data
Select all the data
SELECT * FROM table_name;
The above query will return all the rows form the table.
Select specific column from the table
SELECT column_1 , column_2 FROM table_name;
Adding aliases to column in the table
SELECT column_1 AS "alias" , column_2 AS "alias" FROM table_name;
Example user table:
id | f_name | l_name |
1 | Saheb | Sutradhar |
SELECT f_name AS "First name" ,l_name AS "Last name" FROM users;
Same query you can write like this , both are same
SELECT
f_name "First name",
l_name "Last name"
FROM users;
Output:
First name | Last name |
Saheb | Sutradhar |
SELECT f_name ||' '|| l_name AS "Full name" FROM users;
Full name |
Saheb Sutradhar |
Sorting data in postgreSQL
We use ORDER BY keyword in order to shot the table data
Data table :
id | name |
1 | John |
2 | Saheb |
3 | Adam |
Sort data in ascending order
SELECT * FROM customer
ORDER BY name ASC;
SELECT * FROM customer
ORDER BY name;
NOTE : ORDER BY default is ASC (ascending)
Output :
id | name |
3 | Adam |
1 | John |
2 | Saheb |
Sort data in descending order
SELECT * FROM customer
ORDER BY name DESC;
Output :
id | name |
2 | Saheb |
1 | John |
3 | Adam |
ORDER BY with alias column name
SELECT name AS Name FROM customer
ORDER BY name ASC;
Output :
Name |
Adam |
John |
Saheb |
ORDER BY with expression
SELECT name AS Name , LENGTH(name) AS length FROM customer
ORDER BY length ASC;
Output :
Name | length |
John | 4 |
Adam | 4 |
Saheb | 5 |
Sort NULLS
SELECT * FROM table_name ORDER BY NILLS FIRST;
Above query will short the rows contains null in ascending order.
OUTPUT :
null |
Saheb |
John |
SELECT * FROM table_name ORDER BY NILLS LAST;
Above query will short the rows contains null in descending order.
OUTPUT :
Saheb |
John |
null |
SELECT * FROM table_name ORDER BY name ASC NILLS FIRST;
Above query will short the rows contains null in ascending order and shot name in ascending order .
OUTPUT :
null |
John |
Saheb |
SELECT DISTINCT statement
SELECT DISTINCT statement returns only the distinct values , in table a column can contain multiple duplicate values , so if you want to filter the the distinct value we have to use SELECT DISTINCT
color_table :
color |
red |
green |
red |
yellow |
SELECT DISTINCT color FROM color_table;
OUTPUT :
color |
red |
green |
yellow |