1. Querying Data
Select
It is used to query data from tables using
SELECTstatementIt has following clauses
Select distinct rows using
DISTINCTclassSort rows using
ORDER BYclauseFilter rows using
WHEREclauseSelect subset of rows from table using
LIMITorFETCHclassGroup rows into groups using
GROUP BYclauseFilter groups using
HAVINGclauseJoin with other tables using joins such as
INNTER JOIN, LEFT JOIN, FULL OUTER JOIN, CROSS JOINclausesPerform set operations using
UNION, INTERSECT, EXCEPTclauses
PostgreSQL evaluates the
FROMclause before theSELECTclause in the SELECT statementWe can also use SELECT statement with expression e.g
SELECT 5 * 3;
Concatenation Operator ||
||We can use this operator to concatenate multiple columns together e.g
Column Aliases
It allows us to assign a column or expression in SELECT statement a temporary name
The
ASkeyword is optional.Following are two styles of defining column aliases
Example 1
Example 2
Order By
It is used to sort the rows of the result set, we use it with the
SELECTclauseWe can get the results in
ASCorDESCorder, it usesASCby defaultPostgreSQL evaluates the clauses in the SELECT statment in the following order:
Example 1

Example 2

NULL Clause
NULL ClauseIn db, NULL is a marker that indicates missing or unknown data
When you sort rows that contains NULL, you can specify order of NULL with other non-null values using the
NULLS FIRSTorNULLS LASToption ofORDER BYclause
Select Distinct
DISTINCTclause is used to remove duplicate rows from a result setIt can be applied to one or more columns
If we specify multiple columns, DISTINCT clause will evaluate the duplicate based on the combination of values of columns given
Example 1
Example 2

DISTINCT ON
PostgreSQL also provides the
DISTINCT ON (expression)to keep the “first” row of each group of duplicatesThe order of rows returned from the SELECT statement is unspecified therefore the “first” row of each group of the duplicate is also unspecified.
It is a good practice to always use the ORDER BY clause with the DISTINCT ON(expression) to make the result set predictable.
Notice that the DISTINCT ON expression must match the leftmost expression in the ORDER BY clause.
Example 3

Last updated
