🐘 SQL & Postgres Interview Prep

SQL & PostgreSQL for Interviews

Start with the SQL basics every interviewer expects, then go deep into PostgreSQL: indexes, EXPLAIN, MVCC, locks, JSONB, replication and using Postgres from Node.js. Read a topic, mark it done, then test yourself in Q&A Practice and write real queries in the Query Lab.

0 of 0 topics doneReset progress
How to answer SQL questions in an interview 1) Repeat the question and ask about edge cases (NULLs, duplicates, ties). 2) Say your plan out loud: which tables, which join, which filter. 3) Write the simple version first, then improve it. 4) Mention performance (indexes, EXPLAIN) at the end. Interviewers love a calm, step-by-step thinker more than a fast typist.
Part 1 β€” SQL BasicsWorks in almost every database. Learn this first.

What is SQL and a database?

SQL (Structured Query Language) is the language we use to talk to relational databases.

A relational database stores data in tables. A table has columns (the fields, like name, email) and rows (one record each). Tables are connected to each other using keys. The software that manages it is called an RDBMS (Relational Database Management System). Examples: PostgreSQL, MySQL, SQL Server, Oracle, SQLite.

The 5 groups of SQL commands

GroupFull nameWhat it doesCommands
DDLData Definition LanguageCreates or changes the structureCREATE ALTER DROP TRUNCATE
DMLData Manipulation LanguageChanges the dataINSERT UPDATE DELETE
DQLData Query LanguageReads dataSELECT
DCLData Control LanguagePermissionsGRANT REVOKE
TCLTransaction Control LanguageGroups work into a transactionBEGIN COMMIT ROLLBACK SAVEPOINT

SQL database vs NoSQL (for example MongoDB)

SQL (relational)NoSQL (document, like MongoDB)
StructureFixed schema, tables and rowsFlexible schema, JSON-like documents
RelationsStrong: foreign keys and JOINsUsually embed data or reference by id
ConsistencyACID transactions are the defaultDepends on the database and settings
Best forMoney, orders, users, reports, anything with many relationsFast-changing shapes, content, logs, simple access patterns
Interview tipDo not say "SQL is better than NoSQL". Say "it depends on the data shape and access patterns". For most business apps, PostgreSQL is a safe default choice.

Data types and constraints

Types say what kind of value a column can hold. Constraints are rules that protect your data.

KindCommon types
Whole numbersSMALLINT, INTEGER, BIGINT
DecimalsNUMERIC(10,2) (exact, use for money), REAL / DOUBLE PRECISION (approximate)
TextCHAR(n), VARCHAR(n), TEXT
Date and timeDATE, TIME, TIMESTAMP, TIMESTAMPTZ
True / falseBOOLEAN

Constraints

  • PRIMARY KEY – unique and not null. Identifies a row.
  • FOREIGN KEY – value must exist in another table.
  • UNIQUE – no duplicates allowed (NULLs are allowed).
  • NOT NULL – value is required.
  • CHECK – a rule, like price > 0.
  • DEFAULT – value used when you do not give one.
CREATE TABLE users (
  id          INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email       VARCHAR(255) NOT NULL UNIQUE,
  age         INTEGER CHECK (age >= 13),
  is_active   BOOLEAN NOT NULL DEFAULT true,
  created_at  TIMESTAMP NOT NULL DEFAULT NOW()
);
Common mistakeNever store money in FLOAT. 0.1 + 0.2 is not exactly 0.3 in floating point. Use NUMERIC or store cents as an integer.

Keys and relationships

Primary key

Uniquely identifies each row. One per table. Never NULL.

Foreign key

A column that points to the primary key of another table. It keeps data connected and valid.

Unique key

No duplicates, but a table can have many of them and NULL is allowed.

Composite key

A key made of 2 or more columns, like (student_id, course_id).

Candidate key

Any column set that could be the primary key. You pick one as primary.

Surrogate vs natural

Surrogate = made-up id (1, 2, 3 or UUID). Natural = real data (email, national ID). Surrogate keys are usually safer because real data can change.

Types of relationships

  • One-to-one: one user has one profile. Put a unique foreign key in one table.
  • One-to-many: one customer has many orders. Put the foreign key on the "many" side (orders.customer_id).
  • Many-to-many: students and courses. You need a junction table (enrollments) with two foreign keys.
CREATE TABLE enrollments (
  student_id INTEGER REFERENCES students(id) ON DELETE CASCADE,
  course_id  INTEGER REFERENCES courses(id)  ON DELETE CASCADE,
  PRIMARY KEY (student_id, course_id)
);

What happens when the parent row is deleted? (ON DELETE)

OptionMeaning
RESTRICT / NO ACTIONBlock the delete if children exist (default)
CASCADEDelete the children too
SET NULLSet the child's foreign key to NULL
SET DEFAULTSet the child's foreign key to its default value

SELECT, WHERE, ORDER BY, LIMIT

SELECT DISTINCT city              -- unique values only
FROM customers
WHERE city IN ('Lahore', 'Karachi')    -- list match
  AND created_at BETWEEN '2025-01-01' AND '2025-12-31'
  AND name LIKE 'A%'                   -- starts with A
