← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 21 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 21 of 26

Questions 401–420 of 501 · 0 of 20 on this page marked learned

401.sql-0401Easyfresher

Design tables for a library that lends books, tracking copies, loans, due dates and fines.

Separate the title (books) from physical copies (book_copies), and record loans per copy with borrowed_at, due_at and returned_at. A partial unique index on loans(copy_id) WHERE returned_at IS NULL ensures a copy is lent to only one member at a time. Fines are derived from overdue days or recorded as charges when the book is returned.

Full answer
text
books(id, isbn UNIQUE, title, author)
book_copies(id, book_id FK, barcode UNIQUE, status)
members(id, name, joined_at)
loans(id, copy_id FK, member_id FK, borrowed_at, due_at, returned_at)
CREATE UNIQUE INDEX one_open_loan_per_copy ON loans(copy_id) WHERE returned_at IS NULL;
fines(id, loan_id FK, amount_minor, paid_at)

Common queries:

  • Available copies of a title: copies with no open loan.
  • Overdue loans: returned_at IS NULL AND due_at < :today.
  • A member's history: loans by member_id, newest first.

The partial unique index is the key rule; it works in SQLite and PostgreSQL. Storing fines as rows when a book comes back fixes the amount according to the rules in force at that time, rather than recomputing later.

Key points

  • Separate titles from copies
  • Loans per copy with open and returned state
  • Partial unique index for one open loan
  • Fines recorded as rows

Common mistakes

  • A single available flag that drifts from loan data
  • Treating a title as one lendable item

Follow-ups

  • How would you add reservations for titles?
  • How would you limit members to five open loans?

Tips

  • Show the partial unique index
402.sql-0402Mediummid

Design storage for survey questions and responses where surveys can have different question types.

Store surveys, questions (survey, position, type, settings) and options for choice questions. Responses get a header row per submission and answer rows per question, with typed columns (option_id, text_value, number_value) or a JSON value. Keep questions versioned or immutable once responses exist, so old answers stay interpretable.

Full answer
text
surveys(id, title, published_at)
questions(id, survey_id, position, kind CHECK IN ('single','multi','text','scale'), prompt, required)
question_options(id, question_id, position, label)
responses(id, survey_id, respondent_id, submitted_at)
answers(response_id, question_id, option_id, text_value, number_value)
  • Multiple-choice answers are one row per selected option.
  • A CHECK can tie value columns to question types loosely; strict checks need a trigger.
  • Reports are plain aggregates: COUNT(*) GROUP BY option_id for a question.
  • Editing a published question's meaning invalidates earlier answers, so publish a new question instead and hide the old one.

A single JSON document per response is simpler to write but makes cross-response reporting slower and harder to validate; the row-per-answer shape keeps reporting in SQL.

Key points

  • Questions with type and position
  • Options table for choice questions
  • Answer rows per question with typed values
  • Freeze questions after responses exist
  • Row-per-answer keeps reporting simple

Common mistakes

  • Storing all answers as one comma-separated string
  • Editing published questions in place

Follow-ups

  • How would you support conditional questions?
  • How would you export responses as one row per respondent?

Tips

  • Explain why questions are frozen
403.sql-0403Easyfresher

Design the database side of a shopping cart that survives logins and expires abandoned carts.

Store carts with an owner (customer_id or an anonymous token), status and updated_at, and cart_items with product, quantity and the price shown when added. On login, merge the anonymous cart into the customer's cart. A scheduled job marks carts idle for N days as abandoned and deletes very old ones.

Full answer
text
carts(id, customer_id NULL, anon_token UNIQUE NULL, status, created_at, updated_at,
      CHECK (customer_id IS NOT NULL OR anon_token IS NOT NULL))
cart_items(cart_id FK, product_id FK, qty CHECK (qty > 0), price_at_add_cents,
           PRIMARY KEY (cart_id, product_id))
  • Adding the same product twice upserts the item and increases qty.
  • price_at_add_cents lets the UI warn when the price changed; checkout uses the current price.
  • Merging on login: upsert each anonymous item into the customer cart, summing quantities, then delete the anonymous cart, all in one transaction.
  • A partial unique index allows only one active cart per customer.
  • Abandoned carts feed reminder emails; then retention removes them.

