Questions 241–260 of 501 · 0 of 20 on this page marked learned
241.sql-0241Mediummid
Write a PostgreSQL trigger that keeps an updated_at column current on every UPDATE.
Create a PL/pgSQL function that sets NEW.updated_at = now() and returns NEW, then attach it with CREATE TRIGGER ... BEFORE UPDATE ... FOR EACH ROW. A BEFORE trigger can change the row before it is written, while in SQLite an AFTER UPDATE trigger that runs an UPDATE on the same row does the same job.
Full answer
sql
CREATE TABLE items (id int PRIMARY KEY, name text, updated_at timestamptz DEFAULT '2026-01-01');
CREATE FUNCTION touch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := TIMESTAMPTZ '2026-03-01 00:00:00+00';
RETURN NEW;
END $$;
CREATE TRIGGER items_touch BEFORE UPDATE ON items FOR EACH ROW EXECUTE FUNCTION touch();
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at > TIMESTAMPTZ '2026-01-01 00:00:00+00' AS touched FROM items;
id
name
touched
1
blue pen
true
The sample function writes a fixed timestamp instead of now() so the output is stable. The BEFORE trigger changed the row in flight, so the update and the new timestamp were written together. Returning NULL from a BEFORE row trigger would skip the write entirely.
SQLite has no trigger functions; the usual form is:
sql
CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, updated_at TEXT DEFAULT '2026-01-01');
CREATE TRIGGER items_touch AFTER UPDATE ON items
WHEN NEW.updated_at IS OLD.updated_at
BEGIN
UPDATE items SET updated_at = '2026-03-01' WHERE id = NEW.id;
END;
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at FROM items;
id
name
updated_at
1
blue pen
2026-03-01
The SQLite trigger runs a second UPDATE. It does not loop, because recursive triggers are off by default, and the WHEN guard means the inner update does not fire it again even if they were on.
sql
CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, updated_at TEXT DEFAULT '2026-01-01');
CREATE TRIGGER items_touch AFTER UPDATE ON items
WHEN NEW.updated_at IS OLD.updated_at
BEGIN
UPDATE items SET updated_at = '2026-03-01' WHERE id = NEW.id;
END;
INSERT INTO items (id, name) VALUES (1, 'pen');
UPDATE items SET name = 'blue pen' WHERE id = 1;
SELECT id, name, updated_at FROM items;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
PostgreSQL triggers call a trigger function
BEFORE row triggers can modify NEW
Return NEW to write the row, NULL to skip it
SQLite uses an AFTER trigger with an UPDATE
Common mistakes
Using an AFTER trigger in PostgreSQL to modify NEW
Writing a SQLite trigger that recursively fires itself
Follow-ups
How would you skip updates that change nothing?
What does FOR EACH STATEMENT do?
Tips
Explain why BEFORE is the right timing
242.sql-0242Mediummid
What are the risks of putting business logic in triggers?
Triggers run implicitly, so developers reading application code do not see them, and bulk operations can behave unexpectedly slowly. Chains of triggers are hard to debug and test, ordering among several triggers can surprise, and logic is split between the database and the application. They remain a good fit for small, always-true rules: audit rows, timestamps and derived counters.
Full answer
Problems teams run into:
Hidden behaviour. A one-row UPDATE in code silently performs five writes.
Performance. Row-level triggers run once per row, so a 1-million-row update fires a million times.
Cascades. Trigger A updates table B, whose trigger updates table C, and an error surfaces far from its cause.
Testing and deployment. Trigger code lives in migrations and is often missed by code review and unit tests.
External side effects. Sending email or calling an API from a trigger cannot be rolled back with the transaction.
Good uses: auditing, maintaining updated_at, keeping a denormalized counter in sync, and enforcing rules that must hold no matter which client writes.
A middle path is to keep the rule in the database but make it visible: name triggers clearly, keep each one short, and list them in the schema documentation. For side effects, write an outbox row in the trigger and let a separate worker act on it after commit.
Key points
Triggers hide behaviour from application readers
Row-level triggers multiply work on bulk writes
Trigger chains are hard to debug
Use them for audits, timestamps and invariants
Use an outbox for side effects
Common mistakes
Sending notifications from inside a trigger
Building workflows out of chained triggers
Follow-ups
What is the transactional outbox pattern?
How would you test trigger behaviour?
Tips
Give both risks and legitimate uses
243.sql-0243Mediummid
What is a stored procedure, and how does a PostgreSQL procedure differ from a function?
A stored procedure is code stored and run inside the database, called by name. In PostgreSQL, a FUNCTION returns a value and can be used inside queries, but cannot commit or roll back. A PROCEDURE (PostgreSQL 11+) is invoked with CALL, returns no value in the usual way, and can control transactions with COMMIT inside its body. SQLite has no stored procedures; logic lives in the application or in application-defined functions.
Full answer
A function used in a query:
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
CREATE FUNCTION annual_bonus(salary int) RETURNS int LANGUAGE sql IMMUTABLE AS $$ SELECT salary / 10 $$;
SELECT name, annual_bonus(salary) AS bonus FROM employees WHERE id <= 2 ORDER BY id;
name
bonus
Asha
12000
Ravi
9500
A procedure that applies a raise, called with CALL:
sql
CREATE PROCEDURE give_raise(dept int, pct int) LANGUAGE plpgsql AS $$
BEGIN
UPDATE employees SET salary = salary + salary * pct / 100 WHERE dept_id = dept;
END $$;
CALL give_raise(2, 10);
SELECT name, salary FROM employees WHERE dept_id = 2 ORDER BY id;
name
salary
Tom
77000
Sara
68200
Reasons teams use them: fewer round trips for multi-step operations, permissions that let users run the procedure without direct table access (with SECURITY DEFINER), and logic shared by several applications.
Reasons to be careful: they are harder to version, test and debug than application code, and they tie the system to one engine's language. Many teams keep only data-heavy operations, such as batch maintenance, in the database.
SQLite instead lets the host program register functions (for example Python's create_function), which run in the application process.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Stored procedures are named code run in the database
PostgreSQL functions return values and work inside queries
Procedures use CALL and can COMMIT inside
SQLite has no stored procedures
Common mistakes
Putting every business rule in stored code without tests
Expecting a function to COMMIT in PostgreSQL
Follow-ups
What does SECURITY DEFINER do?
When would a procedure beat application code?
Tips
Contrast function and procedure clearly
244.sql-0244Mediummid
A SQLite view refers to a column that was later renamed in the base table. What happens when you query the view?
Since SQLite 3.25, ALTER TABLE RENAME COLUMN also rewrites references in views and triggers, so the view keeps working, though its unaliased output column takes the new name. Dropping the column, or recreating the table under a new definition without the column, leaves the view broken, and the error appears only when the view is queried. PostgreSQL tracks view dependencies and refuses to drop a column a view uses unless CASCADE is given.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
Renaming is handled:
sql
CREATE VIEW pay AS SELECT name, salary FROM employees;
ALTER TABLE employees RENAME COLUMN salary TO base_salary;
SELECT * FROM pay WHERE name = 'Asha';
name
base_salary
Asha
120000
The view still works, but its output column is now called base_salary, because SQLite rewrote the view text. Queries that select salary from the view would fail. Giving view columns explicit aliases (base_salary AS salary) keeps the view's interface stable across renames.
Dropping a column the view uses is refused in SQLite 3.35+, because the view would break:
sql
CREATE VIEW pay2 AS SELECT name, hire_date FROM employees;
ALTER TABLE employees DROP COLUMN hire_date;
-- error on purpose
text
Error: error in view pay2 after drop column: no such column: hire_date
PostgreSQL is stricter in the same situation and names the dependent view:
sql
CREATE VIEW pay AS SELECT name, salary FROM employees;
ALTER TABLE employees DROP COLUMN salary;
-- error on purpose
text
Error: cannot drop column salary of table employees because other objects depend on it
When views break after a migration, list them with SELECT name, sql FROM sqlite_schema WHERE type = 'view', or in PostgreSQL use the dependency views, and recreate them as part of the migration.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
CREATE VIEW pay AS SELECT name, salary FROM employees;
ALTER TABLE employees RENAME COLUMN salary TO base_salary;
SELECT * FROM pay WHERE name = 'Asha';
-- error on purpose
CREATE VIEW pay2 AS SELECT name, hire_date FROM employees;
ALTER TABLE employees DROP COLUMN hire_date;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
SQLite 3.25+ RENAME COLUMN updates views and triggers
Dropping a used column is refused
PostgreSQL tracks dependencies and needs CASCADE
Recreate dependent views in migrations
Common mistakes
Discovering broken views only when a report fails
Dropping columns with CASCADE without checking what it removes
Follow-ups
How would you find all objects that depend on a column?
How would you change a column used by many views?
Tips
Check dependencies before migrations
245.sql-0245Mediummid
How would you keep a comment_count column on posts accurate as comments are added and deleted?
Use AFTER INSERT and AFTER DELETE triggers on comments that add or subtract 1 from the matching post's comment_count. The count updates in the same transaction as the comment, so it cannot drift from normal writes. Run a periodic check that recomputes counts with GROUP BY to catch drift from bulk loads or disabled triggers.
Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, comment_count INTEGER NOT NULL DEFAULT 0);
CREATE TABLE comments (id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL);
CREATE TRIGGER c_ins AFTER INSERT ON comments BEGIN
UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
END;
CREATE TRIGGER c_del AFTER DELETE ON comments BEGIN
UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
END;
INSERT INTO posts (id) VALUES (1), (2);
INSERT INTO comments (post_id) VALUES (1), (1), (2);
DELETE FROM comments WHERE id = 1;
SELECT id, comment_count FROM posts ORDER BY id;
id
comment_count
1
1
2
1
Post 1 got two comments and lost one; its counter reads 1. The triggers run in the same transaction as the comment write, so a rolled-back insert also rolls back its increment.
A drift check compares the counter with a fresh count:
sql
SELECT p.id, p.comment_count, COUNT(c.id) AS actual
FROM posts p LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.comment_count
HAVING p.comment_count <> COUNT(c.id);
id
comment_count
actual
(0 rows)
No rows come back, which means every counter matches. Any row returned would name a post whose counter needs repair.
Under heavy concurrent writes in a server engine, every comment on a popular post updates the same row, which becomes a hot spot. Options then include batching increments or computing counts asynchronously.
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, comment_count INTEGER NOT NULL DEFAULT 0);
CREATE TABLE comments (id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL);
CREATE TRIGGER c_ins AFTER INSERT ON comments BEGIN
UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
END;
CREATE TRIGGER c_del AFTER DELETE ON comments BEGIN
UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
END;
INSERT INTO posts (id) VALUES (1), (2);
INSERT INTO comments (post_id) VALUES (1), (1), (2);
DELETE FROM comments WHERE id = 1;
SELECT id, comment_count FROM posts ORDER BY id;
SELECT p.id, p.comment_count, COUNT(c.id) AS actual
FROM posts p LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.comment_count
HAVING p.comment_count <> COUNT(c.id);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
AFTER INSERT and AFTER DELETE triggers adjust the counter
Counter changes share the comment's transaction
Recompute periodically to detect drift
A single hot counter row can become a bottleneck
Common mistakes
Updating counters only in some application paths
Never verifying denormalized counts
Follow-ups
What about comments that move between posts?
How would you handle a very popular post?
Tips
Include a drift check
246.sql-0246Easyfresher
What happens if a BEFORE INSERT trigger raises an error in SQLite?
The INSERT is aborted and the error message is returned to the caller; RAISE(ABORT, 'message') undoes the current statement's changes, and the row is not stored. RAISE(FAIL) keeps earlier rows from the same statement, RAISE(ROLLBACK) rolls back the whole transaction, and RAISE(IGNORE) silently skips the row.
Full answer
sql
CREATE TABLE users (email TEXT);
CREATE TRIGGER users_email BEFORE INSERT ON users
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(ABORT, 'invalid email'); END;
INSERT INTO users VALUES ('not-an-email');
-- error on purpose
text
Error: invalid email
The message from RAISE reaches the application as the error text. Nothing was inserted:
sql
SELECT COUNT(*) AS rows_stored FROM users;
rows_stored
0
RAISE(IGNORE) skips the offending row without an error, which is easy to miss:
sql
CREATE TABLE u2 (email TEXT);
CREATE TRIGGER u2_email BEFORE INSERT ON u2
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(IGNORE); END;
INSERT INTO u2 VALUES ('bad'), ('ok@example.com');
SELECT email FROM u2;
The bad email was dropped silently, and only the good row remains. Prefer ABORT for validation, so callers know the write failed, and prefer plain CHECK constraints when the rule only looks at the row itself.
sql
-- error on purpose
CREATE TABLE users (email TEXT);
CREATE TRIGGER users_email BEFORE INSERT ON users
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(ABORT, 'invalid email'); END;
INSERT INTO users VALUES ('not-an-email');
SELECT COUNT(*) AS rows_stored FROM users;
CREATE TABLE u2 (email TEXT);
CREATE TRIGGER u2_email BEFORE INSERT ON u2
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(IGNORE); END;
INSERT INTO u2 VALUES ('bad'), ('ok@example.com');
SELECT email FROM u2;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
RAISE(ABORT) cancels the statement with a message
RAISE(IGNORE) skips the row silently
RAISE(ROLLBACK) ends the whole transaction
Use CHECK for simple single-row rules
Common mistakes
Using IGNORE and losing rows without notice
Writing triggers for rules a CHECK can express
Follow-ups
How would PostgreSQL raise a custom error in a trigger?
When would RAISE(FAIL) be useful?
Tips
Contrast ABORT and IGNORE
247.sql-0247Mediummid
What problems does LIMIT ... OFFSET pagination have on large or changing tables?
The engine still reads and discards every skipped row, so page 10,000 costs as much as reading 10,000 pages. And if rows are inserted or deleted between page requests, items shift: a reader can see the same row twice or miss one. Keyset pagination, which continues after the last row seen, avoids both problems.
Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
Page 2 with three posts per page, newest first:
sql
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 3;
id
created
title
5
2026-03-04
e
4
2026-03-03
d
3
2026-03-02
c
A new post arrives before the reader asks for page 3:
sql
INSERT INTO posts VALUES (9, '2026-03-07', 'i');
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 6;
id
created
title
3
2026-03-02
c
2
2026-03-02
b
1
2026-03-01
a
Post 3 ('c') was the last row of page 2 and now appears again at the top of page 3, because every row shifted down by one. Deleting a row would cause the opposite problem, a skipped post.
The cost side: OFFSET 100000 makes the engine walk 100,000 index entries or rows before returning anything. That is fine for small admin tables and a known problem for infinite feeds and API exports.
OFFSET remains reasonable when users jump to arbitrary page numbers on modest data, because keyset pagination cannot jump directly to page 37.
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 3;
INSERT INTO posts VALUES (9, '2026-03-07', 'i');
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 6;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
OFFSET reads and discards the skipped rows
Deep pages get slower
Inserts and deletes shift rows between pages
Keyset pagination fixes both, but cannot jump to page N
Common mistakes
Using OFFSET for infinite scroll on large tables
Paginating without a deterministic ORDER BY
Follow-ups
How does keyset pagination work?
How would you show total pages cheaply?
Tips
Demonstrate the duplicate row after an insert
248.sql-0248Mediummid
Write a keyset (seek) pagination query that returns the next page of posts after the last one shown.
Remember the sort key of the last row shown, then ask for rows that come after it: WHERE (created, id) < (:last_created, :last_id) ORDER BY created DESC, id DESC LIMIT 3. Including the unique id breaks ties when several rows share a timestamp. An index on (created, id) lets the engine seek straight to the starting point.
Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
Page 1:
sql
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3;
id
created
title
8
2026-03-06
h
7
2026-03-05
g
6
2026-03-05
f
The last row shown is (2026-03-05, 6). The next page continues from there:
sql
SELECT id, created, title FROM posts
WHERE (created, id) < ('2026-03-05', 6)
ORDER BY created DESC, id DESC LIMIT 3;
id
created
title
5
2026-03-04
e
4
2026-03-03
d
3
2026-03-02
c
The row-value comparison (created, id) < ('2026-03-05', 6) means "earlier date, or the same date with a smaller id". Without the id, post 7 or 6 could be skipped or repeated, because two posts share 5 March. SQLite 3.15+ and PostgreSQL support row values; elsewhere, write the expanded form created < ? OR (created = ? AND id < ?).
The plan seeks into the index instead of skipping rows:
sql
EXPLAIN QUERY PLAN SELECT id FROM posts WHERE (created, id) < ('2026-03-05', 6) ORDER BY created DESC, id DESC LIMIT 3;
text
QUERY PLAN
SEARCH posts USING COVERING INDEX posts_created_id (created<?)
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3;
SELECT id, created, title FROM posts
WHERE (created, id) < ('2026-03-05', 6)
ORDER BY created DESC, id DESC LIMIT 3;
EXPLAIN QUERY PLAN SELECT id FROM posts WHERE (created, id) < ('2026-03-05', 6) ORDER BY created DESC, id DESC LIMIT 3;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Continue after the last row's sort key
Include a unique column to break ties
Row values express the tie-break compactly
An index on the sort columns makes each page a seek
Common mistakes
Paging on a non-unique column alone
Passing page numbers instead of the last key
Follow-ups
How would you page backwards?
How would you encode the cursor in an API?
Tips
Explain the tie-breaker with the shared date
249.sql-0249Mediummid
A paginated API also needs the total number of matching rows. How can one query return both the page and the total?
Add COUNT(*) OVER () to the SELECT: the window counts all rows that pass WHERE, before LIMIT applies, so each returned row carries the total. It still has to find every matching row, so for very large results consider an estimate, a cached count, or a 'has next page' flag from fetching one extra row.
Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
sql
SELECT id, title, COUNT(*) OVER () AS total
FROM posts ORDER BY created DESC, id DESC LIMIT 3;
id
title
total
8
h
8
7
g
8
6
f
8
The total is 8 even though only 3 rows came back, because window functions are evaluated before LIMIT.
The cheaper alternative when the interface only needs a Next button: ask for one row more than the page size. If 4 rows return for a page of 3, there is a next page; show 3.
sql
SELECT id, title FROM posts ORDER BY created DESC, id DESC LIMIT 4;
id
title
8
h
7
g
6
f
5
e
PostgreSQL can also give a fast estimate from planner statistics (reltuples in pg_class), which suits "about 1.2 million results" labels.
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
SELECT id, title, COUNT(*) OVER () AS total
FROM posts ORDER BY created DESC, id DESC LIMIT 3;
SELECT id, title FROM posts ORDER BY created DESC, id DESC LIMIT 4;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
COUNT(*) OVER () returns the total before LIMIT
It still scans all matching rows
Fetching page size + 1 rows answers 'is there a next page?'
Estimates suit very large result sets
Common mistakes
Running a separate exact COUNT(*) on every page request for huge tables
Expecting LIMIT to reduce the window count
Follow-ups
How would you cache counts?
What does reltuples represent?
Tips
Offer the page size + 1 trick
250.sql-0250Easyfresher
Write a query that returns the second-highest salary, and returns NULL if there is no second value.
Take the highest salary below the maximum: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). Because MAX over zero rows returns NULL, the query returns one row with NULL when everyone earns the same. Ties at the top are handled, since the comparison is on distinct values.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
second_highest
95000
The top salary is 120000; the highest below it is 95000, even though two people earn it.
If every salary were the same, the inner condition would match no rows and MAX would return NULL rather than an empty result:
sql
WITH same(salary) AS (VALUES (50000), (50000))
SELECT MAX(salary) AS second_highest FROM same WHERE salary < (SELECT MAX(salary) FROM same);
second_highest
NULL
The LIMIT 1 OFFSET 1 version over SELECT DISTINCT salary ... ORDER BY salary DESC also works, but it returns no row at all when there is no second value, which some callers handle badly. Wrapping it as a scalar subquery restores the NULL:
sql
SELECT (SELECT DISTINCT salary FROM employees WHERE salary IS NOT NULL
ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;
second_highest
95000
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
WITH same(salary) AS (VALUES (50000), (50000))
SELECT MAX(salary) AS second_highest FROM same WHERE salary < (SELECT MAX(salary) FROM same);
SELECT (SELECT DISTINCT salary FROM employees WHERE salary IS NOT NULL
ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
MAX below MAX gives the second-highest distinct value
MAX over no rows returns NULL
DISTINCT with OFFSET 1 is an alternative
Wrap in a scalar subquery to return NULL instead of no rows
Common mistakes
Using OFFSET 1 without DISTINCT and returning a tie
Returning an empty result when NULL was expected
Follow-ups
How would you generalize to the Nth highest?
How are NULL salaries treated?
Tips
Mention ties and the empty case
251.sql-0251Mediummid
Write a query that returns the employees earning the Nth highest distinct salary, for N = 3.
Rank salaries with DENSE_RANK() OVER (ORDER BY salary DESC) and keep rows where the rank equals N. DENSE_RANK gives tied salaries the same rank without gaps, so rank 3 means the third distinct salary level, and all employees at that level are returned.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
WITH r AS (
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees WHERE salary IS NOT NULL
)
SELECT name, salary FROM r WHERE rnk = 3 ORDER BY name;
name
salary
Tom
70000
The distinct levels are 120000, 95000 and 70000, so the third is 70000 and Tom is returned. With RANK instead, the tie at 95000 would make the next rank 4, and rnk = 3 would match nobody.
A correlated version without window functions counts the distinct salaries above each row:
sql
SELECT name, salary FROM employees e
WHERE salary IS NOT NULL
AND (SELECT COUNT(DISTINCT salary) FROM employees x WHERE x.salary > e.salary) = 2
ORDER BY name;
name
salary
Tom
70000
The window form is clearer and scans once. NULL salaries are excluded so they do not take a rank.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
WITH r AS (
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees WHERE salary IS NOT NULL
)
SELECT name, salary FROM r WHERE rnk = 3 ORDER BY name;
SELECT name, salary FROM employees e
WHERE salary IS NOT NULL
AND (SELECT COUNT(DISTINCT salary) FROM employees x WHERE x.salary > e.salary) = 2
ORDER BY name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
DENSE_RANK gives distinct salary levels without gaps
Filter rank = N in an outer query
RANK would skip numbers after ties
Exclude NULLs before ranking
Common mistakes
Using ROW_NUMBER and picking one employee arbitrarily
Using RANK and missing the level after a tie
Follow-ups
How would you return N per department?
What if N is larger than the number of levels?
Tips
Say why DENSE_RANK and not RANK
252.sql-0252Easyfresher
Write a query that finds email addresses that appear more than once, with how many times each appears.
Group by the email and keep groups with more than one row: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1. Normalize first, for example with lower(trim(email)), if 'Ana@x.com' and 'ana@x.com ' should count as the same address.
Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'Ana@x.com'),(2,'ana@x.com '),(3,'b@x.com'),(4,'b@x.com'),(5,'c@x.com');
SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;
To see the full duplicate rows rather than just the emails, join back or use a window count:
sql
SELECT id, email FROM (
SELECT id, email, COUNT(*) OVER (PARTITION BY lower(trim(email))) AS n FROM users
) WHERE n > 1 ORDER BY lower(trim(email)), id;
The window version keeps every column of the duplicate rows, which helps decide which one to keep.
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'Ana@x.com'),(2,'ana@x.com '),(3,'b@x.com'),(4,'b@x.com'),(5,'c@x.com');
SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1;
SELECT lower(trim(email)) AS email, COUNT(*) AS n FROM users GROUP BY lower(trim(email)) HAVING COUNT(*) > 1 ORDER BY email;
SELECT id, email FROM (
SELECT id, email, COUNT(*) OVER (PARTITION BY lower(trim(email))) AS n FROM users
) WHERE n > 1 ORDER BY lower(trim(email)), id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
GROUP BY plus HAVING COUNT(*) > 1 finds duplicates
Normalize values before grouping when needed
COUNT(*) OVER (PARTITION BY ...) shows full duplicate rows
Decide which copy to keep before deleting
Common mistakes
Using WHERE COUNT(*) > 1
Missing duplicates that differ only in case or spaces
Follow-ups
How would you delete all but one copy?
How would you prevent duplicates in future?
Tips
Ask whether case and spaces matter
253.sql-0253Mediummid
Invoice numbers should be consecutive. Write a query that lists the missing numbers as ranges.
Compare each number with the next one using LEAD: where next - current > 1, the gap runs from current + 1 to next - 1. This finds gap ranges in one pass without generating every possible number.
Full answer
sql
WITH inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12))
SELECT n + 1 AS gap_start, next_n - 1 AS gap_end
FROM (SELECT n, LEAD(n) OVER (ORDER BY n) AS next_n FROM inv)
WHERE next_n - n > 1
ORDER BY gap_start;
gap_start
gap_end
4
5
8
10
Numbers 4 and 5 are missing, and so are 8 to 10. Each row with a jump produces one range.
For short ranges, a recursive CTE can list each missing number individually, which suits small audits:
sql
WITH RECURSIVE inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12)),
all_n(n) AS (SELECT MIN(n) FROM inv UNION ALL SELECT n + 1 FROM all_n WHERE n < (SELECT MAX(n) FROM inv))
SELECT n AS missing FROM all_n WHERE n NOT IN (SELECT n FROM inv) ORDER BY n;
missing
4
5
8
9
10
Sequences generated by the database (autoincrement, PostgreSQL sequences) are not gap-free by design: rolled-back inserts and cached values leave holes. If legal rules require gap-free invoice numbers, assign them in a separate step under a lock, not from a sequence.
sql
WITH inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12))
SELECT n + 1 AS gap_start, next_n - 1 AS gap_end
FROM (SELECT n, LEAD(n) OVER (ORDER BY n) AS next_n FROM inv)
WHERE next_n - n > 1
ORDER BY gap_start;
WITH RECURSIVE inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12)),
all_n(n) AS (SELECT MIN(n) FROM inv UNION ALL SELECT n + 1 FROM all_n WHERE n < (SELECT MAX(n) FROM inv))
SELECT n AS missing FROM all_n WHERE n NOT IN (SELECT n FROM inv) ORDER BY n;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LEAD compares each value with the next
A jump greater than 1 is a gap
Ranges come from current + 1 to next - 1
Database sequences are not gap-free
Common mistakes
Generating every number up to MAX to find gaps on huge tables
Assuming auto-increment ids never skip
Follow-ups
How would you find gaps in dates instead?
How would you allocate gap-free invoice numbers?
Tips
Mention why sequences have gaps
254.sql-0254Hardsenior
Group consecutive sale dates into islands and show each streak's start, end and length.
Subtract a row number from each date: within a run of consecutive days, the date and the row number grow together, so date minus row_number is constant and identifies the island. Group by that key and take MIN, MAX and COUNT. In SQLite compute it with julianday(day) - ROW_NUMBER() OVER (ORDER BY day).
Full answer
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
WITH k AS (
SELECT day, julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp FROM daily_sales
)
SELECT MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS days
FROM k GROUP BY grp ORDER BY start_day;
start_day
end_day
days
2026-03-01
2026-03-03
3
2026-03-05
2026-03-06
2
2026-03-09
2026-03-09
1
The grp value is the same for every day in a streak. 1 to 3 March form one island, 5 to 6 March another, and 9 March stands alone.
Seeing the intermediate column makes the trick clear:
sql
SELECT day, ROW_NUMBER() OVER (ORDER BY day) AS rn,
julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp
FROM daily_sales ORDER BY day;
day
rn
grp
2026-03-01
1
2461099.5
2026-03-02
2
2461099.5
2026-03-03
3
2461099.5
2026-03-05
4
2461100.5
2026-03-06
5
2461100.5
2026-03-09
6
2461102.5
The days jump from 3 to 5 March while the row number moves by one, so the key changes exactly where the streak breaks. The same idea works for any sequence that should increase by a fixed step, such as ticket numbers or minute buckets.
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
WITH k AS (
SELECT day, julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp FROM daily_sales
)
SELECT MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS days
FROM k GROUP BY grp ORDER BY start_day;
SELECT day, ROW_NUMBER() OVER (ORDER BY day) AS rn,
julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp
FROM daily_sales ORDER BY day;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
date minus ROW_NUMBER is constant within a consecutive run
Group by that key to get each island
MIN, MAX and COUNT describe each streak
Works for any fixed-step sequence
Common mistakes
Using LAG alone and struggling to label whole islands
Forgetting to deduplicate dates before numbering
Follow-ups
How would you compute islands per user?
How would you find the longest streak?
Tips
Show the intermediate key
255.sql-0255Hardsenior
Write a query that finds users who logged in on at least three consecutive days.
Apply the islands trick per user: julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) is constant within a streak. Group by user and that key, keep groups with COUNT(*) >= 3, and select the distinct users. A LAG(day, 2) comparison also works for the fixed length 3.
Full answer
sql
CREATE TABLE logins (user_id INTEGER, day TEXT, PRIMARY KEY (user_id, day));
INSERT INTO logins VALUES
(1,'2026-03-01'),(1,'2026-03-02'),(1,'2026-03-03'),(1,'2026-03-05'),
(2,'2026-03-01'),(2,'2026-03-03'),(2,'2026-03-04'),
(3,'2026-03-02'),(3,'2026-03-03'),(3,'2026-03-04'),(3,'2026-03-05');
sql
WITH k AS (
SELECT user_id, day,
julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS grp
FROM logins
)
SELECT user_id, MIN(day) AS streak_start, COUNT(*) AS days
FROM k GROUP BY user_id, grp HAVING COUNT(*) >= 3
ORDER BY user_id;
user_id
streak_start
days
1
2026-03-01
3
3
2026-03-02
4
User 1 has 1 to 3 March (3 days). User 3 has 2 to 5 March (4 days). User 2's longest run is 3 to 4 March, so they are excluded.
For exactly "three in a row", comparing each login with the one two rows earlier is shorter:
sql
SELECT DISTINCT user_id FROM (
SELECT user_id, day, LAG(day, 2) OVER (PARTITION BY user_id ORDER BY day) AS two_before FROM logins
) WHERE julianday(day) - julianday(two_before) = 2
ORDER BY user_id;
user_id
1
3
If the same day can appear twice for a user, deduplicate first (SELECT DISTINCT user_id, day), or the row numbers advance without the date and break the streak key. Here the primary key already prevents that.
sql
CREATE TABLE logins (user_id INTEGER, day TEXT, PRIMARY KEY (user_id, day));
INSERT INTO logins VALUES
(1,'2026-03-01'),(1,'2026-03-02'),(1,'2026-03-03'),(1,'2026-03-05'),
(2,'2026-03-01'),(2,'2026-03-03'),(2,'2026-03-04'),
(3,'2026-03-02'),(3,'2026-03-03'),(3,'2026-03-04'),(3,'2026-03-05');
WITH k AS (
SELECT user_id, day,
julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS grp
FROM logins
)
SELECT user_id, MIN(day) AS streak_start, COUNT(*) AS days
FROM k GROUP BY user_id, grp HAVING COUNT(*) >= 3
ORDER BY user_id;
SELECT DISTINCT user_id FROM (
SELECT user_id, day, LAG(day, 2) OVER (PARTITION BY user_id ORDER BY day) AS two_before FROM logins
) WHERE julianday(day) - julianday(two_before) = 2
ORDER BY user_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Partition the islands trick by user
Keep islands with at least N days
LAG(day, N-1) works for a fixed streak length
Deduplicate days before numbering
Common mistakes
Counting total login days instead of consecutive ones
Forgetting to partition by user
Follow-ups
How would you return each user's longest streak?
How would you handle time zones for 'day'?
Tips
Explain both approaches briefly
256.sql-0256Mediummid
How do you calculate the median salary in SQLite, which has no MEDIAN function, and in PostgreSQL?
In SQLite, number the sorted values and average the middle one or two: rows where row_number is in ((n + 1) / 2, (n + 2) / 2) with integer division. PostgreSQL has percentile_cont(0.5) WITHIN GROUP (ORDER BY salary), which interpolates between the two middle values for even counts.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
There are seven non-NULL salaries, so the median is the fourth:
sql
WITH s AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS n
FROM employees WHERE salary IS NOT NULL
)
SELECT AVG(salary) AS median FROM s WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
median
70000.0
For an even count, the two middle values are averaged. Removing Asha leaves six salaries:
sql
WITH s AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS n
FROM employees WHERE salary IS NOT NULL AND name <> 'Asha'
)
SELECT AVG(salary) AS median FROM s WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
median
66000.0
PostgreSQL:
sql
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) AS median_cont,
percentile_disc(0.5) WITHIN GROUP (ORDER BY salary) AS median_disc
FROM employees;
median_cont
median_disc
70000.0
70000
percentile_disc(0.5) would return an actual value from the data (the lower middle one) instead of an average. NULL salaries are left out in both engines' versions, which matches how other aggregates behave.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
WITH s AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS n
FROM employees WHERE salary IS NOT NULL
)
SELECT AVG(salary) AS median FROM s WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
WITH s AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS rn, COUNT(*) OVER () AS n
FROM employees WHERE salary IS NOT NULL AND name <> 'Asha'
)
SELECT AVG(salary) AS median FROM s WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Median = middle value, or average of the two middle values
SQLite: ROW_NUMBER with the count, then average the middle rows
PostgreSQL: percentile_cont(0.5) WITHIN GROUP (ORDER BY x)
percentile_disc returns an existing value
Common mistakes
Using AVG and calling it a median
Off-by-one errors in the middle-row positions
Follow-ups
How would you compute the median per department?
When is the median more useful than the mean?
Tips
Check both odd and even counts
257.sql-0257Easyfresher
Write a query that lists pairs of employees in the same department who earn exactly the same salary, with each pair shown once.
Self join employees on equal dept_id and equal salary, and require a.id < b.id. The inequality removes self-pairs (Ravi with Ravi) and mirror pairs (Mei, Ravi as well as Ravi, Mei), so each pair appears exactly once.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
sql
SELECT a.name AS first, b.name AS second, a.dept_id, a.salary
FROM employees a JOIN employees b
ON b.dept_id = a.dept_id AND b.salary = a.salary AND a.id < b.id
ORDER BY a.dept_id, first;
first
second
dept_id
salary
Ravi
Mei
1
95000
Ravi and Mei both earn 95000 in Engineering. Using a.id <> b.id instead would return the pair twice, once in each order:
sql
SELECT a.name AS first, b.name AS second
FROM employees a JOIN employees b
ON b.dept_id = a.dept_id AND b.salary = a.salary AND a.id <> b.id
ORDER BY first;
first
second
Mei
Ravi
Ravi
Mei
NULLs drop out naturally: Lena has no department and no salary, and NULL = NULL is not true, so she never pairs with anyone. If NULL departments should match each other, use IS in SQLite or IS NOT DISTINCT FROM in PostgreSQL.
The same a.id < b.id pattern produces unique pairs for any "find matching pairs" puzzle, such as possible duplicate customers or overlapping bookings.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT a.name AS first, b.name AS second, a.dept_id, a.salary
FROM employees a JOIN employees b
ON b.dept_id = a.dept_id AND b.salary = a.salary AND a.id < b.id
ORDER BY a.dept_id, first;
SELECT a.name AS first, b.name AS second
FROM employees a JOIN employees b
ON b.dept_id = a.dept_id AND b.salary = a.salary AND a.id <> b.id
ORDER BY first;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Self join on the matching columns
a.id < b.id removes self and mirror pairs
<> would return each pair twice
NULLs do not match with =
Common mistakes
Using <> and doubling the result
Forgetting the department condition and pairing across departments
Follow-ups
How would you find groups of three or more with the same salary?
How would you find overlapping date ranges?
Tips
Explain why < and not <>
258.sql-0258Hardsenior
For each signup month, what share of users were active again in the following calendar month?
Assign each user a cohort month from their signup, then check for any activity in the month after it with EXISTS. Group by cohort and divide retained users by cohort size, using 100.0 to avoid integer division. Define 'active' and the month boundaries clearly before writing the query.
Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, signup TEXT NOT NULL);
CREATE TABLE activity (user_id INTEGER, day TEXT);
INSERT INTO users VALUES (1,'2026-01-10'),(2,'2026-01-20'),(3,'2026-02-03'),(4,'2026-02-15'),(5,'2026-02-20');
INSERT INTO activity VALUES
(1,'2026-01-10'),(1,'2026-02-05'),(1,'2026-03-02'),
(2,'2026-01-20'),
(3,'2026-02-03'),(3,'2026-03-10'),
(4,'2026-02-15'),(4,'2026-03-01'),(4,'2026-04-02'),
(5,'2026-02-20');
sql
WITH c AS (
SELECT id, substr(signup, 1, 7) AS cohort,
substr(date(substr(signup, 1, 7) || '-01', '+1 month'), 1, 7) AS next_month
FROM users
)
SELECT cohort, COUNT(*) AS users,
SUM(EXISTS (SELECT 1 FROM activity a WHERE a.user_id = c.id AND substr(a.day, 1, 7) = c.next_month)) AS retained,
ROUND(100.0 * SUM(EXISTS (SELECT 1 FROM activity a WHERE a.user_id = c.id AND substr(a.day, 1, 7) = c.next_month)) / COUNT(*), 1) AS pct
FROM c GROUP BY cohort ORDER BY cohort;
cohort
users
retained
pct
2026-01
2
1
50.0
2026-02
3
2
66.7
January's cohort has users 1 and 2; only user 1 was active in February, so retention is 50 percent. February's cohort has users 3, 4 and 5; users 3 and 4 were active in March, giving 66.7 percent.
The next month is computed with date(month || '-01', '+1 month'), which starts from the first of the month and so avoids month-end surprises.
Design questions an interviewer expects you to raise: does signup-day activity count, should the window be "next calendar month" or "days 30 to 60 after signup", and should the latest cohort be shown when its following month has not finished yet?
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, signup TEXT NOT NULL);
CREATE TABLE activity (user_id INTEGER, day TEXT);
INSERT INTO users VALUES (1,'2026-01-10'),(2,'2026-01-20'),(3,'2026-02-03'),(4,'2026-02-15'),(5,'2026-02-20');
INSERT INTO activity VALUES
(1,'2026-01-10'),(1,'2026-02-05'),(1,'2026-03-02'),
(2,'2026-01-20'),
(3,'2026-02-03'),(3,'2026-03-10'),
(4,'2026-02-15'),(4,'2026-03-01'),(4,'2026-04-02'),
(5,'2026-02-20');
WITH c AS (
SELECT id, substr(signup, 1, 7) AS cohort,
substr(date(substr(signup, 1, 7) || '-01', '+1 month'), 1, 7) AS next_month
FROM users
)
SELECT cohort, COUNT(*) AS users,
SUM(EXISTS (SELECT 1 FROM activity a WHERE a.user_id = c.id AND substr(a.day, 1, 7) = c.next_month)) AS retained,
ROUND(100.0 * SUM(EXISTS (SELECT 1 FROM activity a WHERE a.user_id = c.id AND substr(a.day, 1, 7) = c.next_month)) / COUNT(*), 1) AS pct
FROM c GROUP BY cohort ORDER BY cohort;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Cohort = signup month
EXISTS checks for activity in the following month
Retained / cohort size, with non-integer division
State the definition of 'active' and the window
Common mistakes
Counting activity rows instead of distinct users
Including incomplete recent cohorts without a note
Follow-ups
How would you build a full cohort matrix for months 1 to 6?
How would you define rolling 30-day retention?
Tips
Clarify definitions before writing SQL
259.sql-0259Hardsenior
Split each user's clicks into sessions, where a gap of more than 30 minutes starts a new session.
Use LAG to get the previous click per user, flag a new session when there is no previous click or the gap exceeds 30 minutes, then take a running SUM of the flags per user to number the sessions. This 'flag then cumulative sum' pattern turns event streams into groups.
WITH g AS (
SELECT user_id, ts,
CASE WHEN LAG(ts) OVER w IS NULL
OR (julianday(ts) - julianday(LAG(ts) OVER w)) * 1440 > 30 THEN 1 ELSE 0 END AS new_session
FROM clicks
WINDOW w AS (PARTITION BY user_id ORDER BY ts)
)
SELECT user_id, ts, SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no
FROM g ORDER BY user_id, ts;
user_id
ts
session_no
1
2026-03-01 09:00
1
1
2026-03-01 09:10
1
1
2026-03-01 09:50
2
1
2026-03-01 10:05
2
2
2026-03-01 09:00
1
2
2026-03-01 09:29
1
2
2026-03-01 11:00
2
User 1's clicks at 09:00 and 09:10 share a session; 09:50 is 40 minutes later, so it starts session 2, and 10:05 joins it. User 2's 09:29 click is 29 minutes after 09:00 and stays in session 1; 11:00 starts session 2.
Summarizing sessions is then a GROUP BY:
sql
WITH g AS (
SELECT user_id, ts,
CASE WHEN LAG(ts) OVER w IS NULL
OR (julianday(ts) - julianday(LAG(ts) OVER w)) * 1440 > 30 THEN 1 ELSE 0 END AS new_session
FROM clicks WINDOW w AS (PARTITION BY user_id ORDER BY ts)
), s AS (
SELECT user_id, ts, SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no FROM g
)
SELECT user_id, session_no, MIN(ts) AS started, MAX(ts) AS ended, COUNT(*) AS clicks
FROM s GROUP BY user_id, session_no ORDER BY user_id, session_no;
user_id
session_no
started
ended
clicks
1
1
2026-03-01 09:00
2026-03-01 09:10
2
1
2
2026-03-01 09:50
2026-03-01 10:05
2
2
1
2026-03-01 09:00
2026-03-01 09:29
2
2
2
2026-03-01 11:00
2026-03-01 11:00
1
julianday differences are in days, so multiplying by 1440 gives minutes. Timestamps must be in one zone and format for the subtraction to be meaningful.
sql
CREATE TABLE clicks (user_id INTEGER, ts TEXT);
INSERT INTO clicks VALUES
(1,'2026-03-01 09:00'),(1,'2026-03-01 09:10'),(1,'2026-03-01 09:50'),(1,'2026-03-01 10:05'),
(2,'2026-03-01 09:00'),(2,'2026-03-01 09:29'),(2,'2026-03-01 11:00');
WITH g AS (
SELECT user_id, ts,
CASE WHEN LAG(ts) OVER w IS NULL
OR (julianday(ts) - julianday(LAG(ts) OVER w)) * 1440 > 30 THEN 1 ELSE 0 END AS new_session
FROM clicks
WINDOW w AS (PARTITION BY user_id ORDER BY ts)
)
SELECT user_id, ts, SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no
FROM g ORDER BY user_id, ts;
WITH g AS (
SELECT user_id, ts,
CASE WHEN LAG(ts) OVER w IS NULL
OR (julianday(ts) - julianday(LAG(ts) OVER w)) * 1440 > 30 THEN 1 ELSE 0 END AS new_session
FROM clicks WINDOW w AS (PARTITION BY user_id ORDER BY ts)
), s AS (
SELECT user_id, ts, SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no FROM g
)
SELECT user_id, session_no, MIN(ts) AS started, MAX(ts) AS ended, COUNT(*) AS clicks
FROM s GROUP BY user_id, session_no ORDER BY user_id, session_no;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
LAG gives the previous event per user
Flag 1 when the gap exceeds the threshold
Running SUM of flags numbers the sessions
Group by user and session for summaries
Common mistakes
Using a fixed time bucket instead of gaps
Forgetting to partition by user
Follow-ups
How would you compute average session length?
How would you handle clicks exactly 30 minutes apart?
Tips
Name the flag-and-cumulative-sum pattern
260.sql-0260Mediummid
Which products make up the first 80 percent of revenue? Write a cumulative-share (Pareto) query.
Aggregate revenue per product, then compute a running total ordered by revenue descending and divide by the grand total from SUM(...) OVER (). Keep products whose cumulative share before adding them was under 80 percent, so the product that crosses the line is included.
Full answer
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
WITH r AS (
SELECT product, SUM(qty * unit_price) AS revenue FROM order_items GROUP BY product
), c AS (
SELECT product, revenue,
100.0 * revenue / SUM(revenue) OVER () AS pct,
100.0 * SUM(revenue) OVER (ORDER BY revenue DESC, product) / SUM(revenue) OVER () AS cum_pct
FROM r
)
SELECT product, revenue, ROUND(cum_pct, 1) AS cum_pct
FROM c WHERE cum_pct - pct < 80
ORDER BY revenue DESC, product;
product
revenue
cum_pct
Bag
60
49.2
Lamp
25
69.7
Notebook
20
86.1
Total revenue is 123. Bag (60) and Lamp (25) reach 69.7 percent, so Notebook, which takes the running share to 86.1 percent, crosses the line and is included. Pen is left out. Comparing the share before the current row (cum_pct - pct) is what includes the product that crosses the threshold.
Revenue here counts every order line, including the cancelled order. A real report would join orders and exclude cancelled ones; the definition belongs in the answer.
The window ORDER BY uses product as a tie-breaker so equal revenues produce a stable cumulative order.
sql
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
order_date TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders(id),
product TEXT NOT NULL,
qty INTEGER NOT NULL,
unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
(101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
(103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
(105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
(101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
(104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
WITH r AS (
SELECT product, SUM(qty * unit_price) AS revenue FROM order_items GROUP BY product
), c AS (
SELECT product, revenue,
100.0 * revenue / SUM(revenue) OVER () AS pct,
100.0 * SUM(revenue) OVER (ORDER BY revenue DESC, product) / SUM(revenue) OVER () AS cum_pct
FROM r
)
SELECT product, revenue, ROUND(cum_pct, 1) AS cum_pct
FROM c WHERE cum_pct - pct < 80
ORDER BY revenue DESC, product;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Aggregate first, then apply windows
Running total over revenue descending
Divide by SUM(...) OVER () for shares
Compare the share before the current row to include the crossing item
Common mistakes
Cutting off at cum_pct <= 80 and excluding the product that crosses