Statements (PostgreSQL)
SELECT
LIKE and ILIKE
DISTINCT
LIMIT and OFFSET
LIMITandOFFSETare used to return a portion of data from a resultset generated by a query; theLIMITclause is used to limit the number of records in output and theOFFSETclause is used to provide PostgreSQL with the position in the resultset from which to start returning data.
Combining Queries
UNION / UNION ALL
The
UNIONoperator is used to combine the resultset of two or moreSELECTstatements. We can use theUNIONstatement only if the following rules are respected:
- Each
SELECTstatement withinUNIONmust have the same number of columns.- The columns must have similar data types.
- The columns in each
SELECTstatement must be in the same order.
UNIONis an alias toUNION DISTINCT.
EXCEPT / INTERSECT
Upsert
In PostgreSQL, the
UPSERTstatement does not exist as in other DBMSes. AnUPSERTstatement is used when we want to insert a new record on top of the existing record or update an existing record.
The optional ON CONFLICT clause specifies an alternative action to raising a
unique violation or exclusion constraint violation error:
INSERT INTO table_name(c1, c2, ..., cn) VALUES(v1, v2, ..., vn) ON CONFLICT (...);
and the conflict action can be either:
DO NOTHING.DO UPDATE+ (SETand/orWHERE)
INSERT INTO table_name(c1, c2, ..., cn) VALUES(v1, v2, ..., vn) ON CONFLICT DO UPDATE SET c1 = EXCLUDED.v1;
where EXCLUDED references the proposed new insertion row.
RETURNING
Reduces the need for an extra query as it enables you to output columns.