Stock is not reserved at add-to-cart time in most shops; reservation happens at checkout, which keeps carts cheap.

Key points

  • Carts owned by a customer or anonymous token
  • Upsert items by product
  • Merge carts on login in one transaction
  • One active cart per customer
  • Expire abandoned carts

Common mistakes

  • Storing carts only in browser storage
  • Reserving stock when items are added

Follow-ups

  • How would you handle a product that goes out of stock in a cart?
  • How would you compute cart abandonment rate?

Tips

  • Describe the merge step
404.sql-0404Mediummid

Design a school timetable database that prevents a teacher or room from being double-booked in the same period.

Model teachers, rooms, class groups, subjects and periods (day plus slot number), and a lessons table assigning a group, subject, teacher and room to a period. Unique constraints on (period_id, teacher_id), (period_id, room_id) and (period_id, group_id) make each double booking impossible in the database itself.

Full answer
text
periods(id, weekday, slot, starts_at, ends_at, UNIQUE (weekday, slot))
teachers(id, name)   rooms(id, name, capacity)   class_groups(id, name, size)
subjects(id, name)
lessons(id, term_id, period_id FK, group_id FK, subject_id FK, teacher_id FK, room_id FK,
        UNIQUE (term_id, period_id, teacher_id),
        UNIQUE (term_id, period_id, room_id),
        UNIQUE (term_id, period_id, group_id))

Three unique keys capture three separate rules: a teacher teaches one lesson per period, a room hosts one lesson, a group attends one lesson. Including term_id lets each term have its own timetable.

Other rules, such as room capacity at least group size or a teacher's maximum periods per day, need a trigger or validation in the scheduling application. Generating a good timetable is an optimisation problem solved outside SQL; the database's job is to reject invalid results.

Key points

  • Periods as day plus slot
  • One unique key per double-booking rule
  • Term scoping
  • Triggers or app checks for capacity rules
  • Generation happens outside SQL

Common mistakes

  • Checking clashes only in the UI
  • Storing timetables as free text per teacher

Follow-ups

  • How would you handle double periods?
  • How would substitute teachers be recorded?

Tips

  • Map each rule to a constraint
405.sql-0405Hardsenior

Design storage for ride trips: requests, driver assignment, status changes and fares.

Keep trips with rider, driver (nullable until assigned), status, pickup and drop-off points and timestamps, plus a trip_events table logging each status change. Assign a driver with a conditional UPDATE that only succeeds while the trip is still 'requested' and the driver is available, so two drivers cannot accept the same trip. Store the fare breakdown at completion.

Full answer
text
trips(id, rider_id, driver_id NULL, status CHECK IN ('requested','accepted','arrived',
      'in_progress','completed','cancelled'), pickup, dropoff, requested_at, completed_at)
trip_events(id, trip_id, from_status, to_status, actor, at)
driver_status(driver_id PK, state CHECK IN ('offline','available','on_trip'), updated_at)
fares(trip_id PK, base_minor, distance_minor, time_minor, surge_multiplier, total_minor)

Accepting a trip, in one transaction:

  1. UPDATE trips SET driver_id = :d, status = 'accepted' WHERE id = :t AND status = 'requested';
  2. UPDATE driver_status SET state = 'on_trip' WHERE driver_id = :d AND state = 'available';
  3. If either affects zero rows, roll back; another driver won or this driver is busy.

Allowed transitions form a state machine; enforce them in one place (a function or trigger) and log each to trip_events. Live locations are high-volume and usually live in a separate store, with only key points kept on the trip.

Key points

  • Trips as a state machine
  • Conditional updates for assignment
  • Event log of status changes
  • Fare breakdown stored at completion
  • Live location kept separately

Common mistakes

  • Letting any status change to any other
  • Assigning drivers with read-then-write logic

Follow-ups

  • How would you match the nearest available driver?
  • How would you handle a driver who cancels after accepting?

Tips

  • Show the two conditional updates
406.sql-0406Mediummid

