Questions 1–20 of 100 · 0 of 20 on this page marked learned
1.postgresql-0001Easyfresher
How do text, varchar(n) and char(n) behave in PostgreSQL, and which should a new column use?
text and varchar without a length are the same storage type with no limit. varchar(n) rejects longer values with an error, and char(n) pads values with spaces to n characters, which causes surprising comparisons. Most columns should be text, with a CHECK constraint if a length rule is a business rule.
Full answer
Setup for the example:
sql
CREATE TABLE codes (
t text,
v varchar(5),
c char(5)
);
INSERT INTO codes VALUES ('ab', 'ab', 'ab');
sql
SELECT length(t) AS t_len, length(v) AS v_len, octet_length(c) AS c_bytes, c = 'ab' AS c_equal, '[' || c || ']' AS c_concat FROM codes;
ERROR: value too long for type character varying(5)
The char(5) value is stored padded to five bytes, yet compares equal to 'ab' and loses its padding when concatenated, because trailing spaces are treated as insignificant for char. Inserting seven characters into varchar(5) fails with an error naming the type. There is no performance advantage to varchar(n) or char(n) in PostgreSQL; changing a length limit later needs an ALTER, while a CHECK (length(col) <= n) is easier to change and can carry a clear name.
sql
CREATE TABLE codes (
t text,
v varchar(5),
c char(5)
);
INSERT INTO codes VALUES ('ab', 'ab', 'ab');
SELECT length(t) AS t_len, length(v) AS v_len, octet_length(c) AS c_bytes, c = 'ab' AS c_equal, '[' || c || ']' AS c_concat FROM codes;
INSERT INTO codes (v) VALUES ('toolong');
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
text and varchar have the same storage
varchar(n) errors on longer values
char(n) pads with spaces
No speed benefit to length limits
Use CHECK constraints for business length rules
Common mistakes
Using char(n) for variable-length codes
Picking varchar(255) by habit
Follow-ups
How would you enforce a maximum length that may change?
How does citext differ from text?
Tips
Recommend text plus CHECK
2.postgresql-0002Easyfresher
Should a new table use SERIAL or an IDENTITY column for its primary key?
Use GENERATED ALWAYS AS IDENTITY (or BY DEFAULT) in new tables. It is SQL-standard, ties the sequence to the column, and with ALWAYS rejects manual ids unless OVERRIDING SYSTEM VALUE is given. SERIAL is older shorthand that creates a separate sequence and a default, with looser ownership and permission handling.
Full answer
Tables and rows used here:
sql
CREATE TABLE tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subject text NOT NULL
);
CREATE TABLE legacy (
id serial PRIMARY KEY,
subject text NOT NULL
);
INSERT INTO tickets (id, subject) VALUES (100, 'manual id');
Result on PostgreSQL 17:
text
ERROR: cannot insert a non-DEFAULT value into column "id"
sql
INSERT INTO tickets (id, subject) OVERRIDING SYSTEM VALUE VALUES (100, 'imported') RETURNING id;
Result:
text
id
-----
100
(1 row)
sql
INSERT INTO legacy (id, subject) VALUES (1, 'manual'); SELECT column_name, column_default, is_identity FROM information_schema.columns WHERE table_name IN ('tickets', 'legacy') AND column_name = 'id' ORDER BY table_name;
Output:
text
column_name | column_default | is_identity
-------------+------------------------------------+-------------
id | nextval('legacy_id_seq'::regclass) | NO
id | NULL | YES
(2 rows)
The identity column numbers rows automatically. A manual id is rejected because the column is GENERATED ALWAYS, which protects against code accidentally bypassing the sequence; data imports can still use OVERRIDING SYSTEM VALUE. The serial column accepted a manual id silently, and its definition is just a default calling nextval, which is why information_schema shows it as not an identity. After importing explicit ids, move the sequence forward (ALTER TABLE ... ALTER COLUMN id RESTART WITH ...) so later inserts do not collide.
sql
CREATE TABLE tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subject text NOT NULL
);
CREATE TABLE legacy (
id serial PRIMARY KEY,
subject text NOT NULL
);
INSERT INTO tickets (subject) VALUES ('login fails'), ('slow page') RETURNING id, subject;
INSERT INTO tickets (id, subject) VALUES (100, 'manual id');
INSERT INTO tickets (id, subject) OVERRIDING SYSTEM VALUE VALUES (100, 'imported') RETURNING id;
INSERT INTO legacy (id, subject) VALUES (1, 'manual'); SELECT column_name, column_default, is_identity FROM information_schema.columns WHERE table_name IN ('tickets', 'legacy') AND column_name = 'id' ORDER BY table_name;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Prefer IDENTITY in new tables
ALWAYS rejects manual values
OVERRIDING SYSTEM VALUE for imports
SERIAL is a default plus a sequence
Reset sequences after explicit-id imports
Common mistakes
Using serial in new designs
Importing ids without moving the sequence
Follow-ups
What is the difference in behaviour between ALWAYS and BY DEFAULT?
Why use bigint for ids?
Tips
Show the manual-id error
3.postgresql-0003Easyfresher
Why does integer division return 2 for 5 / 2 in PostgreSQL, and how do you get 2.5?
Dividing two integers produces an integer, truncating toward zero. Cast one side to numeric (5::numeric / 2) or use a decimal literal (5.0 / 2) to get a fractional result. round(value, 2) works on numeric, and numeric is exact while double precision is approximate.
SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal, 0.1::numeric + 0.2 = 0.3 AS numeric_equal;
Output:
text
float_equal | numeric_equal
-------------+---------------
f | t
(1 row)
The first row shows truncation: 5 / 2 is 2, while either numeric form gives 2.5000000000000000, because numeric division keeps extra scale. Negative results truncate toward zero, so -7 / 2 is -3. In the percentage query, writing 100.0 first turns the whole expression numeric, so the percentages are correct, while the plain ratio column is 0 for most rows. Floating-point addition misses 0.3 by a tiny amount, while numeric is exact, which is why money and percentages that must match should use numeric.
sql
CREATE TABLE scores (student text, correct int, total int);
INSERT INTO scores VALUES ('Asha', 5, 8), ('Ben', 7, 8), ('Chen', -7, 2);
SELECT 5 / 2 AS int_div, 5::numeric / 2 AS num_div, 5.0 / 2 AS literal_div, -7 / 2 AS neg_div, 7 % 3 AS remainder;
SELECT student, correct / total AS wrong_ratio, round(100.0 * correct / total, 1) AS pct FROM scores ORDER BY student;
SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal, 0.1::numeric + 0.2 = 0.3 AS numeric_equal;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
int / int truncates
Cast or use a decimal literal
Truncation is toward zero
round() on numeric for display
numeric is exact, float is approximate
Common mistakes
Computing ratios with integer columns
Using float for money
Follow-ups
How does numeric scale work in division?
When is double precision the right choice?
Tips
Put the decimal first
4.postgresql-0004Easyfresher
How do NULLs behave in comparisons, and how do COALESCE, NULLIF and IS DISTINCT FROM help?
Any comparison with NULL using = or <> yields NULL, so WHERE treats it as false. IS NULL and IS DISTINCT FROM compare NULL safely. COALESCE returns the first non-null argument, and NULLIF(a, b) returns NULL when a equals b, which is handy to avoid division by zero.
SELECT name FROM contacts WHERE phone <> '98450' ORDER BY name;
Result:
text
name
------
Chen
(1 row)
sql
SELECT name FROM contacts WHERE phone IS DISTINCT FROM '98450' ORDER BY name;
Output:
text
name
------
Ben
Chen
(2 rows)
sql
SELECT name, COALESCE(NULLIF(phone, ''), 'no phone') AS phone, COALESCE(discount, 0) AS discount, 100 / NULLIF(orders, 0) AS per_order FROM contacts ORDER BY name;
PostgreSQL returns:
text
name | phone | discount | per_order
------+----------+----------+-----------
Asha | 98450 | 10 | 25
Ben | no phone | 0 | NULL
Chen | no phone | 0 | 50
(3 rows)
The first query misses Ben, because NULL <> '98450' is NULL rather than true. IS DISTINCT FROM treats NULL as a comparable value and returns both Ben and Chen. In the last query, NULLIF turns Chen's empty string into NULL so COALESCE can supply a label for both missing phones, and NULLIF(orders, 0) makes Ben's division return NULL instead of raising 'division by zero'. Storing either NULL or empty strings for missing values, not both, avoids needing the NULLIF in the first place.
sql
CREATE TABLE contacts (name text, phone text, discount int, orders int);
INSERT INTO contacts VALUES
('Asha', '98450', 10, 4),
('Ben', NULL, NULL, 0),
('Chen', '', 0, 2);
SELECT name FROM contacts WHERE phone <> '98450' ORDER BY name;
SELECT name FROM contacts WHERE phone IS DISTINCT FROM '98450' ORDER BY name;
SELECT name, COALESCE(NULLIF(phone, ''), 'no phone') AS phone, COALESCE(discount, 0) AS discount, 100 / NULLIF(orders, 0) AS per_order FROM contacts ORDER BY name;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
= and <> with NULL give NULL
WHERE drops NULL results
IS DISTINCT FROM is null-safe
COALESCE supplies defaults
NULLIF avoids division by zero
Common mistakes
Writing = NULL
Mixing empty strings and NULL for missing data
Follow-ups
How do NULLs sort by default in PostgreSQL?
How does COUNT(col) treat NULLs?
Tips
Show the missing row
5.postgresql-0005Easyfresher
How do unique constraints treat NULLs, and what does NULLS NOT DISTINCT change in PostgreSQL 15+?
By default a UNIQUE constraint allows many rows with NULL in the column, because NULLs are not equal to each other. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT, which treats NULLs as equal so only one NULL is allowed. On older versions, a partial unique index on an expression gives the same effect.
Full answer
Sample schema and data:
sql
CREATE TABLE devices (serial_no text UNIQUE, owner text);
CREATE TABLE badges (code text UNIQUE NULLS NOT DISTINCT, owner text);
sql
INSERT INTO devices VALUES (NULL, 'Asha'), (NULL, 'Ben'); SELECT count(*) AS null_serials FROM devices WHERE serial_no IS NULL;
Output:
text
null_serials
--------------
2
(1 row)
sql
INSERT INTO badges VALUES (NULL, 'Asha');
PostgreSQL returns:
text
INSERT 0 1
sql
INSERT INTO badges VALUES (NULL, 'Ben');
Result on PostgreSQL 17:
text
ERROR: duplicate key value violates unique constraint "badges_code_key"
Two devices with no serial number are accepted, since the default rule treats each NULL as distinct. The badges table accepts the first NULL code but rejects the second with a unique-violation error naming the constraint. Which behaviour is right depends on meaning: an unknown serial number should not block other unknowns, but a rule such as 'at most one active badge without a code' needs NULLS NOT DISTINCT or, on PostgreSQL 14 and earlier, CREATE UNIQUE INDEX ... ON badges ((code IS NULL)) WHERE code IS NULL.
sql
CREATE TABLE devices (serial_no text UNIQUE, owner text);
CREATE TABLE badges (code text UNIQUE NULLS NOT DISTINCT, owner text);
INSERT INTO devices VALUES (NULL, 'Asha'), (NULL, 'Ben'); SELECT count(*) AS null_serials FROM devices WHERE serial_no IS NULL;
INSERT INTO badges VALUES (NULL, 'Asha');
INSERT INTO badges VALUES (NULL, 'Ben');
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
UNIQUE allows multiple NULLs by default
NULLS NOT DISTINCT allows only one
Available from PostgreSQL 15
Partial indexes emulate it on older versions
Choose by what NULL means
Common mistakes
Assuming UNIQUE blocks duplicate NULLs
Using sentinel strings instead of NULL
Follow-ups
How would you allow one NULL per customer?
How do composite unique keys treat NULLs?
Tips
Mention the version
6.postgresql-0006Easyfresher
Write a foreign key that deletes child rows with the parent, and show what happens without it.
A foreign key with ON DELETE CASCADE deletes child rows when the parent row is deleted. The default, NO ACTION, raises an error if children exist, and ON DELETE SET NULL clears the reference. Choose per relationship: order lines belong to their order, but orders should usually not vanish with a customer.
Full answer
Setup for the example:
sql
CREATE TABLE orders (id int PRIMARY KEY, customer text);
CREATE TABLE order_lines (
order_id int REFERENCES orders(id) ON DELETE CASCADE,
item text
);
CREATE TABLE invoices (
id int PRIMARY KEY,
order_id int REFERENCES orders(id)
);
INSERT INTO orders VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO order_lines VALUES (1, 'pen'), (1, 'ink'), (2, 'pad');
INSERT INTO invoices VALUES (10, 2);
sql
DELETE FROM orders WHERE id = 1; SELECT order_id, item FROM order_lines ORDER BY item;
PostgreSQL returns:
text
order_id | item
----------+------
2 | pad
(1 row)
sql
DELETE FROM orders WHERE id = 2;
Result on PostgreSQL 17:
text
ERROR: update or delete on table "orders" violates foreign key constraint "invoices_order_id_fkey" on table "invoices"
Deleting order 1 also removed its two lines, leaving only order 2's line. Deleting order 2 fails, because an invoice still refers to it and that foreign key uses the default NO ACTION rule; the error names the constraint and the referencing table. PostgreSQL does not index foreign-key columns automatically, so add an index on order_lines(order_id): without it, each parent delete scans the child table to find matching rows.
sql
CREATE TABLE orders (id int PRIMARY KEY, customer text);
CREATE TABLE order_lines (
order_id int REFERENCES orders(id) ON DELETE CASCADE,
item text
);
CREATE TABLE invoices (
id int PRIMARY KEY,
order_id int REFERENCES orders(id)
);
INSERT INTO orders VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO order_lines VALUES (1, 'pen'), (1, 'ink'), (2, 'pad');
INSERT INTO invoices VALUES (10, 2);
DELETE FROM orders WHERE id = 1; SELECT order_id, item FROM order_lines ORDER BY item;
DELETE FROM orders WHERE id = 2;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
ON DELETE CASCADE removes children
Default NO ACTION blocks deletes
SET NULL clears references
Index foreign-key columns yourself
Choose the rule per relationship
Common mistakes
Cascading deletes through business records
Forgetting the index on the referencing column
Follow-ups
When would you use ON DELETE RESTRICT?
How do deferrable foreign keys work?
Tips
Mention the missing index
7.postgresql-0007Easyfresher
How do schemas and search_path decide which table a query uses?
A schema is a namespace inside a database. Unqualified names are looked up in the schemas listed in search_path, in order, and the first match wins. Qualify names (sales.orders) in scripts and functions to avoid surprises, and set search_path deliberately for each application role.
Full answer
Tables and rows used here:
sql
CREATE SCHEMA sales;
CREATE SCHEMA archive;
CREATE TABLE sales.orders (id int, note text);
CREATE TABLE archive.orders (id int, note text);
INSERT INTO sales.orders VALUES (1, 'current');
INSERT INTO archive.orders VALUES (1, 'old');
sql
SET search_path TO sales, archive; SELECT note FROM orders;
Result on PostgreSQL 17:
text
note
---------
current
(1 row)
sql
SET search_path TO archive, sales; SELECT note FROM orders;
Result:
text
note
------
old
(1 row)
sql
SELECT (SELECT note FROM sales.orders) AS qualified_sales, current_schemas(false)::text AS path;
Output:
text
qualified_sales | path
-----------------+-----------------
current | {archive,sales}
(1 row)
sql
DROP SCHEMA sales CASCADE; DROP SCHEMA archive CASCADE;
PostgreSQL returns:
text
NOTICE: drop cascades to table sales.orders
NOTICE: drop cascades to table orders
DROP SCHEMA
The same unqualified query reads a different table depending on the order of search_path. The qualified name always reads sales.orders. current_schemas(false) shows the effective path without the implicit pg_catalog. Because a schema earlier in the path can shadow a table or function with the same name, functions marked SECURITY DEFINER should set their own search_path, and applications should not let untrusted users create objects in schemas on their path. The last run removes the two demo schemas.
sql
CREATE SCHEMA sales;
CREATE SCHEMA archive;
CREATE TABLE sales.orders (id int, note text);
CREATE TABLE archive.orders (id int, note text);
INSERT INTO sales.orders VALUES (1, 'current');
INSERT INTO archive.orders VALUES (1, 'old');
SET search_path TO sales, archive; SELECT note FROM orders;
SET search_path TO archive, sales; SELECT note FROM orders;
SELECT (SELECT note FROM sales.orders) AS qualified_sales, current_schemas(false)::text AS path;
DROP SCHEMA sales CASCADE; DROP SCHEMA archive CASCADE;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Schemas are namespaces
search_path order decides unqualified names
Qualify names in scripts
Shadowing is a security concern
Set search_path per role
Common mistakes
Relying on the default public schema for everything
SECURITY DEFINER functions without a fixed search_path
Follow-ups
Why did PostgreSQL 15 change public schema permissions?
How would you use schemas for multi-tenant data?
Tips
Show the order effect
8.postgresql-0008Easyfresher
Extract parts of dates and compute ages and intervals in PostgreSQL.
extract(field FROM value) returns parts such as year, month or dow; date_trunc rounds down to a unit such as month. Subtracting two dates gives an integer number of days, subtracting timestamps gives an interval, and age() gives a symbolic years-months-days interval. Adding an interval moves a date by calendar units.
Full answer
Test data:
sql
CREATE TABLE members (name text, born date, joined timestamp);
INSERT INTO members VALUES
('Asha', '1998-02-14', '2025-01-31 09:15'),
('Ben', '2004-11-30', '2026-03-05 18:40');
sql
SELECT name, extract(year FROM born) AS birth_year, extract(dow FROM born) AS weekday, date_trunc('month', joined) AS join_month FROM members ORDER BY name;
SELECT name, age(date '2026-12-04', born) AS age, date '2026-12-04' - born AS days_alive FROM members ORDER BY name;
Output:
text
name | age | days_alive
------+-------------------------+------------
Asha | 28 years 9 mons 18 days | 10520
Ben | 22 years 4 days | 8039
(2 rows)
sql
SELECT date '2025-01-31' + interval '1 month' AS plus_month, timestamp '2026-03-05 18:40' - timestamp '2026-03-01 08:00' AS gap;
PostgreSQL returns:
text
plus_month | gap
---------------------+-----------------
2025-02-28 00:00:00 | 4 days 10:40:00
(1 row)
extract returns numeric values; dow counts Sunday as 0, so Asha's birthday fell on a Saturday (6). date_trunc returns a timestamp at the start of the month. age() gives a readable interval such as '28 years 9 mons 18 days', while plain date subtraction returns days. Adding one month to 31 January gives 28 February 2025, because PostgreSQL clamps to the last day of the shorter month. Timestamp subtraction yields an interval of days and hours.
sql
CREATE TABLE members (name text, born date, joined timestamp);
INSERT INTO members VALUES
('Asha', '1998-02-14', '2025-01-31 09:15'),
('Ben', '2004-11-30', '2026-03-05 18:40');
SELECT name, extract(year FROM born) AS birth_year, extract(dow FROM born) AS weekday, date_trunc('month', joined) AS join_month FROM members ORDER BY name;
SELECT name, age(date '2026-12-04', born) AS age, date '2026-12-04' - born AS days_alive FROM members ORDER BY name;
SELECT date '2025-01-31' + interval '1 month' AS plus_month, timestamp '2026-03-05 18:40' - timestamp '2026-03-01 08:00' AS gap;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
extract for parts, date_trunc for rounding
date minus date gives days
age() gives years, months and days
Month arithmetic clamps to month end
Timestamp subtraction gives an interval
Common mistakes
Calculating age by dividing days by 365
Expecting 31 January plus a month to be 3 March
Follow-ups
How do you group sales by ISO week?
What does date_bin do?
Tips
Show month-end clamping
9.postgresql-0009Easyfresher
How do PostgreSQL arrays work for simple lists such as tags, and when should a separate table be used instead?
A column can hold an array such as text[]; ANY checks membership, @> checks containment, unnest turns elements into rows and array_agg builds arrays. Arrays suit small lists read together with the row. Use a child table when elements need foreign keys, their own attributes or frequent individual updates.
Full answer
Schema and sample rows:
sql
CREATE TABLE posts (id int PRIMARY KEY, title text, tags text[]);
INSERT INTO posts VALUES
(1, 'Intro to SQL', ARRAY['sql', 'beginner']),
(2, 'Indexing', ARRAY['sql', 'performance']),
(3, 'Python tips', '{python,beginner}');
sql
SELECT title, tags[1] AS first_tag, cardinality(tags) AS n FROM posts WHERE 'beginner' = ANY(tags) ORDER BY id;
Output:
text
title | first_tag | n
--------------+-----------+---
Intro to SQL | sql | 2
Python tips | python | 2
(2 rows)
sql
SELECT title FROM posts WHERE tags @> ARRAY['sql', 'performance'];
PostgreSQL returns:
text
title
----------
Indexing
(1 row)
sql
SELECT tag, count(*) AS posts FROM posts, unnest(tags) AS tag GROUP BY tag ORDER BY posts DESC, tag;
Array indexes start at 1, so tags[1] is the first tag. ANY finds posts tagged 'beginner', and @> requires every listed tag, which a GIN index on the column can speed up. unnest expands each array into rows so tags can be counted like a normal column. The literal '{python,beginner}' is the text form of an array. Arrays cannot have foreign keys to a tags table, so if tags need names, descriptions or renaming, a post_tags join table is the better design.
sql
CREATE TABLE posts (id int PRIMARY KEY, title text, tags text[]);
INSERT INTO posts VALUES
(1, 'Intro to SQL', ARRAY['sql', 'beginner']),
(2, 'Indexing', ARRAY['sql', 'performance']),
(3, 'Python tips', '{python,beginner}');
SELECT title, tags[1] AS first_tag, cardinality(tags) AS n FROM posts WHERE 'beginner' = ANY(tags) ORDER BY id;
SELECT title FROM posts WHERE tags @> ARRAY['sql', 'performance'];
SELECT tag, count(*) AS posts FROM posts, unnest(tags) AS tag GROUP BY tag ORDER BY posts DESC, tag;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Arrays are 1-indexed
ANY for membership, @> for containment
unnest turns elements into rows
GIN indexes support containment
Use a join table when elements need integrity
Common mistakes
Using arrays where foreign keys are needed
Assuming arrays start at index 0
Follow-ups
How do you add an element to an array column?
How would you index tags for fast search?
Tips
Mention GIN
10.postgresql-0010Easyfresher
When is an ENUM type a good fit in PostgreSQL, and what are its limitations?
CREATE TYPE ... AS ENUM defines a fixed, ordered list of labels; invalid values are rejected and sorting follows declaration order. ALTER TYPE ... ADD VALUE adds labels, but there is no way to drop one, so lists that change often are easier as a lookup table or a CHECK constraint.
Full answer
Sample schema and data:
sql
CREATE TYPE ticket_status AS ENUM ('open', 'in_progress', 'resolved');
CREATE TABLE support (id int, status ticket_status);
INSERT INTO support VALUES (1, 'resolved'), (2, 'open'), (3, 'in_progress');
sql
SELECT id, status FROM support ORDER BY status;
PostgreSQL returns:
text
id | status
----+-------------
2 | open
3 | in_progress
1 | resolved
(3 rows)
sql
INSERT INTO support VALUES (4, 'closed');
Result on PostgreSQL 17:
text
ERROR: invalid input value for enum ticket_status: "closed"
sql
ALTER TYPE ticket_status ADD VALUE 'on_hold' BEFORE 'resolved';
Result:
text
ALTER TYPE
sql
SELECT enum_range(NULL::ticket_status)::text AS labels;
Sorting by status follows the declared order (open, in_progress, resolved), not alphabetical order. An unknown label is rejected with an 'invalid input value for enum' error. ADD VALUE can insert a new label at a chosen position, and enum_range lists the labels in order. The two statements are sent separately on purpose: a new enum value cannot be used in the same transaction that added it, and sending both in one script fails with 'unsafe use of new value'. There is no ALTER TYPE ... DROP VALUE, so retiring a status means creating a new type and converting the column. A CHECK (status IN (...)) constraint on text is simpler to change, and a lookup table can hold extra attributes such as display names.
sql
CREATE TYPE ticket_status AS ENUM ('open', 'in_progress', 'resolved');
CREATE TABLE support (id int, status ticket_status);
INSERT INTO support VALUES (1, 'resolved'), (2, 'open'), (3, 'in_progress');
SELECT id, status FROM support ORDER BY status;
INSERT INTO support VALUES (4, 'closed');
ALTER TYPE ticket_status ADD VALUE 'on_hold' BEFORE 'resolved';
SELECT enum_range(NULL::ticket_status)::text AS labels;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Enums reject invalid labels
Order follows declaration
ADD VALUE is supported
Values cannot be dropped
Lookup tables suit changing lists
Common mistakes
Using enums for lists that change monthly
Assuming ORDER BY sorts enum labels alphabetically
Follow-ups
How would you rename an enum label?
When is a lookup table better than an enum?
Tips
Show declaration-order sorting
11.postgresql-0011Easyfresher
Use transactions and savepoints to undo part of a unit of work.
BEGIN starts a transaction, COMMIT makes its changes permanent and ROLLBACK discards them. A SAVEPOINT marks a point inside the transaction; ROLLBACK TO SAVEPOINT undoes work after it while keeping earlier work. After an error in PostgreSQL, the transaction is aborted until you roll back, either entirely or to a savepoint.
Full answer
Setup for the example:
sql
CREATE TABLE stock (item text PRIMARY KEY, qty int CHECK (qty >= 0));
INSERT INTO stock VALUES ('pen', 10), ('ink', 2);
sql
BEGIN; UPDATE stock SET qty = qty - 3 WHERE item = 'pen'; SAVEPOINT before_ink;
Result on PostgreSQL 17:
text
SAVEPOINT
sql
UPDATE stock SET qty = qty - 5 WHERE item = 'ink';
Result:
text
ERROR: new row for relation "stock" violates check constraint "stock_qty_check"
sql
SELECT * FROM stock;
Output:
text
ERROR: current transaction is aborted, commands ignored until end of transaction block
sql
ROLLBACK TO SAVEPOINT before_ink; COMMIT; SELECT item, qty FROM stock ORDER BY item;
PostgreSQL returns:
text
item | qty
------+-----
ink | 2
pen | 7
(2 rows)
The pen update succeeds and a savepoint is set. Taking five ink from a stock of two violates the CHECK constraint. Any further statement then fails with 'current transaction is aborted, commands ignored until end of transaction block', which surprises developers coming from databases that continue after errors. Rolling back to the savepoint clears the error while keeping the pen change, and COMMIT saves it, so pens drop to 7 and ink stays at 2. Drivers and ORMs often use savepoints for nested transaction blocks.
sql
CREATE TABLE stock (item text PRIMARY KEY, qty int CHECK (qty >= 0));
INSERT INTO stock VALUES ('pen', 10), ('ink', 2);
BEGIN; UPDATE stock SET qty = qty - 3 WHERE item = 'pen'; SAVEPOINT before_ink;
UPDATE stock SET qty = qty - 5 WHERE item = 'ink';
SELECT * FROM stock;
ROLLBACK TO SAVEPOINT before_ink; COMMIT; SELECT item, qty FROM stock ORDER BY item;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
BEGIN, COMMIT and ROLLBACK
Savepoints allow partial rollback
Errors abort the transaction
ROLLBACK TO SAVEPOINT recovers
ORMs use savepoints for nesting
Common mistakes
Continuing to send statements after an error
Holding transactions open for long periods
Follow-ups
What does psql's ON_ERROR_ROLLBACK do?
How do savepoints affect performance?
Tips
Show the aborted-transaction error
12.postgresql-0012Easyfresher
Why does a table created as CREATE TABLE "UserAccounts" fail when queried as UserAccounts?
PostgreSQL folds unquoted identifiers to lower case, so UserAccounts means useraccounts. A name created with double quotes keeps its exact case and must always be quoted the same way. Use lower-case snake_case names to avoid quoting altogether.
Full answer
Tables and rows used here:
sql
CREATE TABLE "UserAccounts" ("UserName" text);
INSERT INTO "UserAccounts" VALUES ('asha');
sql
SELECT UserName FROM UserAccounts;
Result:
text
ERROR: relation "useraccounts" does not exist
sql
SELECT "UserName" FROM "UserAccounts";
Output:
text
UserName
----------
asha
(1 row)
sql
ALTER TABLE "UserAccounts" RENAME TO user_accounts; ALTER TABLE user_accounts RENAME COLUMN "UserName" TO user_name; SELECT user_name FROM USER_ACCOUNTS;
PostgreSQL returns:
text
user_name
-----------
asha
(1 row)
The unquoted query looks for a table called useraccounts, which does not exist, so it fails with 'relation "useraccounts" does not exist'; the lower-case name in the message is the clue. Quoting both names exactly works. Renaming to snake_case fixes it for good, and then any capitalisation works unquoted, as the final query with upper-case letters shows. ORMs and migration tools that quote identifiers can create mixed-case names without anyone noticing, so check generated DDL.
sql
CREATE TABLE "UserAccounts" ("UserName" text);
INSERT INTO "UserAccounts" VALUES ('asha');
SELECT UserName FROM UserAccounts;
SELECT "UserName" FROM "UserAccounts";
ALTER TABLE "UserAccounts" RENAME TO user_accounts; ALTER TABLE user_accounts RENAME COLUMN "UserName" TO user_name; SELECT user_name FROM USER_ACCOUNTS;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Unquoted names fold to lower case
Quoted names are case-sensitive
Error messages show the folded name
Use snake_case names
Check ORM-generated DDL
Common mistakes
Creating mixed-case quoted names
Quoting inconsistently across queries
Follow-ups
How do reserved words interact with quoting?
How does MySQL handle identifier case?
Tips
Point at the lower-case name in the error
13.postgresql-0013Easyfresher
Use string functions to clean and format text: trim, initcap, split_part, regexp_replace and format.
trim removes surrounding whitespace, lower and initcap normalise case, split_part takes a delimited field, regexp_replace rewrites patterns, and format builds strings from placeholders, with separate ones for values and for identifiers. || concatenates but yields NULL if any part is NULL, while concat and concat_ws skip NULLs.
SELECT initcap(trim(raw_name)) AS name, lower(email) AS email, split_part(lower(email), '@', 2) AS domain, regexp_replace(phone, '[^0-9]', '', 'g') AS digits FROM signups ORDER BY 1;
Output:
text
name | email | domain | digits
-------------+---------------------+------------+--------------
Asha Rao | asha.rao@example.in | example.in | 919845012345
Ben Thomas | ben@mail.co | mail.co | 08022223333
(2 rows)
sql
SELECT raw_name || ' from ' || city AS piped, concat_ws(', ', trim(raw_name), city) AS with_ws, format('%s lives in %s', trim(raw_name), coalesce(city, 'unknown')) AS formatted FROM signups ORDER BY 1;
PostgreSQL returns:
text
piped | with_ws | formatted
-----------------------+-------------------+---------------------------
ben thomas from Pune | ben thomas, Pune | ben thomas lives in Pune
NULL | asha RAO | asha RAO lives in unknown
(2 rows)
trim and initcap turn ' asha RAO ' into 'Asha Rao'; initcap capitalises each word, so names such as 'McDonald' need care. regexp_replace with the 'g' flag strips every non-digit from the phone numbers. In the second query, the || expression is NULL for Asha because her city is NULL, while concat_ws skips the NULL and format with coalesce gives a full sentence. Rows sort NULL last by default in ascending order, which is why Ben's row comes first here.
sql
CREATE TABLE signups (raw_name text, email text, phone text, city text);
INSERT INTO signups VALUES
(' asha RAO ', 'Asha.Rao@Example.IN', '+91 98450-12345', NULL),
('ben thomas', 'ben@mail.co', '080 2222 3333', 'Pune');
SELECT initcap(trim(raw_name)) AS name, lower(email) AS email, split_part(lower(email), '@', 2) AS domain, regexp_replace(phone, '[^0-9]', '', 'g') AS digits FROM signups ORDER BY 1;
SELECT raw_name || ' from ' || city AS piped, concat_ws(', ', trim(raw_name), city) AS with_ws, format('%s lives in %s', trim(raw_name), coalesce(city, 'unknown')) AS formatted FROM signups ORDER BY 1;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
trim, lower and initcap normalise text
split_part extracts fields
regexp_replace with the g flag
|| propagates NULL
concat_ws and format handle NULLs and formatting
Common mistakes
Concatenating nullable columns with ||
Trusting initcap for all names
Follow-ups
How would you build dynamic SQL safely with format()?
How do you split a string into rows?
Tips
Show the NULL concatenation
14.postgresql-0014Easyfresher
Use ILIKE and LIKE patterns, and explain when a pattern search can use an index.
LIKE matches patterns with % for any run of characters and _ for one character; ILIKE is the case-insensitive version. A prefix pattern such as 'abc%' can use a B-tree index built with text_pattern_ops (or in the C collation), but a leading wildcard such as '%abc%' needs a trigram GIN index from pg_trgm.
Full answer
Schema and sample rows:
sql
CREATE TABLE products (id int, name text);
INSERT INTO products VALUES (1, 'Blue Pen'), (2, 'blue ink'), (3, 'Notebook'), (4, 'Pen_Stand');
CREATE INDEX products_name_prefix ON products (name text_pattern_ops);
sql
SELECT name FROM products WHERE name LIKE 'Blue%' ORDER BY id;
PostgreSQL returns:
text
name
----------
Blue Pen
(1 row)
sql
SELECT name FROM products WHERE name ILIKE 'blue%' ORDER BY id;
Result on PostgreSQL 17:
text
name
----------
Blue Pen
blue ink
(2 rows)
sql
SELECT name FROM products WHERE name LIKE '%\_%' ORDER BY id;
Result:
text
name
-----------
Pen_Stand
(1 row)
sql
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name LIKE 'Note%';
Output:
text
Index Only Scan using products_name_prefix on products
Index Cond: ((name ~>=~ 'Note'::text) AND (name ~<~ 'Notf'::text))
Filter: (name ~~ 'Note%'::text)
LIKE is case-sensitive, so only 'Blue Pen' matches the first query, while ILIKE also matches 'blue ink'. An underscore is itself a wildcard, so searching for a literal underscore needs the escape _, which finds only 'Pen_Stand'. The plan shows the prefix search using the text_pattern_ops index as a range condition (name >= 'Note' and name < 'Notf'); sequential scans were disabled only so the tiny table shows the index path. For ILIKE or infix searches, CREATE EXTENSION pg_trgm and a GIN index with gin_trgm_ops is the usual answer.
sql
CREATE TABLE products (id int, name text);
INSERT INTO products VALUES (1, 'Blue Pen'), (2, 'blue ink'), (3, 'Notebook'), (4, 'Pen_Stand');
CREATE INDEX products_name_prefix ON products (name text_pattern_ops);
SELECT name FROM products WHERE name LIKE 'Blue%' ORDER BY id;
SELECT name FROM products WHERE name ILIKE 'blue%' ORDER BY id;
SELECT name FROM products WHERE name LIKE '%\_%' ORDER BY id;
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name LIKE 'Note%';
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
% and _ are wildcards
ILIKE ignores case
Escape literal underscores
Prefix searches can use text_pattern_ops
pg_trgm for infix and ILIKE
Common mistakes
Expecting '%term%' to use a B-tree index
Forgetting that _ is a wildcard
Follow-ups
How does pg_trgm similarity work?
When is full-text search better than LIKE?
Tips
Show the plan
15.postgresql-0015Easyfresher
Write a CHECK constraint that involves two columns, and show how existing bad data blocks adding it.
A CHECK constraint can compare columns in the same row, such as end_date >= start_date. Adding it to a table with violating rows fails. Fix the data first, or add the constraint NOT VALID so new rows are checked immediately, then clean up and run VALIDATE CONSTRAINT.
ALTER TABLE bookings ADD CONSTRAINT dates_in_order CHECK (end_date >= start_date);
Result on PostgreSQL 17:
text
ERROR: check constraint "dates_in_order" of relation "bookings" is violated by some row
sql
ALTER TABLE bookings ADD CONSTRAINT dates_in_order CHECK (end_date >= start_date) NOT VALID;
Result:
text
ALTER TABLE
sql
INSERT INTO bookings VALUES (3, '2026-12-20', '2026-12-01', 2);
Output:
text
ERROR: new row for relation "bookings" violates check constraint "dates_in_order"
sql
UPDATE bookings SET end_date = '2026-12-16' WHERE id = 2; ALTER TABLE bookings VALIDATE CONSTRAINT dates_in_order; SELECT conname, convalidated FROM pg_constraint WHERE conname = 'dates_in_order';
PostgreSQL returns:
text
conname | convalidated
----------------+--------------
dates_in_order | t
(1 row)
Adding the constraint normally scans the table and fails on booking 2, whose end date is before its start. NOT VALID skips the scan of existing rows but still rejects the new bad booking 3. After the data is fixed, VALIDATE CONSTRAINT checks the old rows and marks the constraint validated. On large tables this two-step approach also shortens the strong lock, because validation takes a weaker lock than adding a constraint with a full scan. Note that CHECK passes when the expression is NULL, so add NOT NULL where dates are required.
sql
CREATE TABLE bookings (id int, start_date date, end_date date, guests int);
INSERT INTO bookings VALUES
(1, '2026-12-10', '2026-12-12', 2),
(2, '2026-12-15', '2026-12-14', 1);
ALTER TABLE bookings ADD CONSTRAINT dates_in_order CHECK (end_date >= start_date);
ALTER TABLE bookings ADD CONSTRAINT dates_in_order CHECK (end_date >= start_date) NOT VALID;
INSERT INTO bookings VALUES (3, '2026-12-20', '2026-12-01', 2);
UPDATE bookings SET end_date = '2026-12-16' WHERE id = 2; ALTER TABLE bookings VALIDATE CONSTRAINT dates_in_order; SELECT conname, convalidated FROM pg_constraint WHERE conname = 'dates_in_order';
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
CHECK can compare columns in a row
Existing bad rows block a normal ADD
NOT VALID checks new rows only
VALIDATE CONSTRAINT checks old rows later
CHECK passes on NULL
Common mistakes
Adding constraints to big tables in one step at peak time
Forgetting NOT NULL alongside CHECK
Follow-ups
Which lock does VALIDATE CONSTRAINT take?
When would a trigger be needed instead of CHECK?
Tips
Mention the NULL pass
16.postgresql-0016Easyfresher
Which literals does PostgreSQL accept for boolean columns, and how are booleans used in filters and counts?
A boolean column accepts true and false plus text forms such as 't', 'yes', 'on' and '1', case-insensitively. A boolean can be used directly as a WHERE condition, and count(*) FILTER (WHERE flag) or sum(flag::int) count the true values. NULL is a third state, neither true nor false.
SELECT name, active, active IS NOT TRUE AS not_true FROM flags ORDER BY name;
Result:
text
name | active | not_true
------+--------+----------
a | t | f
b | t | f
c | f | t
d | f | t
e | NULL | t
f | t | f
(6 rows)
sql
SELECT count(*) FILTER (WHERE active) AS on_count, count(*) FILTER (WHERE NOT active) AS off_count, sum(active::int) AS summed, bool_and(active) AS all_on FROM flags;
ERROR: invalid input syntax for type boolean: "maybe"
All the text forms were stored as plain true or false, shown as t and f. Row e is NULL, so IS NOT TRUE is true for it while NOT active would be NULL. The FILTER counts show three true and two false values, with the NULL in neither, and bool_and ignores NULLs too. An unrecognised word such as 'maybe' is rejected with an 'invalid input syntax for type boolean' error, so text flags from imports are validated on the way in.
sql
CREATE TABLE flags (name text, active boolean);
INSERT INTO flags VALUES ('a', true), ('b', 'yes'), ('c', 'off'), ('d', '0'), ('e', NULL), ('f', 'T');
SELECT name, active, active IS NOT TRUE AS not_true FROM flags ORDER BY name;
SELECT count(*) FILTER (WHERE active) AS on_count, count(*) FILTER (WHERE NOT active) AS off_count, sum(active::int) AS summed, bool_and(active) AS all_on FROM flags;
INSERT INTO flags VALUES ('g', 'maybe');
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
Many text literals map to booleans
Booleans work directly in WHERE
FILTER counts true values
NULL is neither true nor false
IS NOT TRUE includes NULLs
Common mistakes
Storing flags as 'Y'/'N' text
Forgetting NULL in boolean logic
Follow-ups
When would you make a boolean column NOT NULL?
What does bool_or return over no rows?
Tips
Mention the NULL state
17.postgresql-0017Easyfresher
Count several conditions in one pass with the aggregate FILTER clause.
agg(...) FILTER (WHERE condition) applies the aggregate only to rows matching the condition, so one query can return several conditional counts or sums side by side. It is PostgreSQL's cleaner form of the CASE-inside-aggregate pattern and works with any aggregate, including array_agg and avg.
SELECT count(*) AS total, count(*) FILTER (WHERE status = 'paid') AS paid, sum(amount) FILTER (WHERE status = 'paid') AS paid_amount, avg(amount) FILTER (WHERE method = 'upi') AS avg_upi, array_agg(id ORDER BY id) FILTER (WHERE status <> 'paid') AS problem_ids FROM payments;
SELECT method, count(*) FILTER (WHERE status = 'paid') AS paid, count(*) FILTER (WHERE status <> 'paid') AS other FROM payments GROUP BY method ORDER BY method;
The first query scans the table once and returns six payments, four paid, 3749.00 collected and an average UPI amount of 382.67 (shown with numeric's full scale), plus the ids of the two problem payments. The second combines FILTER with GROUP BY for a per-method breakdown. The equivalent sum(CASE WHEN status = 'paid' THEN amount END) works on every database, so it is the portable choice, but FILTER is easier to read and also applies to aggregates where a CASE trick is awkward.
sql
CREATE TABLE payments (id int, method text, status text, amount numeric(10,2));
INSERT INTO payments VALUES
(1, 'upi', 'paid', 499), (2, 'card', 'failed', 1200), (3, 'upi', 'paid', 150),
(4, 'card', 'paid', 2300), (5, 'upi', 'refunded', 499), (6, 'netbanking', 'paid', 800);
SELECT count(*) AS total, count(*) FILTER (WHERE status = 'paid') AS paid, sum(amount) FILTER (WHERE status = 'paid') AS paid_amount, avg(amount) FILTER (WHERE method = 'upi') AS avg_upi, array_agg(id ORDER BY id) FILTER (WHERE status <> 'paid') AS problem_ids FROM payments;
SELECT method, count(*) FILTER (WHERE status = 'paid') AS paid, count(*) FILTER (WHERE status <> 'paid') AS other FROM payments GROUP BY method ORDER BY method;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
FILTER restricts one aggregate
Several conditional aggregates in one scan
Works with any aggregate
Combines with GROUP BY
CASE inside the aggregate is the portable form
Common mistakes
Running one query per condition
Using WHERE, which filters rows for every aggregate
Follow-ups
How would you pivot statuses into columns for each month?
Does FILTER work with window functions?
Tips
Contrast with WHERE
18.postgresql-0018Easyfresher
Build ordered, comma-separated lists per group with string_agg and array_agg.
string_agg(expr, separator ORDER BY ...) joins values into one string per group, and array_agg collects them into an array. The ORDER BY inside the call controls element order, which is otherwise unspecified. DISTINCT inside the call removes repeats.
SELECT student, string_agg(course, ', ' ORDER BY enrolled) AS in_order, string_agg(DISTINCT course, ' | ' ORDER BY course) AS distinct_courses, array_agg(enrolled ORDER BY enrolled DESC) AS dates FROM enrolments GROUP BY student ORDER BY student;
For Asha, the ordered list follows enrolment dates, so Python comes before both SQL enrolments, while the DISTINCT version lists each course once in alphabetical order. When DISTINCT is used, the ORDER BY inside the aggregate must use the aggregated expression itself, which is why it sorts by course. array_agg keeps the dates as a real date array, newest first. Without an internal ORDER BY, the order depends on the plan and can change between runs or versions.
sql
CREATE TABLE enrolments (student text, course text, enrolled date);
INSERT INTO enrolments VALUES
('Asha', 'SQL', '2026-03-01'), ('Asha', 'Python', '2026-01-15'), ('Asha', 'SQL', '2026-06-01'),
('Ben', 'Go', '2026-02-10'), ('Ben', 'Python', '2026-02-01');
SELECT student, string_agg(course, ', ' ORDER BY enrolled) AS in_order, string_agg(DISTINCT course, ' | ' ORDER BY course) AS distinct_courses, array_agg(enrolled ORDER BY enrolled DESC) AS dates FROM enrolments GROUP BY student ORDER BY student;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
string_agg joins with a separator
array_agg builds arrays
ORDER BY inside the call sets order
DISTINCT removes duplicates
Unordered aggregation has no guaranteed order
Common mistakes
Relying on table order for list order
Sorting by another column together with DISTINCT
Follow-ups
How would you limit each list to three items?
How do you split a string_agg result back into rows?
Tips
Order inside the aggregate
19.postgresql-0019Easyfresher
Update rows using values from another table with UPDATE ... FROM.
UPDATE target SET ... FROM other WHERE join_condition updates target rows using matching rows from other tables. Rows without a match are left unchanged. If a target row matches several source rows, only one of them is used, unpredictably, so the source must be unique on the join key.
Two products matched and were updated; INK had no update row and kept its price, and the unknown XYZ had no product to change. RETURNING lists exactly the changed rows, which is a quick sanity check in scripts. Before running such an update, check that price_updates has at most one row per sku (for example with GROUP BY sku HAVING count(*) > 1); otherwise PostgreSQL silently picks one of the duplicates. Running the same join as a SELECT first is a cheap way to preview the change.
sql
CREATE TABLE products (sku text PRIMARY KEY, price numeric(10,2));
CREATE TABLE price_updates (sku text, new_price numeric(10,2));
INSERT INTO products VALUES ('PEN', 10), ('INK', 45), ('PAD', 60);
INSERT INTO price_updates VALUES ('PEN', 12), ('PAD', 55), ('XYZ', 99);
UPDATE products p SET price = u.new_price FROM price_updates u WHERE u.sku = p.sku RETURNING p.sku, p.price;
SELECT sku, price FROM products ORDER BY sku;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
UPDATE ... FROM joins another table
Unmatched rows stay unchanged
Duplicate source rows give unpredictable results
RETURNING shows changed rows
Preview with a SELECT
Common mistakes
Repeating the target table in FROM, creating a self-join
Updating from a source with duplicate keys
Follow-ups
How would you write this with MERGE?
How do you update from a CSV file?
Tips
Warn about duplicate source rows
20.postgresql-0020Easyfresher
Delete rows that match another table with DELETE ... USING, and compare it with NOT EXISTS.
DELETE FROM target USING other WHERE condition deletes target rows that have a matching row in other. To delete rows without a match, use WHERE NOT EXISTS (subquery). Both can RETURNING the removed rows, and running inside a transaction allows checking the count before committing.
Full answer
Sample schema and data:
sql
CREATE TABLE sessions (id int, user_id int);
CREATE TABLE banned (user_id int);
CREATE TABLE users (id int);
INSERT INTO users VALUES (1), (2), (3);
INSERT INTO sessions VALUES (10, 1), (11, 2), (12, 2), (13, 4);
INSERT INTO banned VALUES (2);
sql
DELETE FROM sessions s USING banned b WHERE b.user_id = s.user_id RETURNING s.id;
Result:
text
id
----
11
12
(2 rows)
sql
DELETE FROM sessions s WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = s.user_id) RETURNING s.id, s.user_id;
Output:
text
id | user_id
----+---------
13 | 4
(1 row)
sql
SELECT id, user_id FROM sessions;
PostgreSQL returns:
text
id | user_id
----+---------
10 | 1
(1 row)
The USING form removes both sessions of the banned user 2. The NOT EXISTS form removes session 13, whose user 4 does not exist, which is the usual clean-up for orphaned rows. Only session 10 remains. NOT IN (SELECT user_id ...) would behave badly if the subquery returned a NULL, which is why NOT EXISTS is the safer habit. For large deletes, batch the work so locks and WAL volume stay manageable.
sql
CREATE TABLE sessions (id int, user_id int);
CREATE TABLE banned (user_id int);
CREATE TABLE users (id int);
INSERT INTO users VALUES (1), (2), (3);
INSERT INTO sessions VALUES (10, 1), (11, 2), (12, 2), (13, 4);
INSERT INTO banned VALUES (2);
DELETE FROM sessions s USING banned b WHERE b.user_id = s.user_id RETURNING s.id;
DELETE FROM sessions s WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = s.user_id) RETURNING s.id, s.user_id;
SELECT id, user_id FROM sessions;
Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
DELETE ... USING joins for deletion
NOT EXISTS deletes unmatched rows
RETURNING lists removed rows
Avoid NOT IN with nullable subqueries
Batch large deletes
Common mistakes
Using NOT IN with a nullable column
Deleting millions of rows in one statement at peak time