Bookmarks
ReferenceData & AIBackendVerified

SQL

SQL is a query language for retrieving and modifying data in relational databases. This reference covers SELECT, JOIN, GROUP BY, subqueries and CTEs, window functions and NULL.

checked 1 Nov · next check 8 Nov · 66 min read

Sections
14
Reading
66 min
Languages
RU · UZ · EN
Written from
postgresql.org/docs/current/sql.html

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What SQL is and how it works

SQL is a declarative query language for relational databases: you describe the result you want, and the database system decides how to produce it. This reference follows the PostgreSQL documentation and notes where PostgreSQL departs from the SQL standard.

A relational database stores data in tables. A table is a named set of rows with the same columns, and each column has its own data type. The order of columns in a row is fixed, but SQL does not guarantee any order of rows in a table. Tables are grouped into databases, and all the databases of one PostgreSQL server form a cluster.

The result of a query is also a table, so a subquery can stand in for a table in FROM. You run queries in psql, the PostgreSQL terminal client that prints the result as a table of characters, or in any other client. Programs receive the result rows through client libraries.

SELECT is written in one order but processed logically in another. First FROM assembles the rows, WHERE discards the unwanted ones, GROUP BY and HAVING build and filter groups, and only then is the select list evaluated. That is why an alias from SELECT cannot be used in WHERE or HAVING, but can be used in ORDER BY. PostgreSQL also accepts aliases in GROUP BY, which is an extension to the standard.

sql
SELECT customer_id, sum(total) AS revenueFROM ordersWHERE status = 'paid'GROUP BY customer_idHAVING sum(total) > 500ORDER BY revenue DESC, customer_idLIMIT 2;
textexample output
 customer_id | revenue-------------+---------           1 | 1435.00           2 |  640.00(2 rows)
Row counts at each step, for this query on the sample data.

The full logical order follows the SELECT page of the documentation. Subqueries named in WITH (CTEs) are evaluated first; after that they behave like temporary tables. Then:

  1. FROM and JOIN — the rows are assembled; several tables separated by commas give every combination of rows.
  2. WHERE — only rows for which the condition is true remain.
  3. GROUP BY — rows with equal values are collapsed into groups and aggregates are computed; HAVING discards unwanted groups.
  4. Select list — the result columns and window functions are evaluated, and aliases appear.
  5. DISTINCT — duplicate rows are removed.
  6. UNION, INTERSECT, EXCEPT — the results of several SELECTs are combined into one.
  7. ORDER BY — rows are sorted; without it the order is whatever is fastest for the system.
  8. LIMIT, OFFSET or FETCH FIRST — only part of the result is kept.

This is a logical model, not an execution plan. For example, PostgreSQL evaluates select-list expressions after sorting and LIMIT, unless they are needed for DISTINCT, ORDER BY or GROUP BY. An alias does not exist yet in WHERE, so the expression has to be repeated there:

sql
SELECT id, total * 0.12 AS vatFROM ordersWHERE total * 0.12 > 50ORDER BY vat DESC, id;

How PostgreSQL differs from the standard

PostgreSQL understands standard syntax and adds its own extensions. The most noticeable ones:

TaskSQL standardPostgreSQL
First 10 rowsFETCH FIRST 10 ROWS ONLYthe same, and LIMIT 10
Convert a typeCAST(price AS integer)the same, and price::integer
Case-insensitive patternonly LIKEILIKE
First row of each groupnoneDISTINCT ON (customer_id)
Modify data inside WITHnoneWITH d AS (DELETE … RETURNING *)
Subquery in FROM without an aliasnot allowedallowed since PostgreSQL 16

Use the standard form if the query must also work in other database systems. An extension works only where it is also supported: LIMIT, for example, is understood by MySQL too. The standard FETCH FIRST is also used by IBM DB2.

What to know first

  • How to install PostgreSQL, connect to a database and run a query in psql — see the PostgreSQL reference, section “Installation and first run”.
  • What data types exist: numbers, strings, dates, JSON — see the PostgreSQL reference, section “Data model and types”.

Sample schema

All the examples in this reference run on one online-shop schema: customers customers, categories categories, products products, orders orders and their items order_items. Create an empty database and run the next two blocks; after that any example will run. Run examples that modify data between BEGIN and ROLLBACK so the database stays unchanged (see the section “Transactions and isolation levels”). Times in the example output are Tashkent time: to get the same output, run SET TimeZone = 'Asia/Tashkent'; in your session.

sqlsample schema
CREATE TABLE customers (    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    name text NOT NULL,    city text,    email text UNIQUE); CREATE TABLE categories (    id bigint PRIMARY KEY,    parent_id bigint REFERENCES categories,    name text NOT NULL); CREATE TABLE products (    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    name text NOT NULL,    category_id bigint REFERENCES categories,    price numeric(10, 2) NOT NULL CHECK (price > 0)); CREATE TABLE orders (    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    customer_id bigint NOT NULL REFERENCES customers,    status text NOT NULL DEFAULT 'new',    total numeric(12, 2) NOT NULL,    created_at timestamptz NOT NULL DEFAULT now()); CREATE TABLE order_items (    order_id bigint REFERENCES orders ON DELETE CASCADE,    product_id bigint REFERENCES products,    quantity integer NOT NULL CHECK (quantity > 0),    price numeric(10, 2) NOT NULL,    PRIMARY KEY (order_id, product_id));
sqlsample data
INSERT INTO customers (name, city, email) VALUES    ('Aziz', 'Tashkent', 'aziz@example.com'),    ('Dilnoza', 'Samarkand', 'dilnoza@example.com'),    ('Timur', 'Tashkent', NULL),    ('Malika', NULL, 'malika@example.com'),    ('Olga', 'Bukhara', 'olga@example.com'); INSERT INTO categories (id, parent_id, name) VALUES    (1, NULL, 'Electronics'), (2, 1, 'Laptops'),    (3, 1, 'Phones'), (4, 1, 'Accessories'),    (5, 4, 'Cables'); INSERT INTO products (name, category_id, price) VALUES    ('Laptop', 2, 1200), ('Phone', 3, 640),    ('Mouse', 4, 25), ('Charger', 4, 30),    ('Headphones', 4, 150), ('Cable', 5, 10),    ('Tablet', 1, 450); INSERT INTO orders (customer_id, status, total, created_at)VALUES    (1, 'paid', 1200, '2026-08-03 10:15+05'),    (1, 'paid', 85, '2026-09-14 18:40+05'),    (2, 'paid', 640, '2026-09-20 12:00+05'),    (3, 'paid', 300, '2026-10-01 09:30+05'),    (2, 'cancelled', 95, '2026-10-12 16:05+05'),    (4, 'paid', 640, '2026-10-18 11:20+05'),    (1, 'new', 40, '2026-10-25 20:10+05'),    (1, 'paid', 150, '2026-10-28 13:00+05'); INSERT INTO order_items    (order_id, product_id, quantity, price)VALUES    (1, 1, 1, 1200), (2, 3, 1, 25), (2, 4, 2, 30),    (3, 2, 1, 640), (4, 5, 2, 150), (5, 3, 1, 25),    (5, 4, 1, 30), (5, 6, 4, 10), (6, 2, 1, 640),    (7, 6, 4, 10), (8, 5, 1, 150);

Section sources

the section is written from these pages

Cheat sheet

Everyday queries on the sample schema from the section “What SQL is and how it works”; each is explained in its own section.

Selecting and filtering

TaskSyntax
Columns with an aliasSELECT name, city AS town FROM customers;
Several conditionsWHERE status = 'paid' AND total > 100
Range and listWHERE total BETWEEN 50 AND 500, WHERE city IN ('Tashkent', 'Bukhara')
Case-insensitive patternWHERE name ILIKE 'd%'
Sort with a tie-breakerORDER BY total DESC, id
First 10 rowsLIMIT 10 or FETCH FIRST 10 ROWS ONLY
Distinct valuesSELECT DISTINCT city FROM customers;
Latest order of each customerSELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC;

Dates, strings and numbers

TaskSyntax
Start of the monthdate_trunc('month', created_at)
Last 30 daysWHERE created_at >= now() - interval '30 days'
Year and month as a stringto_char(created_at, 'YYYY-MM')
Concatenate, skipping NULLconcat_ws(', ', name, city)
Division with a fractional part5::numeric / 2
Round to 2 decimal placesround(avg(total), 2)
Condition in an expressionCASE WHEN total >= 500 THEN 'large' ELSE 'small' END

Joins

TaskSyntax
Customers and their ordersFROM customers c JOIN orders o ON o.customer_id = c.id
All customers, even without ordersFROM customers c LEFT JOIN orders o ON o.customer_id = c.id
Only customers without ordersthe same, plus WHERE o.id IS NULL
A table joined to itselfFROM categories c LEFT JOIN categories parent ON parent.id = c.parent_id