ORDER BY city ASC, name DESC
LIMIT 10 OFFSET 20;                    -- rows 21 to 30
ToolMeaning
= <> < > <= >=Compare values. <> and != both mean "not equal".
AND OR NOTCombine conditions. AND runs before OR, so use brackets.
IN (...)Matches any value in a list
BETWEEN a AND bInclusive range (includes a and b)
LIKE% = any number of characters, _ = exactly one character
ASGives a column or table a nickname (alias)
RememberORDER BY is the only way to get a guaranteed order. Without it, the database can return rows in any order. Also, OFFSET gets slow on big tables; see keyset pagination in the performance topic.

NULL handling

NULL means "unknown" or "missing". It is not zero and not an empty string.

  • Any comparison with NULL gives unknown, not true: NULL = NULL is not true. Use IS NULL and IS NOT NULL.
  • NULL + 5 is NULL.
  • COUNT(*) counts all rows. COUNT(col) skips NULLs. COUNT(DISTINCT col) counts unique non-NULL values.
  • SUM, AVG, MIN, MAX ignore NULLs.
SELECT COALESCE(phone, 'no phone') FROM customers;   -- first non-NULL value
SELECT NULLIF(discount, 0) FROM orders;               -- returns NULL if discount = 0
SELECT * FROM employees WHERE department_id IS NULL;
Classic trap: NOT INIf the list inside NOT IN (...) contains even one NULL, the whole condition returns no rows. Prefer NOT EXISTS or a LEFT JOIN ... IS NULL.
-- Returns NO rows, because of the NULL:
SELECT 1 WHERE 5 NOT IN (1, 2, NULL);

INSERT, UPDATE, DELETE

INSERT INTO customers (name, email, city)
VALUES ('Sana', 'sana@example.com', 'Peshawar'),
       ('Ali',  'ali@example.com',  'Lahore');

UPDATE employees
SET salary = salary * 1.10
WHERE department_id = 2;      -- ALWAYS check your WHERE

DELETE FROM orders WHERE status = 'cancelled';
DangerAn UPDATE or DELETE without WHERE changes every row. Run a SELECT with the same WHERE first, and use a transaction.

DELETE vs TRUNCATE vs DROP

DELETETRUNCATEDROP
RemovesRows (can use WHERE)All rowsThe whole table
TypeDMLDDLDDL
SpeedSlower (row by row)Very fastFast
Triggers fire?YesNo (row triggers)No
Rollback?YesYes in PostgreSQLYes in PostgreSQL
Table structure stays?YesYesNo

Aggregates, GROUP BY, HAVING

Aggregate functions squeeze many rows into one value: COUNT, SUM, AVG, MIN, MAX.

SELECT department_id,
       COUNT(*)            AS people,
       ROUND(AVG(salary))  AS avg_salary
FROM employees
WHERE salary IS NOT NULL            -- filters ROWS before grouping
GROUP BY department_id
HAVING COUNT(*) >= 2                -- filters GROUPS after grouping
ORDER BY avg_salary DESC;
WHERE vs HAVINGWHERE filters rows before grouping and cannot use aggregates. HAVING filters groups after grouping and can use aggregates.

Rule: every column in SELECT must be either inside an aggregate function or listed in GROUP BY.

JOINs

A JOIN combines rows from two tables using a matching condition, usually primary key = foreign key.

JoinReturns
INNER JOINOnly rows that match in both tables
LEFT JOINAll rows from the left table + matches from the right (NULL if no match)
RIGHT JOINAll rows from the right table + matches from the left
FULL JOINAll rows from both tables, matched where possible
CROSS JOINEvery row of A with every row of B (A Γ— B rows)
Self joinA table joined to itself (for example employee and manager)
-- Orders with the customer name
SELECT o.id, c.name, o.order_date
FROM orders o
INNER JOIN customers c ON c.id = o.customer_id;

-- Customers who NEVER ordered (anti-join)
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

-- Self join: employee and manager
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
ON vs WHERE in a LEFT JOINA condition on the right table inside WHERE removes the NULL rows, so your LEFT JOIN quietly becomes an INNER JOIN. Put such conditions in ON if you want to keep unmatched left rows.

See the Diagrams page for pictures of each join type.

Subqueries and CTEs

A subquery is a query inside another query. It can return one value, a list, or a table.

-- Scalar subquery: employees paid above average
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

-- EXISTS: stops at the first match, good for "has at least one"
SELECT c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

-- Correlated subquery: uses a column from the outer query
SELECT e.name, e.salary FROM employees e
WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id);

CTE (WITH clause)

A Common Table Expression gives a name to a sub-result. It makes long queries easy to read, like small steps.

WITH customer_totals AS (
  SELECT o.customer_id, SUM(oi.quantity * oi.unit_price) AS total
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  GROUP BY o.customer_id
)
SELECT c.name, t.total
FROM customer_totals t JOIN customers c ON c.id = t.customer_id
WHERE t.total > 1000;

