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.
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
| Group | Full name | What it does | Commands |
|---|---|---|---|
| DDL | Data Definition Language | Creates or changes the structure | CREATE ALTER DROP TRUNCATE |
| DML | Data Manipulation Language | Changes the data | INSERT UPDATE DELETE |
| DQL | Data Query Language | Reads data | SELECT |
| DCL | Data Control Language | Permissions | GRANT REVOKE |
| TCL | Transaction Control Language | Groups work into a transaction | BEGIN COMMIT ROLLBACK SAVEPOINT |
SQL database vs NoSQL (for example MongoDB)
| SQL (relational) | NoSQL (document, like MongoDB) | |
|---|---|---|
| Structure | Fixed schema, tables and rows | Flexible schema, JSON-like documents |
| Relations | Strong: foreign keys and JOINs | Usually embed data or reference by id |
| Consistency | ACID transactions are the default | Depends on the database and settings |
| Best for | Money, orders, users, reports, anything with many relations | Fast-changing shapes, content, logs, simple access patterns |
Data types and constraints
Types say what kind of value a column can hold. Constraints are rules that protect your data.
| Kind | Common types |
|---|---|
| Whole numbers | SMALLINT, INTEGER, BIGINT |
| Decimals | NUMERIC(10,2) (exact, use for money), REAL / DOUBLE PRECISION (approximate) |
| Text | CHAR(n), VARCHAR(n), TEXT |
| Date and time | DATE, TIME, TIMESTAMP, TIMESTAMPTZ |
| True / false | BOOLEAN |
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, likeprice > 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()
);
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)
| Option | Meaning |
|---|---|
RESTRICT / NO ACTION | Block the delete if children exist (default) |
CASCADE | Delete the children too |
SET NULL | Set the child's foreign key to NULL |
SET DEFAULT | Set 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
| Tool | Meaning |
|---|---|
= <> < > <= >= | Compare values. <> and != both mean "not equal". |
AND OR NOT | Combine conditions. AND runs before OR, so use brackets. |
IN (...) | Matches any value in a list |
BETWEEN a AND b | Inclusive range (includes a and b) |
LIKE | % = any number of characters, _ = exactly one character |
AS | Gives a column or table a nickname (alias) |
ORDER 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 = NULLis not true. UseIS NULLandIS NOT NULL. NULL + 5is NULL.COUNT(*)counts all rows.COUNT(col)skips NULLs.COUNT(DISTINCT col)counts unique non-NULL values.SUM,AVG,MIN,MAXignore 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;
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';
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
| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Removes | Rows (can use WHERE) | All rows | The whole table |
| Type | DML | DDL | DDL |
| Speed | Slower (row by row) | Very fast | Fast |
| Triggers fire? | Yes | No (row triggers) | No |
| Rollback? | Yes | Yes in PostgreSQL | Yes in PostgreSQL |
| Table structure stays? | Yes | Yes | No |
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 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.
| Join | Returns |
|---|---|
INNER JOIN | Only rows that match in both tables |
LEFT JOIN | All rows from the left table + matches from the right (NULL if no match) |
RIGHT JOIN | All rows from the right table + matches from the left |
FULL JOIN | All rows from both tables, matched where possible |
CROSS JOIN | Every row of A with every row of B (A Γ B rows) |
| Self join | A 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;
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;
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.
| Operator | Result |
|---|---|
UNION | All rows from both, duplicates removed (does extra sorting or hashing) |
UNION ALL | All rows from both, duplicates kept (faster) |
INTERSECT | Rows that are in both results |
EXCEPT | Rows 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)
)
| Function | What 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;
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:
FROMandJOINβ find and combine the tablesWHEREβ filter rowsGROUP BYβ make groupsHAVINGβ filter groupsSELECTβ pick columns, calculate expressions and window functionsDISTINCTβ remove duplicatesORDER BYβ sortLIMIT/OFFSETβ cut the result
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.
| Form | Rule (simple words) | Bad example β fix |
|---|---|---|
| 1NF | Every cell holds one value. No lists in a cell, no repeating columns. | phones = '0300,0311' β one row per phone in a phones table |
| 2NF | 1NF + 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 |
| 3NF | 2NF + 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.
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 BYand prefixLIKE 'abc%'. - Primary key and unique constraints create an index automatically.
- Cost: indexes use disk space and make
INSERT,UPDATE,DELETEslower, 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
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
| Problem | What happens |
|---|---|
| Dirty read | You read data that another transaction has not committed yet |
| Non-repeatable read | You read a row twice and get different values, because someone committed an update between |
| Phantom read | You run the same query twice and new rows appear (or vanish), because someone inserted or deleted |
Isolation levels (SQL standard)
| Level | Dirty read | Non-repeatable | Phantom |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | No | Possible | Possible |
| Repeatable Read | No | No | Possible (standard) * |
| Serializable | No | No | No |
* 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.
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)
| PostgreSQL | MySQL | |
|---|---|---|
| Feature set | More advanced SQL, JSONB, arrays, many index types, strong extensions | Simpler, very popular, great read speed for simple workloads |
| Standards | Follows the SQL standard closely | Has some own behaviours |
| Transactional DDL | Yes, you can roll back CREATE TABLE | No (DDL commits automatically) |
| Concurrency | MVCC, needs VACUUM | MVCC with undo logs (InnoDB) |
Handy psql commands
| Command | Does |
|---|---|
\l | List databases |
\c dbname | Connect to a database |
\dt | List tables |
\d table | Describe a table (columns, indexes, constraints) |
\di / \df / \dv | List indexes / functions / views |
\x | Toggle expanded (vertical) output |
\timing | Show how long each query takes |
\q | Quit |
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 aCHECK 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.
JSON | JSONB | |
|---|---|---|
| Storage | Exact text copy | Binary, parsed |
| Keeps key order and duplicates | Yes | No |
| Faster to query | No | Yes |
| Can be indexed (GIN) | No | Yes |
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;
PostgreSQL index types
| Type | Best for |
|---|---|
| B-tree (default) | Equality, ranges, sorting. The right choice most of the time. |
| Hash | Only equality (=). Rarely needed, B-tree is usually fine. |
| GIN | "Many values inside one cell": JSONB, arrays, full-text search, pg_trgm fuzzy search. |
| GiST | Geometric data, ranges, nearest-neighbor, PostGIS. |
| BRIN | Huge tables where data is naturally ordered (like time-series logs). Very small index. |
| SP-GiST | Non-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);
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
EXPLAIN ANALYZE really executes the statement. For UPDATE or DELETE, wrap it in BEGIN; ... ROLLBACK;.Scan types you must know
| Node | Meaning |
|---|---|
| Seq Scan | Reads the whole table. Fine for small tables or when you need most rows. Bad on a big table with a selective filter. |
| Index Scan | Uses the index, then reads the matching rows from the table. |
| Index Only Scan | Answers from the index alone. Fastest. |
| Bitmap Index/Heap Scan | Medium 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
- Select only the columns you need, not
SELECT *. - Index the columns used in
WHERE,JOINandORDER BY(and foreign keys). - Avoid functions on indexed columns in
WHERE(or create an expression index). - Use keyset pagination instead of big
OFFSET. - 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). - Use
pg_stat_statementsto 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
DELETEonly marks the row as dead.
The problem: old dead rows (dead tuples) pile up. This is called bloat. The cleaning tool is VACUUM.
| Command | What it does |
|---|---|
VACUUM | Marks dead-row space as reusable inside the table. Does not block normal reads and writes. Does not usually shrink the file. |
VACUUM FULL | Rewrites the whole table into a new file and returns space to the OS. Takes an exclusive lock, so use it rarely. |
ANALYZE | Updates the statistics the planner uses to choose good plans. |
| autovacuum | A background worker that runs VACUUM and ANALYZE for you. Keep it ON. |
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
| Level | In PostgreSQL |
|---|---|
| Read Committed (default) | Each statement sees data committed before that statement started. |
| Repeatable Read | The whole transaction sees one snapshot. No dirty, non-repeatable or phantom reads. May fail with a "could not serialize" error that you should retry. |
| Serializable | Acts 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
versioncolumn 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;
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
| Type | What 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). |
| Logical | Publish selected tables and changes (publication / subscription). Works across versions and lets you copy only some tables. |
| Sync vs async | Sync: 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'sPooldoes 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_connectionsis a setting; do not just raise it, use a pool.
Scaling steps (in the usual order)
- Fix slow queries and add the right indexes.
- Add caching (Redis) for hot reads.
- Add connection pooling.
- Scale up: more CPU, RAM, faster disks.
- Add read replicas for read-heavy traffic.
- Partition big tables.
- 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!
}
}
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/relationsin your ORM, or one query withWHERE 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
BIGINTandNUMERICas strings in thepgdriver, 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(*) > 1Delete duplicates, keep one
UseROW_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)
SubtractROW_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_atandupdated_atto most tables. UseTIMESTAMPTZ. - Always add foreign keys and index the foreign key column (Postgres does not do this for you automatically).
- Use
NOT NULLby 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 indexWHERE deleted_at IS NULLhelps). - Store money as
NUMERICor 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.
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.