Grouping

TaskSyntax
Number of rowsSELECT count(*) FROM orders;
Total per groupSELECT customer_id, sum(total) FROM orders GROUP BY customer_id;
Filter groupsHAVING sum(total) > 500
Conditional totalcount(*) FILTER (WHERE status = 'paid')
Comma-separated valuesstring_agg(name, ', ' ORDER BY name)
Subtotals and a grand totalGROUP BY ROLLUP (month)

Subqueries and CTEs

TaskSyntax
Compare with the averageWHERE total > (SELECT avg(total) FROM orders)
Related rows existWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
Named subqueryWITH paid AS (SELECT * FROM orders WHERE status = 'paid') SELECT …
Walk a treeWITH RECURSIVE tree AS (… UNION ALL …) SELECT …

Window functions

TaskSyntax
Row number within a grouprow_number() OVER (PARTITION BY customer_id ORDER BY created_at)
Rank by amountrank() OVER (ORDER BY total DESC)
Previous valuelag(total) OVER (PARTITION BY customer_id ORDER BY created_at)
Running totalsum(total) OVER (ORDER BY created_at)
Share of the grand totaltotal / sum(total) OVER ()

NULL

TaskSyntax
Test for NULLWHERE city IS NULL
Compare, treating NULL as a valueWHERE city IS DISTINCT FROM 'Tashkent'
Replace NULL with a valueCOALESCE(city, 'unknown')
Avoid dividing by zerosum(price * quantity) / NULLIF(sum(quantity), 0)
NULL at the end of the sortORDER BY city NULLS LAST

Modifying data and transactions

TaskSyntax
Insert and get the idINSERT INTO customers (name) VALUES ('Rustam') RETURNING id;
Insert or updateINSERT … ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
Change rowsUPDATE orders SET status = 'paid' WHERE id = 7;
Delete rowsDELETE FROM orders WHERE status = 'cancelled';
Run as a single unitBEGIN; … COMMIT;, to cancel — ROLLBACK;
A different isolation levelBEGIN ISOLATION LEVEL REPEATABLE READ;

Tables

TaskSyntax
Auto-incrementing id columnid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
Add a columnALTER TABLE customers ADD COLUMN phone text;
Add a constraintALTER TABLE orders ADD CHECK (total >= 0);
Save a query as a viewCREATE VIEW paid_orders AS SELECT …;

Dangerous commands

TaskSyntax
Change all rows (no WHERE)UPDATE orders SET status = 'paid';
Delete all rows (no WHERE)DELETE FROM orders;
Empty a table entirely, quicklyTRUNCATE order_items;
Drop a table with its dataDROP TABLE order_items;
Drop it along with dependent objectsDROP TABLE orders CASCADE;

Section sources

the section is written from these pages

SELECT: selecting, filtering and sorting

SELECT chooses rows: the select list defines the result columns, WHERE decides which rows to keep, ORDER BY sets the order, and LIMIT says how many rows to return. Without ORDER BY the row order is not guaranteed and may change from run to run.

Customer 1’s orders for September and October 2026, largest first:

sql
SELECT id, total, created_atFROM ordersWHERE customer_id = 1  AND created_at >= '2026-09-01'  AND created_at < '2026-11-01'ORDER BY total DESC;
textexample output
 id | total  |       created_at----+--------+------------------------  8 | 150.00 | 2026-10-28 13:00:00+05  2 |  85.00 | 2026-09-14 18:40:00+05  7 |  40.00 | 2026-10-25 20:10:00+05(3 rows)

WHERE keeps only the rows for which the condition is true. Strings and dates are written in single quotes. When the type is unambiguous, as in a comparison with a column, PostgreSQL converts the constant '2026-09-01' to the right type itself; otherwise state the type explicitly: date '2026-09-01' or the standard CAST('2026-09-01' AS date). The form '2026-09-01'::date is the same conversion in PostgreSQL syntax.

The period is defined as “not earlier than the start, and strictly earlier than the start of the next month”, so all of 31 October is included, whatever the time.

Select list and aliases

The select list is the columns and expressions separated by commas; an expression is evaluated for each row. AS gives a result column a name, an alias. The documentation recommends always writing AS: without it, a name that coincides with a keyword breaks the query. * means all columns. That is fine in a console, but in application code list the columns explicitly, otherwise a new table column will change the result.

sql
SELECT name,       upper(city) AS city_upper,       'customer #' || id AS labelFROM customers;

Conditions in WHERE

OperatorExampleWhat it tests
=, <>, <, >=status <> 'cancelled'comparison; != is the same as <>
BETWEEN … AND …total BETWEEN 50 AND 500a range, both ends included
IN (…)city IN ('Tashkent', 'Bukhara')equality to one of the values
LIKEemail LIKE '%@example.com'a pattern: % is any substring, _ is a single character
ILIKEname ILIKE 'd%'a case-insensitive pattern, a PostgreSQL extension
IS NULLcity IS NULLthe value is missing
AND, OR, NOTNOT (status = 'new')logical connectives

A LIKE pattern is always matched against the whole string: to find a substring anywhere, start and end the pattern with %. Comparing with NULL using = always gives NULL, not true: test with IS NULL. See the section “NULL and three-valued logic” for details.

AND binds more tightly than OR: the condition a OR b AND c is read as a OR (b AND c). When you mix them, use parentheses:

sql
-- without the parentheses, unpaid order 7 of customer 1 would be returned tooSELECT id, customer_id, statusFROM ordersWHERE (customer_id = 1 OR customer_id = 3)  AND status = 'paid';

Sorting: ORDER BY

Sorting is ascending (ASC) by default; DESC sorts in descending order. Rows that are equal on the first key are ordered by the second, and so on. A direction applies only to its own key: ORDER BY x, y DESC means x ascending and y descending. You can sort by an expression, by an alias from the select list, or by the position of a result column.

In sorting, NULL counts as larger than any value: with ASC it comes last, with DESC first. NULLS FIRST and NULLS LAST change that:

sql
SELECT name, cityFROM customersORDER BY city NULLS LAST, name;

How many rows to return: LIMIT and FETCH FIRST

LIMIT n returns at most n rows, and OFFSET m first skips m rows. This is PostgreSQL syntax; in standard SQL the same thing is written OFFSET m ROWS FETCH FIRST n ROWS ONLY. FETCH FIRST … WITH TIES adds the rows that are equal to the last one on the ORDER BY keys, so it requires ORDER BY.

sql
-- the two largest orders, plus any tied with the secondSELECT id, totalFROM ordersORDER BY total DESCFETCH FIRST 2 ROWS WITH TIES;
textexample output
 id |  total----+---------  1 | 1200.00  6 |  640.00  3 |  640.00(3 rows)

Use an ORDER BY that orders the rows unambiguously, for example with id as the last key. Otherwise LIMIT returns an unpredictable subset, and pages with different OFFSET values may overlap or lose rows.

sql
-- the second page of 3 ordersSELECT id, created_atFROM ordersORDER BY created_at DESC, idLIMIT 3 OFFSET 3;

No duplicates: DISTINCT and DISTINCT ON

SELECT DISTINCT removes duplicate rows from the result; NULLs are treated as equal to each other. DISTINCT ON (expression) is a PostgreSQL extension: from each set of rows with the same expression value, the first one is kept. ORDER BY decides which row is first, and its leftmost keys must match the DISTINCT ON expressions.

sql
-- the latest order of each customerSELECT DISTINCT ON (customer_id)       customer_id, id, total, created_atFROM ordersORDER BY customer_id, created_at DESC;
textexample output
 customer_id | id | total  |       created_at-------------+----+--------+------------------------           1 |  8 | 150.00 | 2026-10-28 13:00:00+05           2 |  5 |  95.00 | 2026-10-12 16:05:00+05           3 |  4 | 300.00 | 2026-10-01 09:30:00+05           4 |  6 | 640.00 | 2026-10-18 11:20:00+05(4 rows)

Without extensions, the same task is solved by the row_number() window function: see the section “Window functions”, the recipe that filters on the window result.

Section sources

the section is written from these pages

Date, string and number functions

Functions and operators process values right in the query: truncate a date to the month, compute intervals, clean up strings, round numbers. You can write them in any expression: in the select list, WHERE, GROUP BY or ORDER BY.

Revenue by month for the 90 days before 1 November 2026. In a real report you would write now() instead of a fixed date, and the window would shift every day; here the date is fixed so that the output matches the sample data:

sql
SET TimeZone = 'Asia/Tashkent'; SELECT date_trunc('month', created_at) AS month,       sum(total) AS revenueFROM ordersWHERE status = 'paid'  AND created_at >= timestamptz '2026-11-01'                    - interval '90 days'GROUP BY monthORDER BY month;
textexample output
         month          | revenue------------------------+--------- 2026-08-01 00:00:00+05 | 1200.00 2026-09-01 00:00:00+05 |  725.00 2026-10-01 00:00:00+05 | 1090.00(3 rows)

date_trunc('month', …) zeroes everything smaller than a month, so all the orders of a month get the same date, and that is what you group by. For timestamptz, the month boundary is computed in the session time zone (the TimeZone setting), so the same query may place orders in different months depending on the zone. You can also pass the zone as a third argument: date_trunc('day', created_at, 'UTC'). For the difference between timestamp and timestamptz, see the PostgreSQL reference, section “Data model and types”.

Dates and times

TaskExpressionResult
Start of the monthdate_trunc('month', timestamp '2026-10-18 11:20')2026-10-01 00:00:00
Year from a dateextract(year FROM date '2026-10-18')2026
Day of the week, Monday is 1extract(isodow FROM date '2026-10-18')7
Difference between dates in daysdate '2026-10-31' - date '2026-10-18'13
Plus 7 daysdate '2026-10-18' + 72026-10-25
Plus an intervaldate '2026-10-18' + interval '1 month'2026-11-18 00:00:00
Ageage(date '2026-10-31', date '2000-05-15')26 years 5 mons 16 days

now(), current_timestamp and current_date return the start time of the current transaction and do not change until it ends, so all rows of one transaction get the same timestamp. clock_timestamp() gives the actual time at the moment of the call. extract returns numeric; there are two fields for the day of the week: dow (Sunday is 0) and isodow (Monday is 1, Sunday is 7).

Formatting and parsing

TaskExpressionResult
Year and month as a stringto_char(timestamp '2026-10-18 11:20', 'YYYY-MM')2026-10
Day, month, year and timeto_char(timestamp '2026-10-18 11:20', 'DD.MM.YYYY HH24:MI')18.10.2026 11:20
A number with two decimal placesto_char(1234.5, 'FM999990.00')1234.50
A date from a stringto_date('18.10.2026', 'DD.MM.YYYY')2026-10-18
A timestamp from a stringto_timestamp('18.10.2026 11:20', 'DD.MM.YYYY HH24:MI')a timestamptz value

In a template, YYYY is the year, MM the month, DD the day, and HH24 and MI the hours and minutes. The FM prefix removes padding spaces and, in dates, leading zeros too. Standard formats such as 2026-10-18 need no functions: it is enough to cast the string to the type, '2026-10-18'::date.

Strings

TaskExpressionResult
To lower caselower('Tashkent')tashkent
Trim spaces from both endstrim(' Aziz ')Aziz
Length in characterslength('Samarkand')9
Concatenate'Aziz' || ' ' || 'Karimov'Aziz Karimov
Concatenate with a separatorconcat_ws(', ', 'Aziz', NULL, 'Tashkent')Aziz, Tashkent
Substringsubstring('2026-10-18' FROM 6 FOR 2)10
Replacereplace('998-90-123', '-', '')99890123
Part by delimitersplit_part('aziz@example.com', '@', 2)example.com

concat and concat_ws skip NULL arguments, so use them to join columns that may be empty. lower and upper change case according to the database locale rules.

Numbers

TaskExpressionResult
Round to 2 decimal placesround(42.4382, 2)42.44
Up and down to a whole numberceil(42.2), floor(42.8)43, 42
Drop the fractional parttrunc(42.8)42
Absolute valueabs(-17.4)17.4
Remainder of division17 % 52
Integer division5 / 22
Division with a fractional part5::numeric / 22.5000000000000000

Conditions in an expression: CASE

CASE picks a value based on conditions: the first WHEN branch whose condition is true is used; if none matches, ELSE is taken, and without ELSE the result is NULL. You can write CASE anywhere an expression is allowed.

sql
SELECT id, total,       CASE WHEN total >= 500 THEN 'large'            WHEN total >= 100 THEN 'medium'            ELSE 'small'       END AS sizeFROM ordersORDER BY total DESC, id;

GREATEST and LEAST pick the largest and smallest value in a list and skip NULL: GREATEST(10, 25, NULL) is 25. In standard SQL the result would be NULL, and some database systems do exactly that. COALESCE and NULLIF are covered in the section “NULL and three-valued logic”.

Section sources

the section is written from these pages

Joining tables (JOIN)

A join combines rows from two tables on a condition: each pair of rows for which the ON condition is true produces a result row. INNER JOIN keeps only such pairs, while LEFT JOIN also keeps rows of the left table that have no match, filling the right table’s columns with NULL.

Customers with their order counts and totals — including customers who have no orders:

sql
SELECT c.name, count(o.id) AS orders, sum(o.total) AS spentFROM customers cLEFT JOIN orders o ON o.customer_id = c.idGROUP BY c.idORDER BY spent DESC NULLS LAST;
textexample output
  name   | orders |  spent---------+--------+--------- Aziz    |      4 | 1475.00 Dilnoza |      2 |  735.00 Malika  |      1 |  640.00 Timur   |      1 |  300.00 Olga    |      0 |(5 rows)

LEFT JOIN first finds all matching pairs, as INNER JOIN does, and then adds every left-table row that found no match, with NULL in all the right-table columns. Aziz has several orders, so he produces several rows in the join result; Olga has no orders, so she produces one row with NULL. That is why count(o.id) is 0 for her and sum(o.total) is NULL.

A join produces rows of pairs, not an overlap of circles: one row on the left can produce several result rows.

Join types

TypeWhich rows appear in the result
INNER JOIN (or JOIN)only the pairs for which the condition is true
LEFT JOINthe pairs, plus left-table rows with no match, with NULL on the right
RIGHT JOINthe pairs, plus right-table rows with no match, with NULL on the left; the same as LEFT JOIN with the tables swapped
FULL JOINthe pairs, plus unmatched rows from both tables
CROSS JOINevery combination of rows: N rows and M rows give N × M

The words INNER and OUTER are optional: LEFT JOIN and LEFT OUTER JOIN are the same thing. A chain of joins without parentheses nests from left to right. The old form FROM customers c, orders o WHERE o.customer_id = c.id gives the same result as INNER JOIN, but it mixes the join condition with filters, and outer joins cannot be written this way.

ON, USING and NATURAL

ON accepts any boolean condition. USING (customer_id) is shorthand for equality of the same-named columns in both tables; such a column appears in the result only once. The example is a FULL JOIN of two totals: a customer stays in the result even if they have only one of the two sums.

sql
WITH paid AS (    SELECT customer_id, sum(total) AS paid    FROM orders    WHERE status = 'paid'    GROUP BY customer_id), cancelled AS (    SELECT customer_id, sum(total) AS cancelled    FROM orders    WHERE status = 'cancelled'    GROUP BY customer_id)SELECT *FROM paidFULL JOIN cancelled USING (customer_id)ORDER BY customer_id;

NATURAL JOIN joins on all columns with matching names, which is dangerous: a new column with a common name silently becomes part of the condition. In the tutorial schema the shared column of customers and orders is id, so NATURAL JOIN would match customer 1 with order 1, not with that customer’s orders.

sqlwrong
-- don’t: this joins customers.id = orders.idSELECT *FROM customersNATURAL JOIN orders;

Condition in ON versus WHERE

For an inner join it makes no difference where the condition goes. For an outer join it does: a condition in ON applies before the join and decides which rows count as a pair, while WHERE filters the finished result. A condition on the right table in WHERE discards rows with NULL and turns a LEFT JOIN into an inner one.

sqlwrong
-- Olga disappears: her o.status is NULLSELECT c.name, o.id, o.totalFROM customers cLEFT JOIN orders o ON o.customer_id = c.idWHERE o.status = 'paid';
sqlcorrect
-- the condition on the right table goes in ON: all customers staySELECT c.name, o.id, o.totalFROM customers cLEFT JOIN orders o  ON o.customer_id = c.id AND o.status = 'paid';

Row multiplication

A one-to-many join repeats the “one” row for every pair. Order 2 has two items and order 5 has three. After joining with order_items, their total is repeated twice and three times, and the sum of total is inflated: 3425 instead of 3150. Compare the row counts before and after the join:

sql
SELECT count(*) FROM orders;SELECT count(*)FROM orders oJOIN order_items i ON i.order_id = o.id;

Here 8 rows become 11. Calculate order totals before the join, in a subquery or CTE. After the join, sum only the item columns: sum(i.price * i.quantity).

Self-joins and aliases

A table can be joined to itself; each occurrence then needs its own alias. The alias fully replaces the table name for the rest of the query. Qualify columns with the alias as well: the query will not break if one of the tables gains a column with the same name.