Recursive CTE (trees and hierarchies)

WITH RECURSIVE org AS (
  SELECT id, name, manager_id, 1 AS level      -- start: the top boss
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, org.level + 1   -- repeat: find the reports
  FROM employees e JOIN org ON e.manager_id = org.id
)
SELECT * FROM org ORDER BY level;
IN vs EXISTSFor "does a match exist?" EXISTS is clear and safe with NULLs. Modern optimizers often turn IN and EXISTS into the same plan, so choose the one that is easiest to read, but avoid NOT IN with nullable columns.

UNION, INTERSECT, EXCEPT

Set operations combine the results of two queries. Both queries need the same number of columns with compatible types.

OperatorResult
UNIONAll rows from both, duplicates removed (does extra sorting or hashing)
UNION ALLAll rows from both, duplicates kept (faster)
INTERSECTRows that are in both results
EXCEPTRows in the first result but not in the second (Oracle calls it MINUS)
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM customers;     -- subscribers who are not customers

Window functions

A window function does a calculation across related rows without collapsing them into one row like GROUP BY does.

function() OVER (
  PARTITION BY column     -- split rows into groups (optional)
  ORDER BY column         -- order inside each group (optional)
)
FunctionWhat it does
ROW_NUMBER()1, 2, 3, 4 … no ties, always unique
RANK()Ties get the same rank and a gap follows: 1, 2, 2, 4
DENSE_RANK()Ties get the same rank and no gap: 1, 2, 2, 3
LAG(col) / LEAD(col)Value from the previous / next row
SUM() OVER (ORDER BY ...)Running total
NTILE(n)Splits rows into n equal buckets
FIRST_VALUE() / LAST_VALUE()First / last value in the window
-- Highest paid person in each department
SELECT * FROM (
  SELECT name, department_id, salary,
         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
  FROM employees
) t
WHERE rn = 1;

-- Running total and change from the previous month
SELECT month, revenue,
       SUM(revenue) OVER (ORDER BY month)        AS running_total,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_revenue;
Can't use them in WHEREWindow functions run after WHERE and GROUP BY, so you cannot filter on them directly. Wrap the query in a subquery or CTE, then filter (as in the example above).

How SQL runs your query (order of execution)

You write SELECT first, but the database thinks about it in a different order:

  1. FROM and JOIN – find and combine the tables
  2. WHERE – filter rows
  3. GROUP BY – make groups
  4. HAVING – filter groups
  5. SELECT – pick columns, calculate expressions and window functions
  6. DISTINCT – remove duplicates
  7. ORDER BY – sort
  8. LIMIT / OFFSET – cut the result
Why this mattersThis explains why you cannot use a column alias from SELECT inside WHERE (it does not exist yet), but you can use it in ORDER BY (it runs later). It also explains why WHERE cannot use COUNT().

Useful built-in functions and CASE

-- CASE: if / else inside SQL
SELECT name,
  CASE WHEN salary >= 120000 THEN 'senior'
       WHEN salary >=  80000 THEN 'mid'
       ELSE 'junior' END AS level
FROM employees;

-- Text
SELECT UPPER(name), LOWER(email), LENGTH(name), TRIM('  hi  '),
       SUBSTRING(email FROM 1 FOR 5), REPLACE(email, '@', ' at '),
       name || ' <' || email || '>' AS label      -- || joins text
FROM customers;

-- Numbers and dates
SELECT ROUND(3.14159, 2), CEIL(2.1), FLOOR(2.9), ABS(-5);
SELECT NOW(), CURRENT_DATE, NOW() - INTERVAL '7 days';
SELECT EXTRACT(YEAR FROM order_date), DATE_TRUNC('month', order_date) FROM orders;

-- Type conversion
SELECT CAST('42' AS INTEGER), '42'::INTEGER;   -- :: is PostgreSQL style

A "conditional count" is a very popular trick:

SELECT COUNT(*) AS total,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered
FROM orders;

Normalization

Normalization means organizing tables so each fact is stored in one place only. This avoids repeated data and update mistakes.

FormRule (simple words)Bad example β†’ fix
1NFEvery cell holds one value. No lists in a cell, no repeating columns.phones = '0300,0311' β†’ one row per phone in a phones table
2NF1NF + every non-key column depends on the whole key (matters for composite keys).(order_id, product_id, product_name): name depends only on product β†’ move to products
3NF2NF + no non-key column depends on another non-key column.employees(zip, city): city depends on zip β†’ move to zip_codes

A short way to remember: "The key, the whole key, and nothing but the key."

Anomalies that normalization prevents

  • Update anomaly: same fact stored in many rows, you update some and forget others.
  • Insert anomaly: you cannot add a fact without adding unrelated data.
  • Delete anomaly: deleting a row accidentally loses another fact.
DenormalizationSometimes we repeat data on purpose to make reads faster, for example storing orders.total or a likes_count column. You get speed, but you must keep the copies in sync. Do it only when you have a real performance reason.

Indexes (the basics)

An index is like the index at the back of a book. Instead of reading every page (a full table scan), the database jumps straight to the right place.