Predict the count: SELECT COUNT(*) FROM (SELECT 1 UNION SELECT 1 UNION ALL SELECT 1);

The result is 2. Compound operators are applied left to right, so SELECT 1 UNION SELECT 1 first collapses to one row, and UNION ALL then appends another 1 without removing duplicates.

Full answer
sql
SELECT COUNT(*) AS n FROM (SELECT 1 UNION SELECT 1 UNION ALL SELECT 1);
n
2

Read the chain as (SELECT 1 UNION SELECT 1) UNION ALL SELECT 1. The first UNION removes the duplicate, leaving one row, and UNION ALL adds the third row as it is. Reordering the same three branches as SELECT 1 UNION ALL SELECT 1 UNION SELECT 1 gives 1, because the final UNION deduplicates everything before it. In PostgreSQL INTERSECT binds tighter than UNION and EXCEPT, while SQLite treats all compound operators with equal precedence, left to right, so parentheses are the safe way to make intent clear (PostgreSQL behaviour stated, not run here).

sql
SELECT COUNT(*) AS n FROM (SELECT 1 UNION SELECT 1 UNION ALL SELECT 1);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Compound operators apply left to right in SQLite
  • A later UNION deduplicates everything before it
  • PostgreSQL gives INTERSECT higher precedence

Common mistakes

  • Assuming UNION ALL anywhere keeps all duplicates

Follow-ups

  • What does SELECT 1 UNION ALL SELECT 1 UNION SELECT 1 return?
  • How would you write the query to make the grouping explicit?

Tips

  • Bracket the first pair mentally
407.sql-0407Hardsenior

What does SQLite return for SELECT 'a' || 1 + 2, and does PostgreSQL agree?

SQLite returns 2, because || binds tighter than +, so it computes ('a' || 1) + 2, and 'a1' converts to 0 in arithmetic. PostgreSQL gives + higher precedence than ||, so it computes 'a' || (1 + 2) and returns 'a3'. Use parentheses whenever concatenation and arithmetic mix.

Full answer
sql
SELECT 'a' || 1 + 2 AS result;
result
2

In SQLite, || has the highest precedence of the binary operators. 'a' || 1 is the text 'a1'; adding 2 converts 'a1' to a number, and since it does not start with digits that number is 0, so the sum is 2. PostgreSQL places || among the 'other operators', below +, so the same text means something else there:

sql
SELECT 'a' || 1 + 2 AS result;
result
a3

The same expression gives two different answers on two engines without any error, which makes this a portability trap worth remembering. Parentheses settle it.

sql
SELECT 'a' || 1 + 2 AS result;

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: || binds tighter than +
  • PostgreSQL: + binds tighter than ||
  • Non-numeric text converts to 0 in SQLite arithmetic
  • Always parenthesise mixed expressions

Common mistakes

  • Assuming operator precedence is identical across engines

Follow-ups

  • What does 'a' || (1 + 2) return in SQLite?
  • Which other operators differ in precedence between engines?

Tips

  • Run both engines in your head
408.sql-0408Easyfresher

Predict the output of comparing 'Z' < 'a' and 'apple' < 'Apple' in SQLite.

'Z' < 'a' is 1 and 'apple' < 'Apple' is 0. SQLite's default BINARY collation compares bytes, and every uppercase ASCII letter has a lower code than every lowercase one, so uppercase sorts first. Use COLLATE NOCASE or lower() for case-insensitive comparisons.

Full answer
sql
SELECT 'abc' < 'abd' AS a, 'Z' < 'a' AS b, 'apple' < 'Apple' AS c, 'apple' < 'Apple' COLLATE NOCASE AS d;
abcd
1100

The first comparison differs at the third character, where 'c' comes before 'd', so it is 1. 'Z' is byte 90 and 'a' is byte 97, so 'Z' < 'a' is 1. 'apple' starts with byte 97 and 'Apple' with 65, so 'apple' is larger and the third result is 0. With NOCASE the two words are equal, so 'less than' is 0 as well. PostgreSQL's result depends on the database collation; with a linguistic locale such as en_US, lowercase and uppercase interleave and 'Z' < 'a' is false (PostgreSQL behaviour stated, not run here).

