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.
SELECT customer_id, sum(total) AS revenueFROM ordersWHERE status = 'paid'GROUP BY customer_idHAVING sum(total) > 500ORDER BY revenue DESC, customer_idLIMIT 2; customer_id | revenue-------------+--------- 1 | 1435.00 2 | 640.00(2 rows)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:
FROMandJOIN— the rows are assembled; several tables separated by commas give every combination of rows.WHERE— only rows for which the condition is true remain.GROUP BY— rows with equal values are collapsed into groups and aggregates are computed;HAVINGdiscards unwanted groups.- Select list — the result columns and window functions are evaluated, and aliases appear.
DISTINCT— duplicate rows are removed.UNION,INTERSECT,EXCEPT— the results of severalSELECTs are combined into one.ORDER BY— rows are sorted; without it the order is whatever is fastest for the system.LIMIT,OFFSETorFETCH 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:
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:
| Task | SQL standard | PostgreSQL |
|---|---|---|
| First 10 rows | FETCH FIRST 10 ROWS ONLY | the same, and LIMIT 10 |
| Convert a type | CAST(price AS integer) | the same, and price::integer |
| Case-insensitive pattern | only LIKE | ILIKE |
| First row of each group | none | DISTINCT ON (customer_id) |
Modify data inside WITH | none | WITH d AS (DELETE … RETURNING *) |
Subquery in FROM without an alias | not allowed | allowed 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.
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));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- SELECTpostgresql.org/docs/18/sql-select.html(opens in a new tab)
- 7.1. Overviewpostgresql.org/docs/18/queries-overview.html(opens in a new tab)
- 2.2. Conceptspostgresql.org/docs/18/tutorial-concepts.html(opens in a new tab)
- 4.2. Value Expressionspostgresql.org/docs/18/sql-expressions.html(opens in a new tab)
- 9.7. Pattern Matchingpostgresql.org/docs/18/functions-matching.html(opens in a new tab)