sql
SELECT child.name AS category, parent.name AS parentFROM categories childLEFT JOIN categories parent ON parent.id = child.parent_idORDER BY child.id;
textexample output
  category   |   parent-------------+------------- Electronics | Laptops     | Electronics Phones      | Electronics Accessories | Electronics Cables      | Accessories(5 rows)

Rows with no match

“Customers without orders” can be found in two ways: LEFT JOIN with an o.id IS NULL check — on a column that can never be NULL in the table itself — or NOT EXISTS. EXISTS is true if the subquery returns at least one row, and it stops at the first one.

sql
SELECT c.nameFROM customers cLEFT JOIN orders o ON o.customer_id = c.idWHERE o.id IS NULL;
sql
SELECT c.nameFROM customers cWHERE NOT EXISTS (    SELECT 1 FROM orders o WHERE o.customer_id = c.id);

LATERAL: each customer’s latest orders

An ordinary subquery in FROM cannot see the other tables of the query. With LATERAL it can refer to columns of the tables to its left and is evaluated for each of their rows. LEFT JOIN LATERAL … ON true keeps the rows for which the subquery returned nothing.

sql
SELECT c.name, last.id, last.totalFROM customers cLEFT JOIN LATERAL (    SELECT o.id, o.total    FROM orders o    WHERE o.customer_id = c.id    ORDER BY o.created_at DESC    LIMIT 3) AS last ON trueORDER BY c.name, last.id;

Section sources

the section is written from these pages

Aggregate functions and GROUP BY

An aggregate function reduces many rows to a single value: count, sum, avg, min, max. With GROUP BY it is computed separately for each group of rows with equal values; without GROUP BY it is computed over all rows at once.

The number of paid orders and the revenue by month; date_trunc truncates a date to the month — see the section “Date, string and numeric functions” for details:

sql
SELECT date_trunc('month', created_at) AS month,       count(*) AS orders,       sum(total) AS revenueFROM ordersWHERE status = 'paid'GROUP BY monthORDER BY month;
textexample output
         month          | orders | revenue------------------------+--------+--------- 2026-08-01 00:00:00+05 |      1 | 1200.00 2026-09-01 00:00:00+05 |      2 |  725.00 2026-10-01 00:00:00+05 |      3 | 1090.00(3 rows)

GROUP BY month refers to an alias from the select list. The standard allows grouping only by columns of the source tables; PostgreSQL also allows grouping by output columns and by expressions.

What aggregates count

CallWhat it computesNULL
count(*)the number of rowsall rows are counted
count(city)the number of non-null valuesskipped
count(DISTINCT city)the number of distinct non-null valuesskipped
sum(total), avg(total)the sum and the averageskipped
min(created_at), max(created_at)the smallest and the largest valueskipped
string_agg(name, ', ')strings joined with a separatorskipped
array_agg(city)an array of valuesincluded in the array
sql
SELECT count(*), count(city), count(DISTINCT city)FROM customers;

The result is 5, 4 and 3: Malika has no city, and Tashkent appears twice. Except for count, all aggregates over an empty set of rows return NULL, not 0: the sum of orders with a nonexistent status is NULL. COALESCE(sum(total), 0) supplies the zero. avg of integers and of numeric returns numeric, so you can round it straight away: round(avg(total), 2).

The GROUP BY rule

In a query with grouping, every column in the select list must appear in GROUP BY or inside an aggregate: a group has one customer_id value but many total values. The exception is functional dependency: if GROUP BY includes the table’s primary key, you do not have to list that table’s other columns.

sql
-- c.name need not be repeated: c.id is the primary keySELECT c.id, c.name, count(o.id) AS ordersFROM customers cLEFT JOIN orders o ON o.customer_id = c.idGROUP BY c.idORDER BY orders DESC, c.id;

WHERE and HAVING

WHERE selects rows before grouping, so it cannot contain aggregates. HAVING selects groups after grouping and usually contains an aggregate. Put a condition without an aggregate in WHERE: fewer rows then have to be grouped and counted.

sql
-- customers whose paid orders add up to more than 500SELECT customer_id, sum(total) AS paidFROM ordersWHERE status = 'paid'GROUP BY customer_idHAVING sum(total) > 500ORDER BY customer_id;

Conditional totals: FILTER

FILTER (WHERE …) after an aggregate passes it only the matching rows, without affecting the query’s other aggregates. This way several totals under different conditions are computed in a single pass.

sql
SELECT count(*) AS all_orders,       count(*) FILTER (WHERE status = 'paid') AS paid,       sum(total) FILTER (WHERE status = 'new') AS open_sumFROM orders;
textexample output
 all_orders | paid | open_sum------------+------+----------          8 |    6 |    40.00(1 row)

Ordering inside an aggregate

The result of string_agg and array_agg depends on the order of the rows, which is undefined. Set the order inside the call: ORDER BY comes after all the arguments, not between them.

sql
SELECT o.id,       string_agg(p.name, ', ' ORDER BY p.name) AS itemsFROM orders oJOIN order_items i ON i.order_id = o.idJOIN products p ON p.id = i.product_idGROUP BY o.idORDER BY o.id;

Subtotals and a grand total: ROLLUP

GROUPING SETS computes grouping over several sets of columns at once. There are shorthands: ROLLUP (a, b) gives the sets (a, b), (a) and the empty set, that is, totals, subtotals and a grand total; CUBE (a, b) gives all combinations. In subtotal rows, columns that are not in the set are NULL; the GROUPING() function helps tell such a NULL from a real one.

sql
SELECT date_trunc('month', created_at) AS month,       sum(total) AS revenueFROM ordersWHERE status = 'paid'GROUP BY ROLLUP (month)ORDER BY month NULLS LAST;
textexample output
         month          | revenue------------------------+--------- 2026-08-01 00:00:00+05 | 1200.00 2026-09-01 00:00:00+05 |  725.00 2026-10-01 00:00:00+05 | 1090.00                        | 3015.00(4 rows)

Section sources

the section is written from these pages

Subqueries and CTEs (WITH)

A subquery is a SELECT in parentheses inside another query: it yields a single value, a set of rows for IN and EXISTS, or a temporary table in FROM. A CTE (common table expression) is a named subquery in WITH: a long query reads from top to bottom, like a chain of steps.

Customers whose paid orders add up to more than the average:

sql
WITH spent AS (    SELECT customer_id, sum(total) AS amount    FROM orders    WHERE status = 'paid'    GROUP BY customer_id)SELECT c.name, s.amountFROM spent sJOIN customers c ON c.id = s.customer_idWHERE s.amount > (SELECT avg(amount) FROM spent)ORDER BY s.amount DESC;
textexample output
 name | amount------+--------- Aziz | 1435.00(1 row)

spent computes the total for each customer, and the subquery (SELECT avg(amount) FROM spent) computes the average of those totals. spent is referenced twice but evaluated only once.

Scalar subqueries

A scalar subquery returns exactly one row with one column and can appear wherever a value is expected. If it returns more than one row, the query fails with an error; if it returns no rows, the value is NULL. A subquery can refer to columns of the outer query — it is then correlated and is evaluated for each outer row.

sql
-- the date of the latest order next to each customerSELECT c.name,       (SELECT max(o.created_at)        FROM orders o        WHERE o.customer_id = c.id) AS last_orderFROM customers cORDER BY c.name;

IN, EXISTS, ANY and ALL

ExpressionTrue when
x IN (SELECT …)x equals at least one row of the subquery
x NOT IN (SELECT …)x equals no row; if any row is NULL, the result is NULL, not true
EXISTS (SELECT …)the subquery returned at least one row
x > ANY (SELECT …)the comparison is true for at least one row; IN is the same as = ANY
x > ALL (SELECT …)the comparison is true for all rows; NOT IN is the same as <> ALL

EXISTS cares only whether any rows exist, so its select list is conventionally written as SELECT 1. If the subquery can return NULL, use NOT EXISTS instead of NOT IN — the section “NULL and three-valued logic” explains why.

sql
-- products that have never been orderedSELECT p.nameFROM products pWHERE NOT EXISTS (    SELECT 1 FROM order_items i WHERE i.product_id = p.id);

A subquery in FROM

A subquery in FROM works as a temporary table and is written in parentheses. The standard requires an alias for it; PostgreSQL has allowed omitting it since version 16, but with an alias the query is more portable and clearer. This is how you take an aggregate of an aggregate — for example, the average number of orders per customer:

sql
SELECT round(avg(per_customer.orders), 2) AS avg_ordersFROM (    SELECT customer_id, count(*) AS orders    FROM orders    GROUP BY customer_id) AS per_customer;

WITH: named subqueries

A single WITH can list several CTEs separated by commas, and each can read the ones before it. The main query refers to them as tables.