sql
SELECT 'abc' < 'abd' AS a, 'Z' < 'a' AS b, 'apple' < 'Apple' AS c, 'apple' < 'Apple' COLLATE NOCASE AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • BINARY collation compares bytes
  • Uppercase ASCII sorts before lowercase
  • NOCASE folds ASCII case
  • PostgreSQL depends on the collation

Common mistakes

  • Expecting dictionary order from byte comparison

Follow-ups

  • How does NOCASE handle non-ASCII letters?
  • How would you sort names case-insensitively?

Tips

  • Think in character codes
409.sql-0409Mediummid

What do length('héllo') and length(CAST('héllo' AS BLOB)) return in SQLite?

length('héllo') is 5 because SQLite counts characters for text, while the blob length is 6 because 'é' takes two bytes in UTF-8. Character counts and byte counts differ for any non-ASCII text, which matters for column limits and storage estimates.

Full answer
sql
SELECT length('héllo') AS chars, length(CAST('héllo' AS BLOB)) AS bytes, octet_length('héllo') AS octets;
charsbytesoctets
566

For text values length() returns the number of characters, and for blobs it returns bytes. The UTF-8 encoding of 'é' (U+00E9) is two bytes, so the five-character word occupies six bytes. octet_length(), available in SQLite since 3.43, returns the byte length of text directly, matching the blob figure. PostgreSQL behaves the same way: length() and char_length() count characters and octet_length() counts bytes. A VARCHAR(5) limit in PostgreSQL counts characters, so 'héllo' fits (PostgreSQL behaviour stated, not run here).

sql
SELECT length('héllo') AS chars, length(CAST('héllo' AS BLOB)) AS bytes, octet_length('héllo') AS octets;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • length counts characters for text
  • Blob and octet lengths count bytes
  • UTF-8 uses several bytes for non-ASCII characters

Common mistakes

  • Using character counts to estimate storage

Follow-ups

  • How many bytes does an emoji take in UTF-8?
  • Does SQLite enforce VARCHAR(n) limits?

Tips

  • Separate characters from bytes
410.sql-0410Easyfresher

Predict typeof() for 1, 1.0, '1', NULL and x'01' in SQLite.

The results are integer, real, text, null and blob. SQLite has five storage classes, and typeof() reports the class of each value, not of a column.

Full answer
sql
SELECT typeof(1) AS a, typeof(1.0) AS b, typeof('1') AS c, typeof(NULL) AS d, typeof(x'01') AS e;
abcde
integerrealtextnullblob

Literals keep their own storage class: a number without a decimal point is an integer, with a decimal point it is a real, quoted values are text, x'..' is a blob literal and NULL is null. In a table, the column's affinity may convert values on insert; for example inserting '1' into an INTEGER column stores the integer 1. Checking typeof(col) across rows is a quick way to find mixed types in a column that was loaded from CSV. PostgreSQL has pg_typeof(), which reports declared types instead.

sql
SELECT typeof(1) AS a, typeof(1.0) AS b, typeof('1') AS c, typeof(NULL) AS d, typeof(x'01') AS e;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Five storage classes: integer, real, text, blob, null
  • typeof reports the value's class
  • Column affinity can convert on insert

Common mistakes

  • Assuming a column's declared type guarantees each value's type in SQLite

Follow-ups

  • What does typeof return after inserting '1' into an INTEGER column?
  • How would you find mixed types in a column?

Tips

  • Name the five storage classes
411.sql-0411Mediummid

What do CAST(3.9 AS INTEGER), CAST(-3.9 AS INTEGER), CAST('12abc' AS INTEGER) and CAST('abc' AS INTEGER) return in SQLite?

They return 3, -3, 12 and 0. CAST to INTEGER truncates reals toward zero, and for text SQLite reads the longest numeric prefix, returning 0 when there is none, instead of raising an error.

Full answer
sql
SELECT CAST(3.9 AS INTEGER) AS a, CAST(-3.9 AS INTEGER) AS b, CAST('12abc' AS INTEGER) AS c, CAST('abc' AS INTEGER) AS d;
abcd
3-3120