CREATE INDEX idx_orders_customer ON orders (customer_id);
CREATE UNIQUE INDEX idx_users_email ON users (email);
DROP INDEX idx_orders_customer;
  • Most databases use a B-tree index by default. It is good for =, <, >, BETWEEN, ORDER BY and prefix LIKE 'abc%'.
  • Primary key and unique constraints create an index automatically.
  • Cost: indexes use disk space and make INSERT, UPDATE, DELETE slower, because the index must be updated too. Do not index everything.

Composite (multi-column) index

An index on (country, city) helps queries on country alone, or country + city, but not on city alone. This is the leftmost prefix rule. Put the column you filter with = first, and range or sort columns later.

When is an index NOT used?

  • You wrap the column in a function: WHERE LOWER(email) = 'a@b.com' (fix: expression index)
  • Leading wildcard: LIKE '%abc'
  • The table is tiny, or the filter matches most of the rows (a full scan is cheaper)
  • Type mismatch causes an implicit cast, like comparing a text column to a number
  • Leftmost column of a composite index is missing from the query
Good candidates for an indexColumns used often in WHERE, JOIN ... ON (foreign keys!), ORDER BY, and columns with many different values (high selectivity).

Transactions and ACID

A transaction is a group of steps that must succeed together or not at all. Classic example: send money from account A to account B.

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;      -- or ROLLBACK; to undo everything

A β€” Atomicity

All steps happen, or none happen.

C β€” Consistency

The data always follows the rules (constraints). A transaction moves the database from one valid state to another.

I β€” Isolation

Transactions running at the same time do not break each other.

D β€” Durability

After COMMIT the data is safe, even if the server crashes.

Problems when transactions run at the same time

ProblemWhat happens
Dirty readYou read data that another transaction has not committed yet
Non-repeatable readYou read a row twice and get different values, because someone committed an update between
Phantom readYou run the same query twice and new rows appear (or vanish), because someone inserted or deleted

Isolation levels (SQL standard)

LevelDirty readNon-repeatablePhantom
Read UncommittedPossiblePossiblePossible
Read CommittedNoPossiblePossible
Repeatable ReadNoNoPossible (standard) *
SerializableNoNoNo

* In PostgreSQL, Repeatable Read also prevents phantoms. More in the PostgreSQL concurrency topic.

Views, functions and triggers

View

A saved query that looks like a table. It stores no data itself (a normal view). Good for hiding complexity and for security.

CREATE VIEW active_customers AS
SELECT id, name, email FROM customers WHERE is_active;

SELECT * FROM active_customers;

A materialized view stores the result on disk. It is fast to read but gets old until you refresh it (REFRESH MATERIALIZED VIEW). Great for heavy reports.

Stored function / procedure

Code saved inside the database. A function returns a value and can be used inside queries. A procedure (CALL) can control transactions.

Trigger

Code that runs automatically BEFORE or AFTER an INSERT, UPDATE or DELETE. Typical uses: audit logs, updating an updated_at column. Use them carefully, because hidden logic is hard to debug.

Part 2 β€” PostgreSQL SpecificWhat makes Postgres special, and what interviewers ask about it.

What is PostgreSQL?

PostgreSQL ("Postgres") is a free, open-source, object-relational database. It is known for being reliable, standards-friendly and very extensible.

  • Fully ACID with strong transaction support.
  • MVCC (Multi-Version Concurrency Control): readers do not block writers, writers do not block readers.
  • Rich types: JSONB, arrays, ranges, UUID, enums, TIMESTAMPTZ, network types, geometric types.
  • Advanced features: CTEs, window functions, partial and expression indexes, full-text search, table partitioning, logical replication.
  • Extensible: PostGIS (maps), pg_trgm (fuzzy search), pgvector (AI embeddings), pg_stat_statements (slow query stats).

PostgreSQL vs MySQL (short and fair)

PostgreSQLMySQL
Feature setMore advanced SQL, JSONB, arrays, many index types, strong extensionsSimpler, very popular, great read speed for simple workloads
StandardsFollows the SQL standard closelyHas some own behaviours
Transactional DDLYes, you can roll back CREATE TABLENo (DDL commits automatically)
ConcurrencyMVCC, needs VACUUMMVCC with undo logs (InnoDB)

Handy psql commands

CommandDoes
\lList databases
\c dbnameConnect to a database
\dtList tables
\d tableDescribe a table (columns, indexes, constraints)
\di / \df / \dvList indexes / functions / views
\xToggle expanded (vertical) output
\timingShow how long each query takes
\qQuit

PostgreSQL data types worth knowing

SERIAL vs IDENTITY

SERIAL is the old way of auto-increment ids. GENERATED ... AS IDENTITY is the modern, standard way. Prefer IDENTITY for new tables.

UUID

128-bit id. Hard to guess, can be created in many services without a central counter. Bigger than an integer and random UUIDs hurt index locality (UUIDv7 is time-ordered and better).

TEXT vs VARCHAR(n)

In Postgres they perform the same. TEXT is fine unless you really need a length limit.