sql
WITH paid AS (    SELECT * FROM orders WHERE status = 'paid'), monthly AS (    SELECT date_trunc('month', created_at) AS month,           sum(total) AS revenue    FROM paid    GROUP BY month)SELECT month, revenueFROM monthlyORDER BY month;

Normally a CTE is evaluated once per query execution, however many references it has. The exception is a side-effect-free CTE that is referenced only once: PostgreSQL inlines it into the main query and optimises them together. WITH x AS MATERIALIZED (…) forces the CTE to be evaluated separately, and AS NOT MATERIALIZED forces it to be inlined even if there are several references.

WITH RECURSIVE: a category tree

A recursive CTE consists of an initial part, UNION ALL (or UNION) and a recursive part that refers to the CTE itself. PostgreSQL runs it in iterations: the recursive part processes the rows of the previous step until none are left. SEARCH DEPTH FIRST BY adds a column for sorting in depth-first traversal order.

sql
WITH RECURSIVE tree AS (    SELECT id, name, 1 AS depth    FROM categories    WHERE parent_id IS NULL  UNION ALL    SELECT c.id, c.name, t.depth + 1    FROM categories c    JOIN tree t ON c.parent_id = t.id) SEARCH DEPTH FIRST BY id SET ordSELECT depth, nameFROM treeORDER BY ord;
textexample output
 depth |    name-------+-------------     1 | Electronics     2 | Laptops     2 | Phones     2 | Accessories     3 | Cables(5 rows)

Modifying data in WITH

WITH can contain INSERT, UPDATE and DELETE, and since PostgreSQL 17 also MERGE. The main query reads not a table but the RETURNING output of that command. Such a command runs exactly once and to completion, even if its output is not read, and all parts of the query see the data as of the same moment.

sql
BEGIN;WITH moved AS (    DELETE FROM orders    WHERE status = 'cancelled'    RETURNING id, total)SELECT count(*) AS deleted, sum(total) AS amountFROM moved;ROLLBACK;

Rows are moved to an archive the same way: if the DELETE returns RETURNING *, the main query INSERT INTO orders_archive SELECT * FROM moved inserts exactly what was deleted.

Views: a query under a name

A query needed in many places can be saved as a view. A view stores no data: its query runs every time the view is accessed. CREATE OR REPLACE VIEW changes the query, but the columns must stay the same; new ones can only be added at the end.

sql
CREATE VIEW paid_orders ASSELECT id, customer_id, total, created_atFROM ordersWHERE status = 'paid'; SELECT customer_id, sum(total) AS paidFROM paid_ordersGROUP BY customer_idORDER BY customer_id;

Section sources

the section is written from these pages

Window functions

A window function computes a value over a set of rows related to the current row. Unlike GROUP BY, it does not collapse rows: each one stays in the result and gets its own value. The set of rows is defined by OVER (PARTITION BY … ORDER BY …).

A customer’s rank by paid revenue within their city:

sql
SELECT c.city, c.name, sum(o.total) AS revenue,       rank() OVER (PARTITION BY c.city                    ORDER BY sum(o.total) DESC) AS placeFROM customers cJOIN orders o ON o.customer_id = c.idWHERE o.status = 'paid'GROUP BY c.idORDER BY c.city, place;
textexample output
   city    |  name   | revenue | place-----------+---------+---------+------- Samarkand | Dilnoza |  640.00 |     1 Tashkent  | Aziz    | 1435.00 |     1 Tashkent  | Timur   |  300.00 |     2           | Malika  |  640.00 |     1(4 rows)

Windows are evaluated after WHERE, GROUP BY and HAVING, so they see the already grouped rows and can take an aggregate as an argument: ORDER BY sum(o.total). The reverse is not possible — a window function cannot be placed inside an aggregate.

Partition, order and frame

PARTITION BY splits the rows into independent partitions, like GROUP BY but without collapsing them; without it, all rows form one partition. ORDER BY inside OVER sets the order of rows within a partition. The window frame is the part of the partition that the function sees for the current row; ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is the current row and the two before it.

sql
SELECT customer_id, created_at::date AS day, total,       sum(total) OVER (PARTITION BY customer_id                        ORDER BY created_at                        ROWS BETWEEN 2 PRECEDING                             AND CURRENT ROW) AS last3FROM ordersWHERE customer_id IN (1, 2)ORDER BY customer_id, created_at;
The frame does not cross partition boundaries: for the first rows it contains fewer than three rows.

row_number, rank and dense_rank

These three functions number rows by the window’s ORDER BY and treat equal values differently:

totalrow_number()rank()dense_rank()
1200111
640222
640322
300443
150554
85665

row_number numbers rows consecutively, and tied rows get their numbers in arbitrary order. rank gives tied rows the same place and skips the following numbers; dense_rank leaves no gaps. The table is produced by this query:

sql
SELECT id, total,       row_number() OVER w,       rank() OVER w,       dense_rank() OVER wFROM ordersWHERE status = 'paid'WINDOW w AS (ORDER BY total DESC)ORDER BY total DESC, id;

WINDOW w AS (…) defines the window once, and the functions refer to it by name: OVER w. This is shorter and prevents inconsistencies between identical windows.

lag, lead and first_value

lag(x, n, default) takes the value from the row n positions earlier in the partition, and lead from the row n positions later; by default n is 1 and default is NULL. first_value, last_value and nth_value take the value from the first, last and nth row of the frame.

sql
-- the change in amount compared with the customer’s previous orderSELECT customer_id, created_at::date AS day, total,       total - lag(total) OVER w AS diffFROM ordersWINDOW w AS (PARTITION BY customer_id ORDER BY created_at)ORDER BY customer_id, created_at;

Running totals and moving averages

An ordinary aggregate with OVER becomes a window aggregate. With ORDER BY in the window it gives a running total; with a ROWS BETWEEN n PRECEDING AND CURRENT ROW frame, a moving value. With an empty OVER () it computes the total over all rows and places it next to each one.

sql
SELECT created_at::date AS day, total,       sum(total) OVER (ORDER BY created_at) AS running,       round(avg(total) OVER last3, 2) AS avg3,       round(100 * total / sum(total) OVER (), 1) AS pctFROM ordersWHERE status = 'paid'WINDOW last3 AS (ORDER BY created_at                 ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)ORDER BY created_at;

Window frames: ROWS, RANGE and GROUPS

ModeHow the frame is measured
ROWSin rows: 2 PRECEDING is the two rows before the current one
RANGEby the value of the ORDER BY key: interval '7 days' PRECEDING covers rows no earlier than 7 days back; rows with equal keys are included together
GROUPSin groups of rows with an equal ORDER BY key: 1 PRECEDING is the previous group

With ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the start of the partition to the last row equal to the current one. Without ORDER BY, the frame is the whole partition. That is why last_value with ORDER BY in the window returns the value of the current row (or the last of its peers), not the last one in the partition. If you need the last one, extend the frame to the end of the partition.

sql
SELECT customer_id, total,       last_value(total) OVER w AS wrong,       last_value(total) OVER whole AS last_totalFROM ordersWINDOW w AS (PARTITION BY customer_id ORDER BY created_at),       whole AS (w ROWS BETWEEN UNBOUNDED PRECEDING                   AND UNBOUNDED FOLLOWING)ORDER BY customer_id, created_at;

Filtering on a window result

Window functions are allowed only in the select list and in ORDER BY: they do not exist yet at the WHERE, GROUP BY and HAVING stages. To filter on a window result, compute it in a subquery or CTE and filter outside. The three largest orders of each customer:

sql
SELECT customer_id, id, totalFROM (    SELECT customer_id, id, total,           row_number() OVER (               PARTITION BY customer_id               ORDER BY total DESC, id           ) AS pos    FROM orders) AS rankedWHERE pos <= 3ORDER BY customer_id, pos;

Section sources

the section is written from these pages

NULL and three-valued logic

NULL means “value unknown”: it is neither zero nor an empty string. An ordinary comparison with NULL, even NULL = NULL, yields neither true nor false but NULL again, so the only way to test for a missing value is IS NULL.

sqlwrong
-- no rows: city = NULL is always NULLSELECT name FROM customers WHERE city = NULL;
sqlcorrect
SELECT name FROM customers WHERE city IS NULL;

Three-valued logic

SQL uses three-valued logic: true, false and NULL, meaning “unknown”. WHERE keeps a row only if the condition is true; false and NULL both discard it. AND and OR behave like this with NULL:

aba AND ba OR b
TRUENULLNULLTRUE
FALSENULLFALSENULL
NULLNULLNULLNULL
TRUEFALSEFALSETRUE