Truncation drops the fractional part, which moves negative numbers up towards zero, so -3.9 becomes -3 rather than -4. Text conversion is lenient: '12abc' starts with the digits 12, so the cast yields 12, and 'abc' has no numeric prefix, so it yields 0. That leniency hides bad data, because a typo becomes a plausible number. PostgreSQL rejects both strings with an invalid input error and rounds 3.9 to 4 when casting to integer (PostgreSQL behaviour stated, not run here). Validate input with a pattern check or typeof() before relying on SQLite casts.

sql
SELECT CAST(3.9 AS INTEGER) AS a, CAST(-3.9 AS INTEGER) AS b, CAST('12abc' AS INTEGER) AS c, CAST('abc' AS INTEGER) AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CAST to INTEGER truncates toward zero in SQLite
  • Text casts use the numeric prefix
  • No numeric prefix gives 0, not an error
  • PostgreSQL raises errors and rounds

Common mistakes

  • Trusting CAST to reject malformed numbers

Follow-ups

  • How would you find rows whose text is not a valid integer?
  • How would you floor negative numbers?

Tips

  • Watch negatives and prefixes
412.sql-0412Mediummid

Predict the last day of the month for February 2028 and March 2026 using SQLite date modifiers.

date(d, 'start of month', '+1 month', '-1 day') returns the last day of d's month: 2028-02-29 for February 2028, a leap year, and 2026-03-31 for March 2026. Moving to the first of the month before adding a month avoids SQLite's overflow of invalid dates.

Full answer
sql
SELECT date('2028-02-10', 'start of month', '+1 month', '-1 day') AS feb_2028, date('2026-03-15', 'start of month', '+1 month', '-1 day') AS mar_2026;
feb_2028mar_2026
2028-02-292026-03-31

The modifiers apply left to right. 'start of month' moves to the 1st, '+1 month' moves to the 1st of the next month, which always exists, and '-1 day' steps back to the last day, so leap years are handled without any calendar logic. Adding a month directly to a 31st can overflow into the following month in SQLite, which is why the start-of-month step comes first. In PostgreSQL the same idea is (date_trunc('month', d) + interval '1 month - 1 day')::date (not run here).

sql
SELECT date('2028-02-10', 'start of month', '+1 month', '-1 day') AS feb_2028, date('2026-03-15', 'start of month', '+1 month', '-1 day') AS mar_2026;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Modifiers apply left to right
  • start of month, +1 month, -1 day gives month end
  • Leap years are handled automatically
  • Avoid adding months to day 31 directly

Common mistakes

  • Hard-coding month lengths

Follow-ups

  • How would you get the last day of the previous month?
  • How would you list all month ends in a year?

Tips

  • Go to the 1st before adding months
413.sql-0413Easyfresher

What do COALESCE(NULL, '', 'x'), IFNULL(NULL, 0) and NULLIF(5, 5) return?

COALESCE returns '' because the empty string is the first non-NULL argument, IFNULL returns 0, and NULLIF(5, 5) returns NULL because its two arguments are equal.

Full answer
sql
SELECT COALESCE(NULL, '', 'x') AS a, IFNULL(NULL, 0) AS b, NULLIF(5, 5) AS c, NULLIF(5, 6) AS d;
abcd
''0NULL5

COALESCE stops at the first argument that is not NULL, and an empty string qualifies even though it looks blank, so 'x' is never reached. IFNULL is SQLite's two-argument form of COALESCE. NULLIF(a, b) returns NULL when a equals b and a otherwise, which is why NULLIF(5, 6) is 5. Combining them, COALESCE(NULLIF(trim(name), ''), 'unknown') treats blank and NULL alike. PostgreSQL has COALESCE and NULLIF but not IFNULL (PostgreSQL behaviour stated, not run here).

sql
SELECT COALESCE(NULL, '', 'x') AS a, IFNULL(NULL, 0) AS b, NULLIF(5, 5) AS c, NULLIF(5, 6) AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COALESCE returns the first non-NULL
  • Empty strings are not NULL
  • NULLIF turns equal values into NULL
  • IFNULL is SQLite and MySQL only

