Description

SELECT is one of the most complex PostgreSQL statements, with many clauses that form flexible queries. In its simplest form it retrieves data from a single table.

SELECT select_list
FROM table_name;

Basic SELECT Examples

SELECT first_name FROM customer;                          -- one column
SELECT first_name, last_name, email FROM customer;        -- several columns
SELECT * FROM customer;                                   -- all columns
SELECT first_name || ' ' || last_name, email FROM customer; -- expression
SELECT 5 * 3;
SELECT now();

If you do not name an output column, PostgreSQL picks a name automatically: the column name for a simple column reference, a function/type name in other cases, or a generated name such as ?column?.

Aliases

A column alias gives a column or expression a temporary name for the duration of the query; a table alias does the same for a table.

SELECT column_name AS alias_name FROM table_name;
SELECT first_name || ' ' || last_name AS full_name FROM customer AS c;

SELECT DISTINCT

Removes duplicate rows from the result set.

SELECT DISTINCT column1 FROM table_name;

Basic PostgreSQL Operators

  1. Arithmetic: +, -, *, /, % (modulo)
  2. Comparison: =, <> or !=, <, >, <=, >= (return TRUE, FALSE or NULL)
  3. Logical: AND (all conditions true), OR (at least one true), NOT (inverts)
  4. Pattern matching:
  5. LIKE: pattern search; % = zero or more characters, _ = exactly one character
  6. ILIKE: case-insensitive LIKE
  7. ~: matches a POSIX regular expression
  8. NULL-related: IS NULL, IS NOT NULL
  9. Other: || (concatenation), BETWEEN (inclusive range), IN (value in a list)

Clauses of SELECT

SELECT [DISTINCT] select_list
FROM table_name
[WHERE condition]
[GROUP BY grouping_elements]
[HAVING condition]
[UNION | INTERSECT | EXCEPT select_statement]
[ORDER BY expression [ASC | DESC] [NULLS FIRST | NULLS LAST]]
[LIMIT count]
[OFFSET start];

WHERE

condition is any expression evaluating to boolean. Any row that does not satisfy it is eliminated from the output.

GROUP BY

Condenses all selected rows that share the same values for the grouped expressions into a single row. A grouping expression can be an input column name, the name or ordinal number of an output column, or an arbitrary expression of input columns.

HAVING

Eliminates group rows that do not satisfy a condition.

WHEREHAVING
Filters individual rows before GROUP BYFilters groups created by GROUP BY

Each column in a HAVING condition must be a grouping column, unless it appears inside an aggregate function.

Set Operations: UNION, INTERSECT, EXCEPT

Each operand is a SELECT without ORDER BY or LIMIT. Both queries must return the same number of columns with compatible data types.

OperatorResultWith ALL
UNIONRows in at least one result set (no duplicates)UNION ALL keeps duplicates
INTERSECTRows in both result sets (no duplicates)A row with m copies on the left and n on the right appears min(m, n) times
EXCEPTRows in the left result but not the right (no duplicates)Appears max(m − n, 0) times

Precedence: INTERSECT binds more tightly than UNION, so A UNION B INTERSECT C is read as A UNION (B INTERSECT C). EXCEPT binds at the same level as UNION; multiple EXCEPT operators are evaluated left to right unless parentheses say otherwise.

ORDER BY

Sorts result rows by one or more expressions. If two rows are equal on the leftmost expression, the next one is compared, and so on. If equal on all, the order is implementation-dependent.

  • Each expression may be an output column name, an ordinal number, or an arbitrary expression.
  • ASC (default) or DESC.
  • NULLS FIRST / NULLS LAST control where NULLs sort (by default NULLs sort last in ascending order).

LIMIT and OFFSET

  • LIMIT count: maximum number of rows returned (LIMIT NULL = LIMIT ALL, no limit).
  • OFFSET start: number of rows to skip before returning rows (OFFSET NULL = OFFSET 0).
  • Used together for pagination; the start rows are skipped before counting the count rows.
SELECT * FROM film ORDER BY title LIMIT 10 OFFSET 20;  -- rows 21-30

Conclusion

SELECT is built from composable clauses that filter (WHERE, HAVING), group (GROUP BY), combine (UNION, INTERSECT, EXCEPT), sort (ORDER BY) and page (LIMIT/OFFSET) the result.