NOT applied to NULL is also NULL. This leads to a common trap: the condition city <> 'Tashkent' will not return Malika, whose city is not set, because NULL <> 'Tashkent' is NULL. If you need such rows, compare with IS DISTINCT FROM, which treats NULL as an ordinary value.

sql
-- Dilnoza, Malika and Olga; with <> Malika would be missingSELECT nameFROM customersWHERE city IS DISTINCT FROM 'Tashkent';

Testing for NULL

ExpressionResult
NULL = NULLNULL
7 <> NULLNULL
NULL IS NULLTRUE
1 IS DISTINCT FROM NULLTRUE
NULL IS NOT DISTINCT FROM NULLTRUE
NULL::boolean IS TRUEFALSE

IS TRUE, IS FALSE and IS UNKNOWN always return true or false, never NULL. The non-standard ISNULL and NOTNULL are equivalent to IS NULL and IS NOT NULL, but portable code avoids them.

COALESCE and NULLIF

COALESCE(a, b, …) returns the first argument that is not NULL and does not evaluate the rest, which makes it handy for substituting a default value in output. NULLIF(a, b) returns NULL if a equals b, and a otherwise.

sql
SELECT name,       COALESCE(city, 'unknown') AS city,       COALESCE(email, 'no email') AS emailFROM customers;

Division by zero is an error. Wrap a denominator that may be zero in NULLIF: in x / NULLIF(y, 0) a zero becomes NULL, so you get NULL instead of an error.

sql
SELECT 100 / NULLIF(0, 0) AS safe;

NOT IN and NULL

If the subquery behind NOT IN returns at least one NULL and there is no match, the result is NULL rather than true, and the row is left out of the output. In the sample data Malika has no city, so the following query finds nothing, even though there are no customers in Khiva or Nukus:

sqlwrong
-- empty result: the subquery also returned NULLSELECT cityFROM (VALUES ('Tashkent'), ('Khiva'), ('Nukus')) AS d(city)WHERE city NOT IN (SELECT city FROM customers);
sqlcorrect
SELECT d.cityFROM (VALUES ('Tashkent'), ('Khiva'), ('Nukus')) AS d(city)WHERE NOT EXISTS (    SELECT 1 FROM customers c WHERE c.city = d.city)ORDER BY d.city;

NOT EXISTS is true when the subquery returns no rows, and NULLs in the data do not affect it. For Malika, the condition c.city = d.city yields NULL, that is, “no match”.

NULL in aggregates, sorting and UNIQUE

  • Aggregates other than count(*) skip NULL, and over an empty set of rows they return NULL; see the section “Aggregate functions and GROUP BY”.
  • When sorting, NULL is greater than any value: it comes last with ASC and first with DESC. NULLS FIRST and NULLS LAST change the order; see the section “SELECT: selecting, filtering and sorting”.
  • A UNIQUE constraint allows several rows with NULL, because two NULLs are not considered equal. UNIQUE NULLS NOT DISTINCT (since PostgreSQL 15) changes this; see the section “Tables and constraints (DDL)”.

Section sources

the section is written from these pages

Changing data: INSERT, UPDATE, DELETE

INSERT adds rows, UPDATE changes values in the rows that match WHERE, and DELETE removes those rows. Without WHERE, UPDATE and DELETE affect every row in the table, so check the condition with a plain SELECT first.

sql
INSERT INTO customers (name, city, email)VALUES ('Rustam', 'Tashkent', 'rustam@example.com')RETURNING id;
textexample output
 id----  6(1 row) INSERT 0 1

You can omit the column list, but then the values follow the table’s column order and the query depends on that order. Columns missing from the list get their default value or NULL. The keyword DEFAULT in place of a value explicitly requests the default. At the end the server reports the number of rows inserted: INSERT 0 1, where the 0 is a leftover from old versions.

Insert several rows with a single command:

sql
INSERT INTO products (name, category_id, price) VALUES    ('Monitor', 1, 320),    ('Smartwatch', 1, 250);

Insert the result of a query with INSERT … SELECT, for example to add a product to an order at its current price:

sql
INSERT INTO order_items    (order_id, product_id, quantity, price)SELECT 7, id, 1, priceFROM productsWHERE name = 'Mouse';

RETURNING: what was inserted or changed

RETURNING returns the rows that the command inserted, updated or deleted, using the same syntax as a select list. This is how you get the id assigned by the database without a second query. RETURNING is a PostgreSQL extension and is not in the standard. Since PostgreSQL 18 it can use the aliases old and new: the values before and after the change.

sql
UPDATE productsSET price = price * 1.10WHERE category_id = 4RETURNING name,          old.price AS old_price,          new.price AS new_price;
textexample output
    name    | old_price | new_price------------+-----------+----------- Mouse      |     25.00 |     27.50 Charger    |     30.00 |     33.00 Headphones |    150.00 |    165.00(3 rows) UPDATE 3

Insert or update: ON CONFLICT

ON CONFLICT says what to do when an insert would violate uniqueness. DO NOTHING skips the row, and DO UPDATE updates the existing one; the proposed row is available as EXCLUDED. DO UPDATE requires you to name the conflict columns that have a unique index or constraint. The outcome is atomic: either an insert or an update is guaranteed to happen, even under concurrent load.

sql
INSERT INTO customers (name, city, email)VALUES ('Aziz Karimov', 'Tashkent', 'aziz@example.com')ON CONFLICT (email) DO UPDATESET name = EXCLUDED.name, city = EXCLUDED.city;

ON CONFLICT is a PostgreSQL extension; the standard solves a similar problem with MERGE, but the two commands are not interchangeable. ON CONFLICT (email) DO NOTHING will not insert a duplicate, and the server replies INSERT 0 0.

UPDATE and DELETE

sql
UPDATE ordersSET status = 'paid'WHERE id = 7;

SET lists only the columns to change; the others keep their values, and a new value can refer to the old one: price = price * 1.10. Only rows for which WHERE is true are changed. The server replies with the number of affected rows, such as UPDATE 1 or DELETE 3; zero is not an error but a sign that nothing matched the condition.

sql
DELETE FROM ordersWHERE status = 'cancelled';

The items of a cancelled order are deleted along with it, because order_items in the sample schema has ON DELETE CASCADE. To delete all rows of a table faster than DELETE without WHERE, use TRUNCATE order_items.

Data from another table: FROM and USING

UPDATE … FROM joins the table being updated with other tables and takes values and conditions from them. Each row being updated must match at most one joined row; otherwise it is unspecified which of them is used. DELETE … USING does the same for deletion. Both forms are PostgreSQL extensions; the standard alternative is a subquery in WHERE.

sql
-- items of new orders get the product’s current priceUPDATE order_items iSET price = p.priceFROM products p, orders oWHERE p.id = i.product_id  AND o.id = i.order_id  AND o.status = 'new';
sql
-- delete the items of cancelled ordersDELETE FROM order_items iUSING orders oWHERE o.id = i.order_id  AND o.status = 'cancelled';

MERGE: several actions in one command

MERGE joins a source with the target table and, for each row, runs the first matching WHEN branch: UPDATE, DELETE, INSERT or DO NOTHING. It is a standard command, available in PostgreSQL since version 15. Use it when one operation needs inserts, updates and deletes together. If another session may insert the same row concurrently, the documentation suggests INSERT … ON CONFLICT, which performs an UPDATE when a concurrent insert occurs.

sql
-- price list: update prices, add new productsMERGE INTO products pUSING (VALUES ('Mouse', 4, 27.00), ('Webcam', 4, 60.00))      AS s(name, category_id, price)ON p.name = s.nameWHEN MATCHED THEN    UPDATE SET price = s.priceWHEN NOT MATCHED THEN    INSERT (name, category_id, price)    VALUES (s.name, s.category_id, s.price);

The server replies MERGE 2: one row updated, one inserted. Each target row must match at most one source row, otherwise MERGE fails with an error.

How not to lose data

Check any change that touches many rows before you commit it:

  1. Run SELECT count(*) with the same WHERE as the planned change.
  2. Start a transaction with BEGIN.
  3. Run the UPDATE or DELETE and compare the number in the reply with the count(*) result.
  4. If they match, COMMIT; if not, ROLLBACK and the database stays as it was.
sql
BEGIN;SELECT count(*) FROM orders WHERE status = 'new';UPDATE orders SET status = 'cancelled' WHERE status = 'new';-- does the UPDATE count match count(*)? then COMMITROLLBACK;

Section sources

the section is written from these pages

Tables and constraints (DDL)

DDL is the set of commands that create and change the structure of a database: CREATE TABLE, ALTER TABLE, DROP TABLE. Constraints in a table definition make the database itself reject bad data: empty required fields, duplicates, references to rows that do not exist.