Common mistakes

  • Expecting COALESCE to skip empty strings

Follow-ups

  • How would you treat blank and NULL the same?
  • Where is NULLIF useful besides division?

Tips

  • Check each argument in order
414.sql-0414Hardsenior

Predict the running totals: SELECT x, SUM(x) OVER (ORDER BY x) over the values 1, 2, 2, 3.

The totals are 1, 5, 5 and 8. With ORDER BY and no frame clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all peers of the current row, so both 2s see the sum through both 2s.

Full answer
sql
WITH t(x) AS (VALUES (1), (2), (2), (3))
SELECT x, SUM(x) OVER (ORDER BY x) AS running, SUM(x) OVER (ORDER BY x ROWS UNBOUNDED PRECEDING) AS by_rows FROM t;
xrunningby_rows
111
253
255
388

The running column uses the default RANGE frame: rows with equal ORDER BY values are peers and enter the frame together, so the first 2 already counts the second one and shows 5. The by_rows column uses a ROWS frame, which stops at the physical current row and gives 1, 3, 5, 8. The order among the two peer rows is not defined, so which one shows 3 under ROWS can vary; add a unique tiebreaker to the ORDER BY when the running total must be stable. PostgreSQL follows the same standard default (PostgreSQL behaviour stated, not run here).

sql
WITH t(x) AS (VALUES (1), (2), (2), (3))
SELECT x, SUM(x) OVER (ORDER BY x) AS running, SUM(x) OVER (ORDER BY x ROWS UNBOUNDED PRECEDING) AS by_rows FROM t;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Default frame with ORDER BY is RANGE ... CURRENT ROW
  • RANGE includes peers with equal values
  • ROWS counts physical rows
  • Add a tiebreaker for stable running totals

Common mistakes

  • Expecting row-by-row totals with duplicate sort keys

Follow-ups

  • When is RANGE the desired behaviour?
  • How would you write a 3-row moving average?

Tips

  • Look for ties in the ORDER BY
415.sql-0415Mediummid

In SQLite, what are MIN and MAX over a column holding 1, 'a' and 2.5?

MIN is 1 and MAX is 'a'. SQLite orders values across storage classes as NULL, then numbers (integers and reals together), then text, then blobs, so any text value is greater than any number.

Full answer
sql
CREATE TABLE mixed (v);
INSERT INTO mixed VALUES (1), ('a'), (2.5);
SELECT MIN(v) AS lo, MAX(v) AS hi, typeof(MAX(v)) AS hi_type FROM mixed;
lohihi_type
1atext

The column has no declared type, so each value keeps its own class. Among numbers, 1 is smaller than 2.5, and numbers rank below text, so MIN is 1 and MAX is the text 'a', reported with type text. The same cross-class ordering drives ORDER BY, which is why a numeric column polluted with a stray string sorts that string last. PostgreSQL cannot store mixed types in one column, so this situation does not arise there.

sql
CREATE TABLE mixed (v);
INSERT INTO mixed VALUES (1), ('a'), (2.5);
SELECT MIN(v) AS lo, MAX(v) AS hi, typeof(MAX(v)) AS hi_type FROM mixed;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Cross-class order: NULL < numbers < text < blob
  • Integers and reals compare numerically
  • Mixed columns sort surprisingly

Common mistakes

  • Assuming MAX on a numeric-looking column returns a number

Follow-ups

  • How would you find non-numeric values in such a column?
  • How would STRICT tables prevent this?

Tips

  • Recall the storage class order
416.sql-0416Mediummid

Predict CASE WHEN NULL THEN 'yes' ELSE 'no' END and CASE NULL WHEN NULL THEN 'match' ELSE 'no match' END.

Both take the ELSE branch, returning 'no' and 'no match'. A searched CASE needs its condition to be true, and NULL is not true; a simple CASE compares with =, and NULL = NULL is NULL, so it never matches.

Full answer
sql
SELECT CASE WHEN NULL THEN 'yes' ELSE 'no' END AS searched, CASE NULL WHEN NULL THEN 'match' ELSE 'no match' END AS simple, CASE WHEN NULL IS NULL THEN 'match' END AS with_is;
searchedsimplewith_is
nono matchmatch

