Statements (PostgreSQL)
SELECT
LIKE
and ILIKE
DISTINCT
LIMIT
and OFFSET
LIMIT
andOFFSET
are used to return a portion of data from a resultset generated by a query; theLIMIT
clause is used to limit the number of records in output and theOFFSET
clause is used to provide PostgreSQL with the position in the resultset from which to start returning data.
Combining Queries
UNION
/ UNION ALL
The
UNION
operator is used to combine the resultset of two or moreSELECT
statements. We can use theUNION
statement only if the following rules are respected:
- Each
SELECT
statement withinUNION
must have the same number of columns.- The columns must have similar data types.
- The columns in each
SELECT
statement must be in the same order.
UNION
is an alias toUNION DISTINCT
.
EXCEPT
/ INTERSECT
Upsert
In PostgreSQL, the
UPSERT
statement does not exist as in other DBMSes. AnUPSERT
statement 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
+ (SET
and/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.