sql
CREATE TABLE reviews (    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    product_id bigint NOT NULL        REFERENCES products ON DELETE CASCADE,    customer_id bigint        REFERENCES customers ON DELETE SET NULL,    rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),    body text,    created_at timestamptz NOT NULL DEFAULT now(),    UNIQUE (product_id, customer_id));

A column has a name, a type and, optionally, a default value and constraints. Here bigint is an integer, smallint is a short integer, text is a string of any length and timestamptz is a point in time. All the types are covered in the PostgreSQL reference, in the section “Data model and types”. DEFAULT applies to every insert that does not supply a value for the column, so DEFAULT now() stores the time of the transaction that inserted the row. Without DEFAULT, such a column gets NULL.

GENERATED ALWAYS AS IDENTITY turns a column into a counter: the database assigns the next numbers to new rows, and the column automatically becomes NOT NULL. With ALWAYS you can insert your own value only with OVERRIDING SYSTEM VALUE; with BY DEFAULT you can do so freely. PRIMARY KEY makes values unique and required.

Constraints

ConstraintWhat it prevents
NOT NULLNULL in the column
CHECK (rating BETWEEN 1 AND 5)values for which the condition is false; NULL passes the check
UNIQUEduplicate values; several NULLs are allowed unless NULLS NOT DISTINCT is specified (since PostgreSQL 15)
PRIMARY KEYduplicates and NULL; a table can have only one primary key
REFERENCES (foreign key)values that do not exist in the referenced table

A single-column constraint is written next to the column, and a multi-column constraint goes on a separate line, like UNIQUE (product_id, customer_id). Give it a name yourself with CONSTRAINT rating_range CHECK (…); otherwise the database invents one, such as reviews_rating_check. PRIMARY KEY and UNIQUE automatically create a unique index. A foreign key does not create an index on the referencing column, but you usually want one for deletes from the referenced table; see the PostgreSQL reference, section “Indexes”.

Deleting a referenced row

ON DELETE defines what happens to references when the row they point to is deleted:

ActionWhat happens
NO ACTION (default)an error if references remain; the check can be deferred to the end of the transaction
RESTRICTan error immediately, with no deferral
CASCADEthe referencing rows are deleted too
SET NULLthe referencing rows get NULL
SET DEFAULTthe default value is set; it must also exist in the referenced table

CASCADE fits when the referencing row is part of the parent and cannot exist without it: an order item without an order, a review without a product. For independent objects, such as a customer and their orders, keep NO ACTION or RESTRICT so that deletion is explicit. SET NULL suits an optional reference: the review of a deleted customer stays, without an author. ON UPDATE defines the same for a change to the key.

Table and column names

Unquoted names are case-insensitive: PostgreSQL folds them to lower case, so FOO, foo and "foo" are the same name. A name in double quotes keeps its case and any characters: "Foo" is a different name, and you will always have to quote it. The SQL standard folds names to upper case, so for portability either always quote names or never do.

In practice, use lower-case names with underscores and no quotes (order_items), and upper-case keywords. Names longer than 63 bytes are truncated.

Changing a table: ALTER TABLE

sql
-- new column: existing rows get NULLALTER TABLE customers ADD COLUMN phone text;-- the constraint is checked against all rows at onceALTER TABLE orders    ADD CONSTRAINT total_not_negative CHECK (total >= 0);-- change a column’s typeALTER TABLE products ALTER COLUMN price TYPE numeric(12, 2);ALTER TABLE reviews RENAME COLUMN body TO comment;-- the column’s data is deleted along with itALTER TABLE customers DROP COLUMN phone;

A new column with a constant default is added quickly even to a large table, because the rows are not rewritten. A type change succeeds only if the old values convert implicitly to the new type; otherwise give the conversion expression in USING. If another table’s foreign key depends on the column, DROP COLUMN requires CASCADE.

Dropping a table

sql
DROP TABLE IF EXISTS reviews;

IF EXISTS avoids an error if the table is already gone. To empty a table but keep it, use DELETE or TRUNCATE. Without CASCADE (the default is RESTRICT), dropping a table that other tables reference fails with an error.

Section sources

the section is written from these pages

Transactions and isolation levels

A transaction groups several commands into one unit: either all of them take effect or none do, and the intermediate changes are invisible to other sessions until COMMIT. The isolation level determines what a transaction sees of changes made concurrently.

sql
BEGIN;UPDATE orders SET status = 'paid' WHERE id = 7;INSERT INTO order_items    (order_id, product_id, quantity, price)VALUES (7, 3, 1, 25);UPDATE orders SET total = total + 25 WHERE id = 7;COMMIT;

ROLLBACK instead of COMMIT undoes everything done since BEGIN. Without BEGIN, PostgreSQL runs each command in its own transaction and commits it immediately; this is autocommit. Some client libraries send BEGIN and COMMIT themselves, so check how yours behaves. The standard form of BEGIN is START TRANSACTION.

An error in any command aborts the transaction, and from then on it can only be rolled back. To keep working, use ROLLBACK TO SAVEPOINT to return to a savepoint set before the error; otherwise only a full ROLLBACK remains.

ACID

  • Atomicity: all the commands in a transaction take effect, or none do.
  • Consistency: the data satisfies the constraints; a transaction that violates them at commit time is rolled back.
  • Isolation: a transaction’s changes are invisible to concurrent transactions until it commits.
  • Durability: committed changes survive a system crash.

Savepoints: SAVEPOINT

SAVEPOINT sets a marker inside a transaction, and ROLLBACK TO SAVEPOINT undoes only what was done after it; earlier changes stay. A savepoint remains valid after you roll back to it, while rolling back to it removes all savepoints set later.

sql
BEGIN;UPDATE products SET price = price * 0.9WHERE category_id = 4;SAVEPOINT before_phones;UPDATE products SET price = price * 0.9WHERE category_id = 3;-- cancel the discount on phones, keep it on accessoriesROLLBACK TO SAVEPOINT before_phones;COMMIT;

Isolation levels

The SQL standard defines isolation levels in terms of phenomena that must not occur at a given level:

PhenomenonWhat happens
Dirty reada transaction reads uncommitted changes made by another
Nonrepeatable readreading a row again gives a different value because another transaction changed it and committed
Phantom readrepeating a query with the same condition returns a different set of rows
Serialization anomalythe result of concurrent transactions matches no order of running them one at a time
LevelWhat is possible in PostgreSQL
Read Uncommittedbehaves like Read Committed
Read Committed (default)nonrepeatable and phantom reads, serialization anomaly
Repeatable Readonly a serialization anomaly: the standard allows phantoms at this level, PostgreSQL does not
Serializablenone of the above

Set the level when the transaction starts, with BEGIN ISOLATION LEVEL REPEATABLE READ;, or with the SET TRANSACTION command. How PostgreSQL achieves this (MVCC and locks) is covered in the PostgreSQL reference, section “Transactions, MVCC and locks”.

Read Committed: two sessions

At the Read Committed level, each command sees the data committed before it began. So two identical SELECT statements in one transaction can return different results if another session commits a change between them:

At the Repeatable Read level, step 6 would return 640: the transaction sees a snapshot of the data taken at its first query.
  1. A starts a transaction: BEGIN.
  2. A reads the order total: SELECT total FROM orders WHERE id = 3 returns 640.
  3. B starts its own transaction: BEGIN.
  4. B changes the total: UPDATE orders SET total = 600 WHERE id = 3.
  5. B commits the change: COMMIT.
  6. A repeats the same SELECT and gets 600.
  7. A finishes the transaction: COMMIT.

Serialization failure

At the Repeatable Read and Serializable levels, a command that runs into a concurrent change fails with a serialization failure (SQLSTATE 40001). For example, if a row read by a Repeatable Read transaction was changed and committed by another, an attempt to change it fails like this:

textexample output
ERROR:  could not serialize access due to concurrent update

The application must abort such a transaction and retry it in full from the start: the second time it will see the committed change. Read-only transactions at Repeatable Read never get serialization failures. At Serializable, the same error with the message could not serialize access due to read/write dependencies among transactions means that the concurrent transactions would have produced a result impossible when run one at a time.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the error text and its SQLSTATE code. The five-character code does not depend on the message language and changes less often than the text; its first two characters give the error class. If there is no error but the result looks odd, run the query in parts on a small sample.

Order of checks

  1. Syntax and names: typos, quotes, table aliases.
  2. Types: a string instead of a number, integer division, the time zone for timestamptz.
  3. Constraints: NOT NULL, UNIQUE, CHECK, foreign keys — class 23 errors.
  4. Logic: FROM and joins first, then WHERE, then grouping — and run count(*) after each step.

value too long for type character varying(5)