In the searched form, each WHEN condition is evaluated and only a true result selects the branch; unknown behaves like false. The simple form CASE x WHEN y is shorthand for CASE WHEN x = y, so a NULL on either side gives unknown. To branch on NULL, use the searched form with IS NULL, as the third column does, returning 'match'. This also explains why CASE status WHEN NULL THEN ... silently never fires in real queries.

sql
SELECT CASE WHEN NULL THEN 'yes' ELSE 'no' END AS searched, CASE NULL WHEN NULL THEN 'match' ELSE 'no match' END AS simple, CASE WHEN NULL IS NULL THEN 'match' END AS with_is;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CASE branches need true, not unknown
  • Simple CASE uses = comparison
  • Use WHEN x IS NULL to test NULL

Common mistakes

  • Writing CASE col WHEN NULL THEN ...

Follow-ups

  • How would you label NULL statuses as 'unknown'?
  • Does COALESCE help here?

Tips

  • Translate simple CASE into =
417.sql-0417Easyfresher

What do substr('database', -4), substr('database', 2, 3) and instr('database', 'a') return in SQLite?

They return 'base', 'ata' and 2. A negative start counts from the end of the string, substr positions start at 1, and instr returns the 1-based position of the first match.

Full answer
sql
SELECT substr('database', -4) AS a, substr('database', 2, 3) AS b, instr('database', 'a') AS c, instr('database', 'z') AS d;
abcd
baseata20

'database' has eight characters. Starting four from the end gives 'base'. Starting at position 2 and taking three characters gives 'ata'. The first 'a' is at position 2, so instr returns 2, and a missing substring returns 0, as the fourth column shows. PostgreSQL's substr does not accept negative starts the same way; use right('database', 4) there, and strpos instead of instr. SQLite 3.34 and later also accept substring as an alias (PostgreSQL behaviour stated, not run here).

sql
SELECT substr('database', -4) AS a, substr('database', 2, 3) AS b, instr('database', 'a') AS c, instr('database', 'z') AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • substr positions start at 1
  • Negative start counts from the end in SQLite
  • instr returns 0 when not found
  • PostgreSQL uses right() and strpos()

Common mistakes

  • Using 0-based positions

Follow-ups

  • How would you extract the text after the last '/'?
  • How would you count occurrences of a character?

Tips

  • Count positions from 1
418.sql-0418Easyfresher

Predict SELECT EXISTS (SELECT NULL) and SELECT EXISTS (SELECT 1 WHERE 0).

The first returns 1 and the second 0. EXISTS only checks whether the subquery returns any row; the values in that row, even NULL, do not matter.

Full answer
sql
SELECT EXISTS (SELECT NULL) AS has_null_row, EXISTS (SELECT 1 WHERE 0) AS no_rows, (SELECT NULL) IS NULL AS scalar_null;
has_null_rowno_rowsscalar_null
101

SELECT NULL produces one row containing NULL, which is still a row, so EXISTS is true. SELECT 1 WHERE 0 produces no rows, so EXISTS is false. The third column shows the contrast with a scalar subquery, whose value is NULL either when the row holds NULL or when there is no row, which is why a scalar subquery cannot tell the two cases apart. This is also why the select list inside EXISTS is conventionally SELECT 1: it is never read.

sql
SELECT EXISTS (SELECT NULL) AS has_null_row, EXISTS (SELECT 1 WHERE 0) AS no_rows, (SELECT NULL) IS NULL AS scalar_null;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • EXISTS tests for rows, not values
  • A row of NULLs still counts
  • Scalar subqueries conflate NULL and no row

Common mistakes

  • Thinking EXISTS (SELECT NULL) is false

Follow-ups

  • Why do people write SELECT 1 inside EXISTS?
  • How does NOT EXISTS behave with NULL columns?

Tips

  • Count rows, ignore values
419.sql-0419Mediummid

A compound query ends with ORDER BY 1 DESC LIMIT 2. Does the LIMIT apply to the last branch or to the whole result?