TIMESTAMP vs TIMESTAMPTZ

TIMESTAMPTZ stores a real moment in time (internally UTC) and shows it in your session time zone. Use it for almost everything.

NUMERIC

Exact decimal numbers. Use for money and anything that must not have rounding errors.

ENUM

A fixed list of allowed values. Simple, but changing it later is awkward. A lookup table or a CHECK is more flexible.
CREATE TABLE products (
  id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name      TEXT NOT NULL,
  price     NUMERIC(10,2) NOT NULL CHECK (price >= 0),
  tags      TEXT[] DEFAULT '{}',          -- array column
  attrs     JSONB  DEFAULT '{}',          -- JSON column
  created   TIMESTAMPTZ NOT NULL DEFAULT now()
);

SELECT * FROM products WHERE 'sale' = ANY(tags);   -- array search
SELECT '42'::int + 1;                               -- cast with ::
SELECT gen_random_uuid();                           -- built in since PG 13

JSON and JSONB

Postgres can store JSON documents inside a normal table. This gives you "a bit of MongoDB" while keeping SQL.

JSONJSONB
StorageExact text copyBinary, parsed
Keeps key order and duplicatesYesNo
Faster to queryNoYes
Can be indexed (GIN)NoYes

In almost every case you want JSONB.

-- a column: attrs JSONB
SELECT attrs->'color'            FROM products;   -- ->  returns JSON   ("red")
SELECT attrs->>'color'           FROM products;   -- ->> returns TEXT   (red)
SELECT attrs#>>'{size,width}'    FROM products;   -- path into nested JSON

SELECT * FROM products WHERE attrs @> '{"color":"red"}';   -- contains
SELECT * FROM products WHERE attrs ? 'warranty';            -- key exists

-- speed it up with a GIN index
CREATE INDEX idx_products_attrs ON products USING GIN (attrs);

-- update one key without rewriting the whole document in your code
UPDATE products SET attrs = jsonb_set(attrs, '{color}', '"blue"') WHERE id = 1;
When to use JSONBGood for flexible, rarely-joined data (settings, extra attributes, API payloads). Do not hide core, relational data in JSONB: you lose foreign keys, constraints and easy joins.

PostgreSQL index types

TypeBest for
B-tree (default)Equality, ranges, sorting. The right choice most of the time.
HashOnly equality (=). Rarely needed, B-tree is usually fine.
GIN"Many values inside one cell": JSONB, arrays, full-text search, pg_trgm fuzzy search.
GiSTGeometric data, ranges, nearest-neighbor, PostGIS.
BRINHuge tables where data is naturally ordered (like time-series logs). Very small index.
SP-GiSTNon-balanced structures (phone prefixes, IP ranges).

Special kinds of indexes

-- Partial index: only some rows (smaller and faster)
CREATE INDEX idx_orders_open ON orders (created_at) WHERE status = 'open';

-- Expression index: for queries that use a function
CREATE INDEX idx_users_lower_email ON users (LOWER(email));
-- now this can use it:  WHERE LOWER(email) = 'a@b.com'

-- Covering index: INCLUDE extra columns so Postgres can answer from the index alone
CREATE INDEX idx_orders_cust ON orders (customer_id) INCLUDE (total);

-- Build an index on a live table without blocking writes
CREATE INDEX CONCURRENTLY idx_big ON big_table (col);
Index-only scanIf all the columns a query needs are in the index, Postgres does not need to touch the table at all. This is fast, but it also depends on VACUUM keeping the visibility map up to date.

EXPLAIN and query performance

EXPLAIN shows the plan Postgres will use. EXPLAIN ANALYZE actually runs the query and shows real times and row counts.

EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42;

-- Example result (shortened):
-- Index Scan using idx_orders_customer on orders
--   (cost=0.29..8.31 rows=1 width=40) (actual time=0.02..0.03 rows=3 loops=1)
--   Index Cond: (customer_id = 42)
-- Planning Time: 0.1 ms
-- Execution Time: 0.05 ms
CarefulEXPLAIN ANALYZE really executes the statement. For UPDATE or DELETE, wrap it in BEGIN; ... ROLLBACK;.

Scan types you must know

NodeMeaning
Seq ScanReads the whole table. Fine for small tables or when you need most rows. Bad on a big table with a selective filter.
Index ScanUses the index, then reads the matching rows from the table.
Index Only ScanAnswers from the index alone. Fastest.
Bitmap Index/Heap ScanMedium number of rows: collect matches from the index, then read table pages in order.

Join algorithms

  • Nested Loop: for each row on one side, look up the other side. Great when one side is small and the other has an index.
  • Hash Join: build a hash table from the smaller side, probe it with the bigger side. Good for large, unsorted data.
  • Merge Join: both sides sorted, then walk through them together. Good when data is already sorted (or indexed).

How to read a plan

  • Read from the innermost / most indented node outwards.
  • cost=a..b: estimated start-up and total cost (no real unit). rows: estimated rows. actual time: real milliseconds.
  • If estimated rows are very different from actual rows, the statistics are old. Run ANALYZE.
  • Look for a Seq Scan with a big Rows Removed by Filter: probably a missing index.