Cause: a string is longer than the limit n of a varchar(n) column — for example, the promo code SUMMER2026 in the promo_codes.code column of type varchar(5). The limit counts characters, not bytes. An explicit cast 'SUMMER2026'::varchar(5) silently truncates the string, while an insert into the column raises this error.

sql
-- length of the value that does not fitSELECT length('SUMMER2026');
  • Raise the column limit: ALTER TABLE promo_codes ALTER COLUMN code TYPE varchar(20).
  • Or store text: in PostgreSQL it is no slower than varchar(n), and the documentation recommends text or varchar without a length when there is no real limit.

violates foreign key constraint

Cause: an insert or update refers to a row that does not exist in the referenced table — for example, an order for a customer with a nonexistent id. The message names the table and the constraint (orders_customer_id_fkey), and the DETAIL line gives the key: Key (customer_id)=(999) is not present in table "customers". Check whether the row exists:

sql
SELECT id FROM customers WHERE id = 999;
  • Insert the parent row first, then the referencing one — preferably in a single transaction.
  • If the error occurs when deleting a parent, decide what to do with the references: delete them, set them to NULL or forbid the deletion (ON DELETE, see “Tables and constraints (DDL)”).

Column not in GROUP BY: grouping_error (42803)

Cause: in a query with grouping, a select-list column is neither in GROUP BY nor inside an aggregate — the group has many values of it.

sqlnot allowed
-- not allowed: c.name is neither in GROUP BY nor in an aggregateSELECT c.city, c.name, count(*)FROM customers cJOIN orders o ON o.customer_id = c.idGROUP BY c.city;
  • Add the column to GROUP BY: GROUP BY c.city, c.name.
  • Or group by the primary key — GROUP BY c.id — and select any columns of that table.
  • Or wrap the column in an aggregate: string_agg(c.name, ', ').

Duplicate key: unique_violation (23505)

Cause: the value already exists in a column with UNIQUE or PRIMARY KEY — for example, a second customer with the same email. The message names the constraint, and DETAIL shows the duplicated key.

sql
SELECT id, nameFROM customersWHERE email = 'olga@example.com';
  • If the row already exists and that is fine, use INSERT … ON CONFLICT (email) DO NOTHING or DO UPDATE (see “Changing data: INSERT, UPDATE, DELETE”).
  • If the duplicate is a data error, fix the value before inserting.

NULL in a required column: not_null_violation (23502)

Cause: no value was supplied for a NOT NULL column that has no default — it is missing from the INSERT column list or NULL was passed.

  • Pass the value explicitly or give the column a DEFAULT.
  • Check whether a LEFT JOIN or a subquery in INSERT … SELECT produced the NULL.

Column not found: undefined_column (42703)

Usually one of four causes:

  • A typo in the name.
  • An alias from the select list is used in WHERE, where it does not exist yet.
  • A string is in double quotes, but double quotes denote an identifier, not a string.
  • The column was created in quotes with capital letters, but the query writes it without quotes.
sqlnot allowed
-- not allowed: "Tashkent" is a column name, not a stringSELECT name FROM customers WHERE city = "Tashkent";
sqlcorrect
SELECT name FROM customers WHERE city = 'Tashkent';

Ambiguous column: ambiguous_column (42702)

Cause: a column with that name exists in several tables of the query — in the sample schema almost every table has id. Qualify it with the table name or alias:

sqlcorrect
SELECT o.id, c.nameFROM orders oJOIN customers c ON c.id = o.customer_id;

Subquery returned more than one row: cardinality_violation (21000)

Cause: a scalar subquery — one used in place of a value — returned several rows. Find the keys that have more than one row:

sql
-- customers with more than one orderSELECT customer_id, count(*)FROM ordersGROUP BY customer_idHAVING count(*) > 1;

Narrow the subquery with a condition, reduce it with an aggregate (max, count) or replace it with IN or EXISTS (see “Subqueries and CTEs (WITH)”).

Division by zero: division_by_zero (22012)

Cause: the denominator is zero. Wrap it in NULLIF(denominator, 0) so the result becomes NULL (see “NULL and three-valued logic”).

Silent errors

The query runs, but the result is wrong:

SymptomCauseWhat to do
Totals are too high after a JOINa one-to-many join repeated rowssum before joining; compare count(*) before and after
LEFT JOIN lost rows with no matchthe condition on the right table is in WHEREmove it to ON
NOT IN returned an empty resultthe subquery returned NULLuse NOT EXISTS
WHERE col = NULL finds nothingcomparison with NULL gives NULLwrite col IS NULL
<> drops rows with NULLNULL <> 'x' is also NULLuse IS DISTINCT FROM
5 / 2 gives 2integer division discards the fractional part5::numeric / 2
Row order changes between runsno ORDER BY, or it is ambiguousadd a unique key as the last sort column
Orders “slipped” into the neighbouring monthdate_trunc on timestamptz uses the session time zoneset TimeZone or the third argument of date_trunc

If the query runs but is slow, that is a matter of the execution plan and indexes: see the PostgreSQL reference, “Performance and EXPLAIN”.

Section sources

the section is written from these pages

Standards and their status

The SQL language is defined by the international standard ISO/IEC 9075, “Database Language SQL”. The current edition is SQL:2023; each edition supersedes the previous one, so claims of conformance to older editions carry no official weight. This reference describes SQL as implemented in PostgreSQL 18.

Before SQL:2023, each superseding the last, came SQL:2016, SQL:2011, SQL:2008, SQL:2006, SQL:2003, SQL:1999 and SQL-92. The standard is divided into parts; the PostgreSQL core covers parts 1, 2, 9, 11 and 14:

ISO/IEC 9075 partMeaningIn PostgreSQL
1 Framework (SQL/Framework)basic conceptsin the core
2 Foundation (SQL/Foundation)the foundation: the main part of the languagein the core
3 Call Level Interface (SQL/CLI)call-level interfaceODBC driver
4 Persistent Stored Modules (SQL/PSM)stored modulesno
9 Management of External Data (SQL/MED)management of external datain the core
10 Object Language Bindings (SQL/OLB)object language bindingsno
11 Information and Definition Schemas (SQL/Schemata)information schemasin the core
13 Routines and Types using the Java Language (SQL/JRT)routines and types in JavaPL/Java module
14 XML-related specifications (SQL/XML)XML-related specificationsin the core
15 Multi-dimensional arrays (SQL/MDA)multi-dimensional arraysno
16 Property Graph Queries (SQL/PGQ)property graph queriesno

Conformance to parts 3 and 13 is not currently tested. Part numbers missing from the table do not exist in the standard or are no longer used.

Of the 177 mandatory Core features of SQL:2023, PostgreSQL 18 supports at least 170. According to the documentation, at the time of writing no database system claimed full conformance to Core SQL:2023. Each has its own set of deviations and extensions; the ClickHouse dialect is described in the ClickHouse reference.

What PostgreSQL has added from the standard

Standard features that appeared in recent PostgreSQL releases, with their identifiers:

  • ANY_VALUE — an aggregate that returns any value from the group (T626), since PostgreSQL 16.
  • Integers in hexadecimal, octal and binary notation — 0x42F, 0o273, 0b100101 (T661), since PostgreSQL 16.
  • Underscores in numbers — 1_000_000 (T662), since PostgreSQL 16.
  • The SQL/JSON constructors JSON_ARRAY, JSON_OBJECT, JSON_ARRAYAGG and JSON_OBJECTAGG (T811 and related), since PostgreSQL 16.
  • JSON_TABLE, which turns JSON into a table, and the SQL/JSON query functions JSON_EXISTS, JSON_QUERY and JSON_VALUE (T821, T828 and related), since PostgreSQL 17.

Outdated documents that are still quoted

SQL-92 split conformance into three levels: Entry, Intermediate and Full. Most database systems that claimed conformance reached only Entry. Since SQL:1999 the levels have been replaced by a set of individual features with identifiers. References to SQL-92, SQL:1999 or SQL:2016 in product descriptions and textbooks say nothing about conformance to the current edition.

How to read the list of standard features

Appendix D of the PostgreSQL documentation keeps two lists: supported features (D.1) and unsupported ones (D.2). Each feature has an identifier, a Core mark for mandatory ones and a description. For example, E011 is numeric data types, E051 is the basic SELECT query, F312 is MERGE, T121 is WITH without RECURSIVE, and T615 is LEAD and LAG. An identifier with a hyphen is a subfeature: E011-01 covers the INTEGER and SMALLINT types.

If a subfeature is not supported, the whole feature is listed in D.2 even when its other parts work. For example, D.2 lists T616, the null treatment option in LEAD and LAG, and F866, FETCH FIRST … PERCENT. It also lists T618, NTH_VALUE, with a note that the function exists but not all variants. The lists are approximate; the main text of the documentation is the most accurate source on behaviour.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “SQL” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61