It applies to the whole compound result. ORDER BY and LIMIT at the end of a UNION sort and cut the combined rows, so the output is the two largest values across both branches. To limit one branch alone, wrap it in a subquery.

Full answer
sql
SELECT 5 AS v UNION ALL SELECT 1 UNION ALL SELECT 9 ORDER BY 1 DESC LIMIT 2;
v
9
5

The three branches produce 5, 1 and 9. The trailing ORDER BY sorts all of them, and LIMIT 2 keeps 9 and 5. SQLite does not allow ORDER BY or LIMIT inside an individual branch of a compound select without a subquery, so SELECT * FROM (SELECT ... ORDER BY ... LIMIT 1) UNION ALL ... is the way to cap one branch. PostgreSQL accepts parenthesised branches with their own LIMIT instead (PostgreSQL behaviour stated, not run here). Positional ORDER BY 1 refers to the first output column.

sql
SELECT 5 AS v UNION ALL SELECT 1 UNION ALL SELECT 9 ORDER BY 1 DESC LIMIT 2;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Final ORDER BY and LIMIT apply to the compound
  • Limit a branch by wrapping it
  • ORDER BY 1 is positional

Common mistakes

  • Expecting LIMIT to apply only to the last branch

Follow-ups

  • How would you take the top row from each branch?
  • Why can positional ORDER BY be risky?

Tips

  • Locate where the compound ends
420.sql-0420Hardsenior

Merge overlapping or touching booking intervals into continuous blocks.

Sort intervals by start, and mark a new block whenever an interval starts after the latest end seen so far. A running maximum of end over the previous rows gives that latest end, a running sum of the new-block flags numbers the blocks, and grouping by that number yields each block's MIN(start) and MAX(end).

Full answer
sql
CREATE TABLE busy (id INTEGER PRIMARY KEY, s INTEGER, e INTEGER);
INSERT INTO busy VALUES (1, 1, 4), (2, 3, 6), (3, 6, 8), (4, 10, 12), (5, 11, 11), (6, 15, 18);
sql
WITH flagged AS (
  SELECT s, e, CASE WHEN s <= MAX(e) OVER (ORDER BY s, e ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) THEN 0 ELSE 1 END AS new_block FROM busy
), numbered AS (
  SELECT s, e, SUM(new_block) OVER (ORDER BY s, e ROWS UNBOUNDED PRECEDING) AS block FROM flagged
)
SELECT block, MIN(s) AS block_start, MAX(e) AS block_end FROM numbered GROUP BY block ORDER BY block;
blockblock_startblock_end
118
21012
31518

Intervals 1 to 3 chain together, because 3 starts before 4 ends and 6 starts exactly where the previous one ends, so they form block 1 from 1 to 8. Interval 5 lies inside interval 4, giving block 2 from 10 to 12, and interval 6 stands alone. The running maximum is essential: comparing only with the previous row's end would wrongly split a block when a long interval covers several short ones. Using <= treats touching intervals as one block; change it to < to keep them apart. The first row has no previous rows, so its MAX is NULL and the CASE starts a new block.

sql
CREATE TABLE busy (id INTEGER PRIMARY KEY, s INTEGER, e INTEGER);
INSERT INTO busy VALUES (1, 1, 4), (2, 3, 6), (3, 6, 8), (4, 10, 12), (5, 11, 11), (6, 15, 18);

WITH flagged AS (
  SELECT s, e, CASE WHEN s <= MAX(e) OVER (ORDER BY s, e ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) THEN 0 ELSE 1 END AS new_block FROM busy
), numbered AS (
  SELECT s, e, SUM(new_block) OVER (ORDER BY s, e ROWS UNBOUNDED PRECEDING) AS block FROM flagged
)
SELECT block, MIN(s) AS block_start, MAX(e) AS block_end FROM numbered GROUP BY block ORDER BY block;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Running MAX of previous ends detects overlaps
  • Running SUM of flags numbers blocks
  • Group by block for start and end
  • <= merges touching intervals

Common mistakes

  • Comparing only with the previous row's end
  • Forgetting contained intervals

Follow-ups

  • How would you compute total busy time?
  • How would you find free gaps between blocks?

Tips

  • Explain why the running maximum matters