Quick performance checklist

  1. Select only the columns you need, not SELECT *.
  2. Index the columns used in WHERE, JOIN and ORDER BY (and foreign keys).
  3. Avoid functions on indexed columns in WHERE (or create an expression index).
  4. Use keyset pagination instead of big OFFSET.
  5. Check for the N+1 query problem in your app code (one query per row). Fix it with a JOIN or WHERE id = ANY($1).
  6. Use pg_stat_statements to find the slowest queries in real life.
-- Keyset (cursor) pagination: stays fast on page 10,000
SELECT id, title FROM posts
WHERE id < 98765            -- last id the user saw
ORDER BY id DESC
LIMIT 20;

MVCC, VACUUM and autovacuum

This is the most "Postgres-only" topic and a favourite for interviews.

MVCC means Postgres never changes a row in place. When you UPDATE, it writes a new version of the row and marks the old one as dead. Every transaction sees a snapshot of the data from when it started, so:

  • Readers do not block writers, and writers do not block readers.
  • A DELETE only marks the row as dead.

The problem: old dead rows (dead tuples) pile up. This is called bloat. The cleaning tool is VACUUM.

CommandWhat it does
VACUUMMarks dead-row space as reusable inside the table. Does not block normal reads and writes. Does not usually shrink the file.
VACUUM FULLRewrites the whole table into a new file and returns space to the OS. Takes an exclusive lock, so use it rarely.
ANALYZEUpdates the statistics the planner uses to choose good plans.
autovacuumA background worker that runs VACUUM and ANALYZE for you. Keep it ON.
Long transactions hurtA transaction left open for hours stops VACUUM from removing dead rows newer than its snapshot. The result is table bloat and slower queries. Keep transactions short.

Also: transaction ID wraparound

Postgres numbers transactions with a 32-bit counter. VACUUM "freezes" old rows so the counter can safely wrap around. If autovacuum is blocked for too long, Postgres can be forced to stop accepting writes to protect data. This is rare, but it is a good senior-level detail to mention.

Isolation levels and locking in Postgres

LevelIn PostgreSQL
Read Committed (default)Each statement sees data committed before that statement started.
Repeatable ReadThe whole transaction sees one snapshot. No dirty, non-repeatable or phantom reads. May fail with a "could not serialize" error that you should retry.
SerializableActs as if transactions ran one after another. Can abort transactions, so your app must retry.

Postgres treats Read Uncommitted exactly like Read Committed: dirty reads never happen.

Row-level locks

BEGIN;
SELECT * FROM tickets WHERE id = 5 FOR UPDATE;   -- lock this row, others wait
UPDATE tickets SET status = 'sold' WHERE id = 5;
COMMIT;

-- Job queue pattern: take a free job, skip rows other workers have locked
SELECT * FROM jobs WHERE status = 'new'
ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED;
  • FOR UPDATE – lock rows so nobody else can change them.
  • FOR SHARE – others can read-lock but not change.
  • SKIP LOCKED – ignore locked rows (great for queues).
  • NOWAIT – fail at once instead of waiting.

Deadlock

Transaction A waits for B, and B waits for A. Postgres detects this after about 1 second and cancels one of them with an error. Prevention: always lock rows in the same order, keep transactions short, and retry on deadlock errors.

Optimistic vs pessimistic locking

  • Pessimistic: lock first (SELECT ... FOR UPDATE). Safe, but others wait.
  • Optimistic: no lock; add a version column and update only if it did not change. If 0 rows were updated, someone else changed it, so retry.
UPDATE products SET stock = stock - 1, version = version + 1
WHERE id = 7 AND version = 3;      -- 0 rows updated => conflict, retry

UPSERT, RETURNING and other Postgres tricks

-- UPSERT: insert, or update if the key already exists
INSERT INTO page_views (page, views)
VALUES ('/home', 1)
ON CONFLICT (page)
DO UPDATE SET views = page_views.views + 1;

-- Or ignore duplicates
INSERT INTO tags (name) VALUES ('sql') ON CONFLICT DO NOTHING;

-- RETURNING: get the row back without a second query
INSERT INTO users (email) VALUES ('a@b.com') RETURNING id, created_at;
UPDATE orders SET status = 'paid' WHERE id = 9 RETURNING *;
DELETE FROM sessions WHERE expires_at < now() RETURNING id;

-- DISTINCT ON: first row per group (Postgres only)
SELECT DISTINCT ON (customer_id) customer_id, id, order_date
FROM orders
ORDER BY customer_id, order_date DESC;     -- latest order per customer

-- FILTER: conditional aggregates, cleaner than CASE
SELECT COUNT(*) AS total,
       COUNT(*) FILTER (WHERE status = 'delivered') AS delivered
FROM orders;

-- generate_series: make rows from nothing (calendars, test data)
SELECT generate_series(1, 5);
SELECT d::date FROM generate_series('2026-01-01'::date, '2026-01-07', '1 day') d;

