PostgreSQL Syntax

Updated · 5 min read

Every task from the syntax reference, written for PostgreSQL, on one page. Use it as a quick lookup when you know what you want to do and need the PostgreSQL spelling. Rows marked standard use SQL that other databases share. For the other databases, see the topic pages linked from the SQL Syntax by Database.

How these were checked: every PostgreSQL and SQLite form on this page was run (PostgreSQL 18 and SQLite 3.54). MySQL, SQL Server and Oracle forms follow each database's current documentation (MySQL 8.4, SQL Server 2022 and later, Oracle AI Database 26ai); version notes such as "8.0.19+" mark features that older releases lack.

Querying

TaskPostgreSQL
First 10 rowsSELECT * FROM t ORDER BY id LIMIT 10;standard
Skip 20 rows, take 10SELECT * FROM t ORDER BY id OFFSET 20 LIMIT 10;standard
Case-insensitive matchSELECT * FROM t WHERE name ILIKE 'nav%';dialect
Rows with a missing valueSELECT * FROM t WHERE email IS NULL;standard
Groups with a conditionSELECT city, count(*) FROM t GROUP BY city HAVING count(*) > 1;standard
Full outer joinSELECT * FROM a FULL JOIN b ON b.id = a.id;standard
Rows in one table but not anotherSELECT id FROM a EXCEPT SELECT id FROM b;standard
Quote a name with a spaceSELECT "first name" FROM t;standard

All five databases side by side: Syntax: Querying.

Changing Data

TaskPostgreSQL
Insert several rowsINSERT INTO t (id, name) VALUES (1, 'a'), (2, 'b');standard
Get the new id backINSERT INTO t (name) VALUES ('a') RETURNING id;dialect
Update from another tableUPDATE t SET name = s.name FROM s WHERE s.id = t.id;dialect
Insert or update (upsert)INSERT INTO t (id, name) VALUES (1, 'a') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;dialect
Delete all rows quicklyTRUNCATE TABLE t;dialect
Copy rows into a new tableCREATE TABLE t2 AS SELECT * FROM t;dialect
Load a CSV file\copy t FROM 'file.csv' WITH (FORMAT csv, HEADER true)dialect

All five databases side by side: Syntax: Changing Data.

Tables and Keys

TaskPostgreSQL
Auto-numbered primary keyid INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEYstandard
Money columnfee_usd NUMERIC(8,2)standard
Text columnname VARCHAR(40)standard
True/false columnis_active BOOLEANstandard
Foreign key with cascadestudent_id INTEGER REFERENCES students (student_id) ON DELETE CASCADEstandard
Check constraintCHECK (fee_usd > 0)standard
Create table if missingCREATE TABLE IF NOT EXISTS t (id INTEGER);dialect
Add a columnALTER TABLE t ADD COLUMN note TEXT;standard
Rename a columnALTER TABLE t RENAME COLUMN note TO memo;standard
Create an indexCREATE INDEX t_name_idx ON t (name);dialect
Create or replace a viewCREATE OR REPLACE VIEW v AS SELECT id FROM t;dialect

All five databases side by side: Syntax: Tables and Keys.

Functions

TaskPostgreSQL
Join textfirst_name || ' ' || last_namestandard
Text lengthlength(name)dialect
Part of a stringsubstring(name FROM 1 FOR 3)standard
Replace NULLCOALESCE(email, 'none')standard
Round to centsround(x, 2)dialect
Today's dateCURRENT_DATEstandard
Add 30 daysd + 30dialect
Days between datesd2 - d1dialect
Year of a dateEXTRACT(YEAR FROM d)standard
Format a dateto_char(d, 'YYYY-MM-DD')dialect
Convert text to a numberCAST('450.00' AS NUMERIC)standard
If / elseCASE WHEN x > 0 THEN 'yes' ELSE 'no' ENDstandard
Join values from many rowsstring_agg(name, ', ' ORDER BY name)standard

All five databases side by side: Syntax: Functions.

Advanced SQL

TaskPostgreSQL
Common table expressionWITH x AS (SELECT 1 AS n) SELECT n FROM x;standard
Recursive CTEWITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 3) SELECT x FROM n;standard
Rank rowsRANK() OVER (ORDER BY fee DESC)standard
Running totalsum(x) OVER (ORDER BY d)standard
Conditional countcount(*) FILTER (WHERE method = 'card')standard
SubtotalsGROUP BY ROLLUP (a, b)standard
Read a JSON field as textdata ->> 'name'dialect
Full-text searchto_tsvector('english', body) @@ to_tsquery('english', 'join')dialect
A function languageCREATE FUNCTION f() RETURNS int LANGUAGE plpgsql AS $$ BEGIN RETURN 1; END $$;dialect

All five databases side by side: Syntax: Advanced SQL.

Administration

TaskPostgreSQL
Start a transactionBEGIN;standard
SavepointSAVEPOINT s; ROLLBACK TO SAVEPOINT s;standard
Set the isolation levelSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;standard
Show a query planEXPLAIN (ANALYZE) SELECT ...;dialect
Create a loginCREATE ROLE app LOGIN PASSWORD 'secret';dialect
Grant read accessGRANT SELECT ON payments TO app;standard
Back up a databasepg_dump --format=custom --file=db.dump dbnamedialect
Parameter placeholder in app code$1, $2 (node-postgres); %s (psycopg); ? (JDBC)dialect
Server versionSELECT version();dialect

All five databases side by side: Syntax: Administration.

Was this tutorial helpful?