-- ILIKE: case-insensitive LIKE
SELECT * FROM users WHERE name ILIKE 'ali%';

-- string_agg / array_agg: combine rows into one value
SELECT customer_id, string_agg(product, ', ') FROM purchases GROUP BY customer_id;
Bulk loadingFor loading lots of rows, use COPY (or multi-row INSERT) instead of thousands of single inserts. It is many times faster.

Full-text search and fuzzy search

You do not always need Elasticsearch. Postgres can do good text search built in.

-- Full-text: understands words, not just characters ("running" matches "run")
SELECT title FROM articles
WHERE to_tsvector('english', title || ' ' || body) @@ plainto_tsquery('english', 'database index');

-- Make it fast: a GIN index on the tsvector
CREATE INDEX idx_articles_fts ON articles
USING GIN (to_tsvector('english', title || ' ' || body));

-- Fuzzy / typo-friendly search with the pg_trgm extension
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_users_name_trgm ON users USING GIN (name gin_trgm_ops);
SELECT name FROM users WHERE name % 'Muhamad';      -- finds "Muhammad"
SELECT name FROM users WHERE name ILIKE '%ahm%';    -- the trigram index helps here too

For very large search systems with heavy ranking needs, a dedicated search engine can still be better. For many apps, Postgres is enough and keeps your stack simple.

Table partitioning

Splitting one huge table into smaller physical pieces (partitions) while you still query it as one table.

CREATE TABLE events (
  id BIGINT GENERATED ALWAYS AS IDENTITY,
  created_at TIMESTAMPTZ NOT NULL,
  payload JSONB
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_11 PARTITION OF events
  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
  • Range: by date or number ranges (most common, for logs and time series).
  • List: by fixed values (country, region).
  • Hash: spread rows evenly across N partitions.

Benefits: partition pruning (queries touch only the needed partitions), fast deletion of old data (drop a partition instead of a giant DELETE), smaller indexes, easier maintenance. Cost: more complexity; the partition key must be part of the primary key.

Partitioning vs sharding: partitioning is inside one database server. Sharding spreads data across many servers.

WAL, replication and backups

WAL (Write-Ahead Log)

Before Postgres changes a data file, it first writes the change to a sequential log, the WAL. If the server crashes, Postgres replays the WAL to recover. This is how Durability (the D in ACID) works. It also powers replication and point-in-time recovery.

Replication

TypeWhat it does
Streaming (physical)A standby copies the WAL from the primary. The whole cluster is copied byte by byte. Standbys can serve read-only queries (read replicas).
LogicalPublish selected tables and changes (publication / subscription). Works across versions and lets you copy only some tables.
Sync vs asyncSync: the commit waits for the standby (safer, slower). Async: does not wait (faster, tiny risk of losing the last transactions in a failover).

Replication lag: a read replica can be a little behind. If a user saves something and instantly reads from a replica, they might not see it. Read your own writes from the primary.

Backups

  • Logical: pg_dump / pg_restore – SQL or custom-format export. Simple, good for small and medium databases and for moving between versions.
  • Physical: pg_basebackup + archived WAL – a copy of the data files. Enables PITR (Point-In-Time Recovery): restore to "10:42 yesterday".

Connections, pooling and scaling

Each Postgres connection is a separate server process and uses memory (roughly several MB). Thousands of direct connections are a bad idea.

  • Connection pooling: reuse a small set of connections. In Node.js, pg's Pool does this inside your app. PgBouncer (or a managed pooler such as the ones in Supabase / Neon) does it between many app servers and the database.
  • Serverless apps (Vercel, Lambda) open many short connections, so a pooler is almost required.
  • max_connections is a setting; do not just raise it, use a pool.

Scaling steps (in the usual order)

  1. Fix slow queries and add the right indexes.
  2. Add caching (Redis) for hot reads.
  3. Add connection pooling.
  4. Scale up: more CPU, RAM, faster disks.
  5. Add read replicas for read-heavy traffic.
  6. Partition big tables.
  7. Shard across servers (last, because it is the most complex).

Important settings to know by name

  • shared_buffers – Postgres's own memory cache (often about 25% of RAM).
  • work_mem – memory for each sort or hash operation (per operation, not per connection!).
  • effective_cache_size – a hint to the planner about total cache available.
  • max_connections, autovacuum, random_page_cost.

Roles, security and Row Level Security

CREATE ROLE app_user LOGIN PASSWORD 'use-a-secret-manager';
GRANT SELECT, INSERT, UPDATE ON orders TO app_user;
REVOKE DELETE ON orders FROM app_user;
  • Follow least privilege: the app user should not be a superuser and should not own the tables.
  • SQL injection happens when you build a query by joining strings with user input. Always use parameterized queries: the value is sent separately and never run as SQL.
-- BAD (in code): "SELECT * FROM users WHERE email = '" + email + "'"
-- GOOD (parameter $1):
SELECT * FROM users WHERE email = $1;

Row Level Security (RLS)

RLS lets the database itself decide which rows each user can see. It is the base of Supabase security.

ALTER TABLE notes ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_notes ON notes
  USING (owner_id = current_setting('app.user_id')::int);

Using PostgreSQL from Node.js (MERN developer section)

Since you know Node and Express, here is how Postgres looks in a real backend, with the pg package.

import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });

// 1. Parameterized query (safe from SQL injection)
export async function getUser(email) {
  const { rows } = await pool.query('SELECT id, email FROM users WHERE email = $1', [email]);
  return rows[0] ?? null;
}

// 2. Transaction: use ONE client for all steps
export async function transfer(from, to, amount) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
    await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();          // always give the connection back!
  }
}
Common bugRunning a transaction with pool.query() for each step. Each call may use a different connection, so BEGIN and COMMIT do not belong together. Use pool.connect() to get one client, and always release() it, or your pool will run out of connections.

Other things to know

  • Migrations: keep schema changes in versioned files (tools: Prisma Migrate, Drizzle, Knex, node-pg-migrate). Never edit the production schema by hand.
  • ORM vs query builder vs raw SQL: Prisma/Drizzle/Sequelize give speed of development and type safety; raw SQL gives full control for complex queries. Good developers know both.
  • N+1 problem: loading 100 posts and then running 100 extra queries for their authors. Fix with a JOIN, include/relations in your ORM, or one query with WHERE id = ANY($1).
  • Postgres vs Mongo in a MERN app: use Postgres when you have strong relations, money, reports or need transactions; MongoDB is fine for flexible documents.
  • Postgres returns BIGINT and NUMERIC as strings in the pg driver, so convert them on purpose to avoid precision bugs.

Common interview query patterns

These come up again and again. Try each one in the Query Lab before you look at the answers.

Nth highest salary

DENSE_RANK() in a subquery, filter rank = N. Or ORDER BY salary DESC LIMIT 1 OFFSET N-1 on SELECT DISTINCT salaries.

Find duplicates

GROUP BY col HAVING COUNT(*) > 1

Delete duplicates, keep one

Use ROW_NUMBER() OVER (PARTITION BY ... ) in a CTE, delete where rn > 1.

Top N per group

ROW_NUMBER() / RANK() with PARTITION BY group, filter rn <= N.

Rows with no match

LEFT JOIN ... WHERE right.id IS NULL or NOT EXISTS.

Running total

SUM(x) OVER (ORDER BY date)

Month-over-month change

LAG() over DATE_TRUNC('month', ...) grouped totals.

Consecutive days (streaks)

Subtract ROW_NUMBER() from the date; equal results mean the same streak.

Employees earning more than their manager

Self join: e.manager_id = m.id AND e.salary > m.salary.

Median

PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)
-- 2nd highest salary, safe when there are ties
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- Delete duplicate emails, keep the oldest row
DELETE FROM users
WHERE id IN (
  SELECT id FROM (
    SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
    FROM users
  ) t WHERE rn > 1
);

Schema design tips (what interviewers like to hear)

  • Give every table a primary key. Name things consistently (snake_case, plural tables).
  • Add created_at and updated_at to most tables. Use TIMESTAMPTZ.
  • Always add foreign keys and index the foreign key column (Postgres does not do this for you automatically).
  • Use NOT NULL by default. Allow NULL only when "unknown" is truly meaningful.
  • Use soft delete (deleted_at) when you need history, but remember to filter it everywhere (a partial index WHERE deleted_at IS NULL helps).
  • Store money as NUMERIC or integer cents, and store a currency code.
  • Do not put a comma-separated list in a column. Make a child table or an array / JSONB if it is truly just a tag-like list.
  • Plan for change: use migrations, and add columns as nullable or with a default first, then backfill.
Mini design exerciseDesign a tuition academy system: teachers, students, classes, enrollments (junction), attendance (class_id, student_id, date, status with a unique key on those three), tests and test_results. Explain each key and index you chose. This kind of exercise is common in interviews.
You finished the reading!Now test yourself: go to Q&A Practice, look at the Diagrams, and write real queries on real data in the Query Lab. Speaking the answers out loud is the best interview practice.

Q&A Practice

Click a question, try to answer it in your head (or out loud) first, then open the answer. Mark it Known or Revise. Your marks are saved in this browser.

Level: Status:

Diagrams

Pictures are easier to remember than paragraphs. In an interview, you can even draw these on a whiteboard.

JOIN types (Venn view)

Left circle = table A, right circle = table B. The blue part is what the join returns.

LEFT JOIN with WHERE b.id IS NULL is called an anti-join: rows in A that have no match in B.

Query Lab

A real PostgreSQL database that runs inside your browser (WebAssembly, powered by PGlite). Nothing is sent to a server. Practice on sample data, then solve the challenges. Press Ctrl + Enter to run.

⏳ Loading PostgreSQL… (about 3 MB, only the first time)

Sample tables

Playground

Tip: you can also try EXPLAIN ANALYZE, CREATE INDEX, INSERT, BEGIN / ROLLBACK.

Challenges

Write the query, press Run & check. Your result is compared with the expected result (column names do not matter; row order only matters when the task says "ordered"). If you changed the data in the playground, press Reset database first.

All guides