← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 8 of 26

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

Page 8 of 26

Questions 141–160 of 501 · 0 of 20 on this page marked learned

141.sql-0141Mediummid

Is LIKE case-sensitive? Compare SQLite and PostgreSQL for WHERE email LIKE 'ben%'.

SQLite's LIKE is case-insensitive for ASCII letters by default, so 'ben%' matches 'Ben@...'. PostgreSQL's LIKE is case-sensitive and returns nothing; it offers ILIKE for case-insensitive matching. A portable form is LOWER(email) LIKE 'ben%'.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, email FROM contacts WHERE email LIKE 'ben%' ORDER BY id;
idemail
2Ben@Mail.example.org
sql
SELECT id, email FROM contacts WHERE email LIKE 'ben%' ORDER BY id;
idemail

(0 rows)

The same query finds Ben on SQLite and nothing on PostgreSQL. PostgreSQL's ILIKE matches:

sql
SELECT id, email FROM contacts WHERE email ILIKE 'ben%' ORDER BY id;
idemail
2Ben@Mail.example.org

The portable version lowercases the column, which works on both engines:

sql
SELECT id, email FROM contacts WHERE LOWER(email) LIKE 'ben%' ORDER BY id;
idemail
2Ben@Mail.example.org

LOWER(email) on the column prevents a plain index on email from being used. PostgreSQL can index the expression lower(email), or use the citext type (not run here). SQLite's case-folding in LIKE covers ASCII only; it does not fold letters such as Ä without an extension.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, email FROM contacts WHERE email LIKE 'ben%' ORDER BY id;

SELECT id, email FROM contacts WHERE LOWER(email) LIKE 'ben%' ORDER BY id;

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 LIKE ignores ASCII case by default
  • PostgreSQL LIKE is case-sensitive; ILIKE is not
  • LOWER(col) LIKE lower-pattern is portable
  • Functions on the column need an expression index

Common mistakes

  • Testing a search on SQLite and shipping it to PostgreSQL
  • Lowercasing the column but not the pattern

Follow-ups

  • How would you index a case-insensitive email lookup?
  • Is = case-sensitive in SQLite?

Tips

  • Mention both the behaviour and the index cost
142.sql-0142Easyfresher

Write a query that extracts the domain part of each email address.

Find the position of '@' and take everything after it: SUBSTR(email, INSTR(email, '@') + 1) in SQLite. PostgreSQL has SPLIT_PART(email, '@', 2) and POSITION('@' IN email). Lowercase the result, because domains are case-insensitive.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, email, LOWER(SUBSTR(email, INSTR(email, '@') + 1)) AS domain
FROM contacts ORDER BY id;
idemaildomain
1asha.rao@example.comexample.com
2Ben@Mail.example.orgmail.example.org
3chen_li@example.comexample.com
4NULLNULL

INSTR returns the 1-based position of the first @, and SUBSTR with no length takes the rest of the string. Dara's NULL email gives NULL, which is correct.

PostgreSQL's SPLIT_PART reads more clearly:

sql
SELECT id, LOWER(SPLIT_PART(email, '@', 2)) AS domain FROM contacts ORDER BY id;
iddomain
1example.com
2mail.example.org
3example.com
4NULL

Counting domains is then a GROUP BY on the expression. For heavy reporting, store the domain in its own column (or a generated column) rather than parsing on every query.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, email, LOWER(SUBSTR(email, INSTR(email, '@') + 1)) AS domain
FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • INSTR finds the '@' position (1-based)
  • SUBSTR(s, start) takes the rest of the string
  • PostgreSQL has SPLIT_PART
  • Lowercase domains before grouping

Common mistakes

  • Off-by-one errors when skipping the '@'
  • Grouping 'Mail.example.org' and 'mail.example.org' as different domains

Follow-ups

  • How would you extract the part before the '@'?
  • How would you count contacts per domain?

Tips

  • Handle NULL and case in the answer
143.sql-0143Easyfresher

A search for first = 'Chen' finds nothing, though the table shows Chen. What is likely wrong, and how do you clean it?

The stored value probably has leading or trailing spaces, such as ' Chen '. Equality compares every character, so it fails. TRIM removes spaces from both ends (LTRIM and RTRIM do one side); clean the data with an UPDATE and validate input so it does not come back.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id FROM contacts WHERE first = 'Chen';
id

(0 rows)

Comparing lengths exposes the hidden characters:

sql
SELECT id, '[' || first || ']' AS shown, LENGTH(first) AS len FROM contacts WHERE id = 3;
idshownlen
3[ Chen ]7

TRIM on the comparison finds the row, but it hides the problem and blocks plain index use on first:

sql
SELECT id FROM contacts WHERE TRIM(first) = 'Chen';
id
3

Fix the data once, then guard it, for example with CHECK (first = TRIM(first)):

sql
UPDATE contacts SET first = TRIM(first) WHERE first <> TRIM(first);
SELECT id, '[' || first || ']' AS shown FROM contacts ORDER BY id;
idshown
1[Asha]
2[ben]
3[Chen]
4[Dara]

TRIM removes spaces by default. Tabs, non-breaking spaces and line breaks need an explicit character list, such as TRIM(first, ' ' || char(9)) in SQLite.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id FROM contacts WHERE first = 'Chen';

SELECT id, '[' || first || ']' AS shown, LENGTH(first) AS len FROM contacts WHERE id = 3;

SELECT id FROM contacts WHERE TRIM(first) = 'Chen';

UPDATE contacts SET first = TRIM(first) WHERE first <> TRIM(first);
SELECT id, '[' || first || ']' AS shown FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Hidden spaces break equality
  • LENGTH or quote() reveals them
  • TRIM, LTRIM and RTRIM remove spaces
  • Clean with UPDATE and prevent with a CHECK or input validation

Common mistakes

  • Wrapping every query in TRIM instead of fixing the data
  • Assuming TRIM removes tabs and non-breaking spaces

Follow-ups

  • How would you find all rows with leading or trailing whitespace?
  • How would you collapse repeated inner spaces?

Tips

  • Show the length check as a diagnostic step
144.sql-0144Easyfresher

Write a query that normalizes phone numbers by removing spaces, dashes and brackets.

Nest REPLACE calls, one per unwanted character: REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', ''). PostgreSQL can do it in one call with REGEXP_REPLACE(phone, '[^0-9+]', '', 'g'). Store the cleaned form, and keep formatting for display.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, phone,
       REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', '') AS clean
FROM contacts ORDER BY id;
idphoneclean
1+91 98450-12345+919845012345
2(020) 7946 001802079460018
3020-7946-001902079460019
41234512345

Each REPLACE removes one character everywhere it occurs. Four nested calls handle spaces, dashes and both brackets. The leading + stays, because the country code matters.

PostgreSQL's regular-expression version keeps only digits and +:

sql
SELECT id, REGEXP_REPLACE(phone, '[^0-9+]', '', 'g') AS clean FROM contacts ORDER BY id;
idclean
1+919845012345
202079460018
302079460019
412345

SQLite has no built-in REGEXP_REPLACE; the REGEXP operator exists only if an application or extension defines it. For anything beyond a few characters, clean in application code before insert.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, phone,
       REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', '') AS clean
FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • REPLACE(s, from, to) replaces every occurrence
  • Nest REPLACE calls for several characters
  • PostgreSQL has REGEXP_REPLACE with the 'g' flag
  • Store a normalized form; format on display

Common mistakes

  • Removing the + and losing the country code
  • Forgetting the 'g' flag and replacing only the first match in PostgreSQL

Follow-ups

  • How would you find duplicate contacts by normalized phone?
  • Where should phone validation live?

Tips

  • Mention storing E.164 format as a design choice
145.sql-0145Mediummid

What do LENGTH('café') and the byte length of the same string return?

LENGTH counts characters, so it returns 4. The UTF-8 encoding uses 5 bytes, because 'é' takes two. In SQLite, LENGTH(CAST(x AS BLOB)) or OCTET_LENGTH gives the byte count; PostgreSQL has OCTET_LENGTH. Column limits such as VARCHAR(n) count characters in PostgreSQL.

Full answer
sql
SELECT LENGTH('café') AS chars, LENGTH(CAST('café' AS BLOB)) AS bytes;
charsbytes
45
sql
SELECT LENGTH('café') AS chars, OCTET_LENGTH('café') AS bytes;
charsbytes
45

Both engines count 4 characters and 5 bytes. The difference matters when an external system limits bytes (some protocols, older MySQL utf8 indexes) while the database limits characters.

Characters can also be composed differently. 'é' can be one code point, or 'e' followed by a combining accent, which LENGTH counts as two. Normalizing text to one form (NFC) before storage avoids strings that look equal but compare unequal; neither engine does this automatically.

sql
SELECT LENGTH('café') AS chars, LENGTH(CAST('café' AS BLOB)) AS bytes;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • LENGTH counts characters
  • UTF-8 bytes can exceed the character count
  • OCTET_LENGTH or a BLOB cast gives bytes
  • Combining characters change character counts

Common mistakes

  • Assuming one character is one byte
  • Comparing visually equal strings in different Unicode forms

Follow-ups

  • How does VARCHAR(10) count in PostgreSQL?
  • How would you find rows with non-ASCII characters?

Tips

  • Mention Unicode normalization briefly
146.sql-0146Mediummid

Given paths like '/api/v2/users', write a query that returns the second path segment ('v2').

Find the second slash by searching the remainder after the first one, then take the text up to the third slash. In SQLite that means nesting INSTR and SUBSTR, which is easiest to read in a CTE that keeps the remainder. PostgreSQL's SPLIT_PART(path, '/', 3) does it in one call, because the leading slash creates an empty first part.

Full answer
sql
WITH p(path) AS (VALUES ('/api/v2/users'), ('/health')),
 s AS (SELECT path, SUBSTR(path, 2) AS rest1 FROM p),
 t AS (SELECT path, CASE WHEN INSTR(rest1, '/') > 0 THEN SUBSTR(rest1, INSTR(rest1, '/') + 1) END AS rest2 FROM s)
SELECT path,
       CASE WHEN INSTR(rest2, '/') > 0 THEN SUBSTR(rest2, 1, INSTR(rest2, '/') - 1) ELSE rest2 END AS segment2
FROM t ORDER BY path;
pathsegment2
/api/v2/usersv2
/healthNULL

INSTR only finds the first occurrence, so each step strips what has been read and searches the rest. rest1 drops the leading slash, rest2 drops the first segment, and the final SUBSTR cuts at the next slash. When no slash follows, as in /health, the CASE returns NULL.

PostgreSQL:

sql
SELECT path, SPLIT_PART(path, '/', 3) AS segment2
FROM (VALUES ('/api/v2/users'), ('/health')) AS p(path) ORDER BY path;
pathsegment2
/api/v2/usersv2
/health''

SPLIT_PART returns an empty string, not NULL, for a missing part. For deep or variable parsing, a recursive CTE or the json_each split shown earlier scales better than more nesting.

sql
WITH p(path) AS (VALUES ('/api/v2/users'), ('/health')),
 s AS (SELECT path, SUBSTR(path, 2) AS rest1 FROM p),
 t AS (SELECT path, CASE WHEN INSTR(rest1, '/') > 0 THEN SUBSTR(rest1, INSTR(rest1, '/') + 1) END AS rest2 FROM s)
SELECT path,
       CASE WHEN INSTR(rest2, '/') > 0 THEN SUBSTR(rest2, 1, INSTR(rest2, '/') - 1) ELSE rest2 END AS segment2
FROM t ORDER BY path;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • INSTR finds only the first occurrence
  • Strip and search again to find later occurrences
  • PostgreSQL SPLIT_PART takes a part number
  • SPLIT_PART returns '' for missing parts

Common mistakes

  • Counting the leading empty segment wrongly in SPLIT_PART
  • Nesting many INSTR calls in one unreadable expression

Follow-ups

  • How would you return every segment as a row?
  • How would you get the last segment?

Tips

  • Build the expression in steps with a CTE
147.sql-0147Easyfresher

Write a query that shows order ids padded to 8 digits with leading zeros, such as 00000101.

In SQLite use printf('%08d', id) (also called format()). In PostgreSQL use LPAD(id::text, 8, '0') or TO_CHAR(id, 'FM00000000'). Padding is display formatting, so keep the stored value numeric.

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
SELECT id, printf('%08d', id) AS padded FROM orders WHERE id <= 102 ORDER BY id;
idpadded
10100000101
10200000102

%08d means an integer, at least 8 wide, padded with zeros.

PostgreSQL:

sql
SELECT id, LPAD(id::text, 8, '0') AS lpad, TO_CHAR(id, 'FM00000000') AS to_char,
       LPAD('123456789', 8, '0') AS too_long
FROM orders WHERE id <= 102 ORDER BY id;
idlpadto_chartoo_long
101000001010000010112345678
102000001020000010212345678

LPAD pads a string on the left; if the input is longer than the target length, LPAD truncates it, which can silently cut ids. TO_CHAR prints # characters for numbers that do not fit. Choose the width with the largest expected value in mind.

Storing padded values as text breaks numeric sorting and range queries, so format at output time.

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);

SELECT id, printf('%08d', id) AS padded FROM orders WHERE id <= 102 ORDER BY id;

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: printf or format with %08d
  • PostgreSQL: LPAD or TO_CHAR
  • LPAD truncates values longer than the width
  • Store numbers, format for display

Common mistakes

  • Storing zero-padded ids as text and sorting them
  • Choosing a width too small and truncating with LPAD

Follow-ups

  • How would you format a price with two decimals?
  • How would you right-pad a column for a fixed-width file?

Tips

  • Note the truncation behaviour of LPAD
148.sql-0148Mediummid

Split a full name column into first name and last name, assuming the first space separates them.

First name is SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) and last name is SUBSTR(full_name, INSTR(full_name, ' ') + 1). Handle names without a space with CASE, because INSTR returns 0 there. Real names vary a lot, so store given and family names separately when possible.

Full answer
sql
WITH people(full_name) AS (VALUES ('Asha Rao'), ('Mei'), ('Ana María López'))
SELECT full_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN full_name
            ELSE SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) END AS first_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN NULL
            ELSE SUBSTR(full_name, INSTR(full_name, ' ') + 1) END AS last_name
FROM people
ORDER BY full_name;
full_namefirst_namelast_name
Ana María LópezAnaMaría López
Asha RaoAshaRao
MeiMeiNULL

Mei has no space. INSTR returns 0, so the plain SUBSTR expression would give an empty first name. The CASE keeps the whole value as the first name and leaves the last name NULL.

Ana María López shows the limit of the rule: everything after the first space is treated as the last name. Some cultures put the family name first, and many people have several given or family names. A rule-based split is fine for a one-off clean-up, but for new data, collect the parts separately.

PostgreSQL's SPLIT_PART(full_name, ' ', 1) gives the first word directly.

sql
WITH people(full_name) AS (VALUES ('Asha Rao'), ('Mei'), ('Ana María López'))
SELECT full_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN full_name
            ELSE SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) END AS first_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN NULL
            ELSE SUBSTR(full_name, INSTR(full_name, ' ') + 1) END AS last_name
FROM people
ORDER BY full_name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INSTR finds the first space
  • SUBSTR before and after that position gives the two parts
  • Guard the no-space case, where INSTR returns 0
  • Name structure varies across cultures

Common mistakes

  • Producing empty strings for single-word names
  • Assuming every name has exactly two parts

Follow-ups

  • How would you take the last word as the surname instead?
  • How would you design a person table for a global audience?

Tips

  • Raise the global-names point after the query
149.sql-0149Mediummid

Does 'apple' < 'Banana' evaluate to true? How does collation affect string comparison and sorting?

In SQLite's default BINARY collation it is false, because uppercase letters have lower byte values than lowercase ones, so 'B' sorts before 'a'. With COLLATE NOCASE it is true. PostgreSQL uses the database's locale collation, which usually sorts case-insensitively first, but the "C" collation behaves like bytes.

Full answer
sql
SELECT 'apple' < 'Banana' AS binary_cmp, 'apple' < 'Banana' COLLATE NOCASE AS nocase_cmp;
binary_cmpnocase_cmp
01

SQLite compares bytes by default: B (66) is less than a (97), so 'apple' is not less than 'Banana'. NOCASE folds ASCII case before comparing.

Sorting shows the same effect:

sql
WITH w(word) AS (VALUES ('banana'), ('Apple'), ('cherry'), ('Date'))
SELECT group_concat(word, ',') AS binary_order FROM (SELECT word FROM w ORDER BY word)
UNION ALL
SELECT group_concat(word, ',') FROM (SELECT word FROM w ORDER BY word COLLATE NOCASE, word);
binary_order
Apple,Date,banana,cherry
Apple,banana,cherry,Date

PostgreSQL with the C collation sorts by bytes, while a linguistic collation such as und-x-icu, if available, sorts alphabetically:

sql
SELECT string_agg(word, ',' ORDER BY word COLLATE "C") AS c_order,
       string_agg(word, ',' ORDER BY word COLLATE "und-x-icu") AS icu_order
FROM (VALUES ('banana'), ('Apple'), ('cherry'), ('Date')) AS w(word);
c_ordericu_order
Apple,Date,banana,cherryApple,banana,cherry,Date

The practical rule: specify a collation where order matters to users, and do not assume test results on one engine will match production on another.

sql
SELECT 'apple' < 'Banana' AS binary_cmp, 'apple' < 'Banana' COLLATE NOCASE AS nocase_cmp;

WITH w(word) AS (VALUES ('banana'), ('Apple'), ('cherry'), ('Date'))
SELECT group_concat(word, ',') AS binary_order FROM (SELECT word FROM w ORDER BY word)
UNION ALL
SELECT group_concat(word, ',') FROM (SELECT word FROM w ORDER BY word COLLATE NOCASE, word);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Collation decides string comparison and sort order
  • SQLite's default BINARY puts uppercase before lowercase
  • COLLATE NOCASE ignores ASCII case
  • PostgreSQL uses locale collations; "C" sorts by bytes

Common mistakes

  • Assuming alphabetical order is the same on every engine
  • Mixing case in user-facing lists sorted with a binary collation

Follow-ups

  • How would you make a column case-insensitive by default in SQLite?
  • Can collation affect index use?

Tips

  • Use the byte values to explain the result
150.sql-0150Mediummid

How do you count how many times a character appears in a string, such as dots in an email address?

Subtract the length after removing the character from the original length: LENGTH(email) - LENGTH(REPLACE(email, '.', '')). For a multi-character substring, divide the difference by the substring's length.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, email, LENGTH(email) - LENGTH(REPLACE(email, '.', '')) AS dots
FROM contacts ORDER BY id;
idemaildots
1asha.rao@example.com2
2Ben@Mail.example.org2
3chen_li@example.com1
4NULLNULL

Removing every dot shortens the string by exactly the number of dots. The same trick counts words roughly (spaces plus one) or path depth (slashes).

For a substring longer than one character, divide:

text
(LENGTH(s) - LENGTH(REPLACE(s, 'ab', ''))) / LENGTH('ab')

PostgreSQL 15+ also offers REGEXP_COUNT(s, '\.') (not run here).

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, email, LENGTH(email) - LENGTH(REPLACE(email, '.', '')) AS dots
FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • LENGTH minus LENGTH after REPLACE counts occurrences
  • Divide by the substring length for longer patterns
  • NULL input gives NULL
  • Works on every engine with basic functions

Common mistakes

  • Forgetting to divide for multi-character patterns
  • Using LIKE, which only says whether a match exists

Follow-ups

  • How would you count words in a sentence?
  • How would you find emails with more than one '@'?

Tips

  • Explain why the subtraction works
151.sql-0151Mediummid

Write a query that finds phone values made up only of digits.

In SQLite use GLOB with a negated character class: phone NOT GLOB '*[^0-9]*' AND phone <> ''. In PostgreSQL use a regular expression: phone ~ '^[0-9]+$'. LIKE cannot express character classes, so it is the wrong tool here.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, phone FROM contacts
WHERE phone NOT GLOB '*[^0-9]*' AND phone <> ''
ORDER BY id;
idphone
412345

GLOB '*[^0-9]*' matches any string that contains at least one non-digit. NOT GLOB therefore keeps strings with only digits. The empty-string check is needed because an empty string contains no non-digit either. GLOB is case-sensitive and uses * and ? instead of % and _.

PostgreSQL:

sql
SELECT id, phone FROM contacts WHERE phone ~ '^[0-9]+$' ORDER BY id;
idphone
412345

Only 12345 qualifies; the others contain spaces, brackets, dashes or +. For validating new data, a CHECK constraint with the same expression rejects bad values at insert time.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, phone FROM contacts
WHERE phone NOT GLOB '*[^0-9]*' AND phone <> ''
ORDER BY id;

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 GLOB supports character classes like [0-9]
  • NOT GLOB '*[^0-9]*' means only digits
  • PostgreSQL uses ~ with a regular expression
  • Guard against empty strings

Common mistakes

  • Trying to express character classes with LIKE
  • Forgetting that an empty string passes the negated test

Follow-ups

  • How would you enforce this with a CHECK constraint?
  • How would you find emails without exactly one '@'?

Tips

  • Explain the double negative in the GLOB pattern
152.sql-0152Easyfresher

SQLite has no DATE type. How are dates usually stored there, and what are the trade-offs?

SQLite stores dates as ISO-8601 TEXT ('2026-03-01'), as REAL Julian day numbers, or as INTEGER Unix seconds, and its date functions accept all three. ISO text is readable and sorts correctly as a string. Integers are compact and fast to compare but need conversion to read.

Full answer
sql
SELECT date('2026-03-01')                AS from_text,
       date(2461100.5)                     AS from_julian,
       date(1772323200, 'unixepoch')       AS from_unix,
       julianday('2026-03-01')             AS as_julian,
       CAST(strftime('%s', '2026-03-01') AS INTEGER) AS as_unix;
from_textfrom_julianfrom_unixas_julianas_unix
2026-03-012026-03-012026-03-012461100.51772323200

A column declared DATE in SQLite gets NUMERIC affinity, and a value like '2026-03-01' stays TEXT because it does not look like a number. The functions date(), datetime(), julianday() and strftime() read all three forms, as long as integers are flagged with the 'unixepoch' modifier.

Choose one form per column and keep it. ISO text works with string comparison only if every value uses the same zero-padded format: '2026-03-01', never '2026-3-1'. PostgreSQL has real date, timestamp and timestamptz types that validate input, which SQLite does not do.

sql
SELECT date('2026-03-01')                AS from_text,
       date(2461100.5)                     AS from_julian,
       date(1772323200, 'unixepoch')       AS from_unix,
       julianday('2026-03-01')             AS as_julian,
       CAST(strftime('%s', '2026-03-01') AS INTEGER) AS as_unix;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Common forms: ISO TEXT, REAL Julian day, INTEGER Unix time
  • Date functions accept all three
  • ISO text sorts correctly only with consistent zero-padding
  • SQLite does not validate dates; PostgreSQL does

Common mistakes

  • Mixing formats in one column
  • Storing '3/1/2026' style text and sorting it

Follow-ups

  • How would you enforce a valid date format with a CHECK?
  • Which form would you pick for event timestamps?

Tips

  • Mention that SQLite accepts invalid dates like '2026-02-30' as text
153.sql-0153Easyfresher

Write a query that counts orders per month.

Group by the year-month part of the date. In SQLite use strftime('%Y-%m', order_date); in PostgreSQL use date_trunc('month', order_date) or to_char(order_date, 'YYYY-MM'). Always include the year, or January of different years is merged.

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
SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders
FROM orders GROUP BY month ORDER BY month;
monthorders
2026-011
2026-022
2026-033

strftime('%Y-%m', ...) turns each date into a sortable month key. On ISO text, substr(order_date, 1, 7) gives the same key more cheaply.

PostgreSQL:

sql
SELECT date_trunc('month', order_date::date)::date AS month, COUNT(*) AS orders
FROM orders GROUP BY 1 ORDER BY 1;
monthorders
2026-01-011
2026-02-012
2026-03-013

date_trunc returns a timestamp at the start of the month, which keeps date arithmetic possible later. Months with no orders do not appear; to show them with 0, generate the list of months first and LEFT JOIN, as with the calendar CTE.

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);

SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders
FROM orders GROUP BY month ORDER BY month;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Group by a year-month key
  • SQLite: strftime('%Y-%m', d)
  • PostgreSQL: date_trunc('month', d)
  • Missing months need a generated calendar

Common mistakes

  • Grouping by month number only and merging years
  • Expecting empty months to appear

Follow-ups

  • How would you include months with zero orders?
  • How would you compute month-over-month growth?

Tips

  • Mention the year trap
154.sql-0154Easyfresher

How many days passed between each employee's hire date and 2026-12-01?

In SQLite subtract Julian day numbers: julianday('2026-12-01') - julianday(hire_date). In PostgreSQL subtracting two dates gives an integer number of days directly. Cast to INTEGER in SQLite, because julianday returns a real number.

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 name, hire_date,
       CAST(julianday('2026-12-01') - julianday(hire_date) AS INTEGER) AS days
FROM employees WHERE id IN (1, 8) ORDER BY id;
namehire_datedays
Asha2019-03-012832
Omar2024-09-09813

julianday converts a date to a continuous day count, so subtraction gives days, including leap days. With times included, the result has a fractional part, which is why the cast matters.

PostgreSQL:

sql
SELECT name, DATE '2026-12-01' - hire_date::date AS days
FROM employees WHERE id IN (1, 8) ORDER BY id;
namedays
Asha2832
Omar813

Subtracting two timestamp values in PostgreSQL gives an interval instead; use EXTRACT(EPOCH FROM ...) / 86400 or cast to date first if you need a number.

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 name, hire_date,
       CAST(julianday('2026-12-01') - julianday(hire_date) AS INTEGER) AS days
FROM employees WHERE id IN (1, 8) ORDER BY id;

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: julianday(a) - julianday(b) gives days
  • Cast the real result to an integer when needed
  • PostgreSQL: date - date is an integer
  • timestamp - timestamp is an interval in PostgreSQL

Common mistakes

  • Subtracting text dates directly in SQLite
  • Ignoring the fractional part when times are present

Follow-ups

  • How would you compute whole months between two dates?
  • How would you find employees hired in the last 365 days?

Tips

  • Explain why Julian days make subtraction safe
155.sql-0155Hardsenior

What does adding one month to 2026-01-31 return on SQLite and on PostgreSQL?

SQLite's '+1 month' modifier moves to 2026-02-31, which does not exist, and normalizes it forward to 2026-03-03. PostgreSQL's date + interval '1 month' clamps to the last valid day, 2026-02-28. Month arithmetic on month-end dates needs an explicit rule.

Full answer
sql
SELECT date('2026-01-31', '+1 month') AS plus_one_month;
plus_one_month
2026-03-03
sql
SELECT (DATE '2026-01-31' + INTERVAL '1 month')::date AS plus_one_month;
plus_one_month
2026-02-28

SQLite adds to the month field and then normalizes the impossible date by rolling the extra days into the next month. PostgreSQL clamps to the end of the shorter month. Neither is wrong by the standard, but billing code that assumes one behaviour will drift on the other.

Since SQLite 3.46, modifiers ceiling and floor control this; floor clamps like PostgreSQL:

sql
SELECT date('2026-01-31', '+1 month', 'floor') AS floor_rule, date('2026-01-31', '+1 month', 'ceiling') AS ceiling_rule;
floor_ruleceiling_rule
2026-02-282026-03-03

When the rule is "same day next month, or the last day if it does not exist", write it explicitly, or compute from the start of the month.

sql
SELECT date('2026-01-31', '+1 month') AS plus_one_month;

SELECT date('2026-01-31', '+1 month', 'floor') AS floor_rule, date('2026-01-31', '+1 month', 'ceiling') AS ceiling_rule;

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 +1 month normalizes Feb 31 to 3 March
  • PostgreSQL clamps to the last valid day
  • SQLite 3.46 adds floor and ceiling modifiers
  • State the month-end rule explicitly in billing logic

Common mistakes

  • Assuming month arithmetic is portable
  • Generating monthly due dates by repeatedly adding one month to the 31st

Follow-ups

  • How would you produce the last day of each month?
  • How would you generate monthly billing dates from a start date?

Tips

  • Name both results and the reason
156.sql-0156Mediummid

Write an expression that returns the last day of the month for any date.

Go to the first day of the month, add one month, and subtract one day. In SQLite: date(d, 'start of month', '+1 month', '-1 day'). In PostgreSQL: (date_trunc('month', d) + interval '1 month - 1 day')::date. Starting from the first of the month avoids month-length surprises.

Full answer
sql
WITH d(x) AS (VALUES ('2026-01-15'), ('2026-02-10'), ('2028-02-10'))
SELECT x, date(x, 'start of month', '+1 month', '-1 day') AS month_end
FROM d ORDER BY x;
xmonth_end
2026-01-152026-01-31
2026-02-102026-02-28
2028-02-102028-02-29

Because the calculation starts on the 1st, adding a month never hits a missing day, and subtracting one day lands on the month's end, including 29 February in leap years.

PostgreSQL:

sql
SELECT x, (date_trunc('month', x) + INTERVAL '1 month - 1 day')::date AS month_end
FROM (VALUES (DATE '2026-01-15'), (DATE '2026-02-10'), (DATE '2028-02-10')) AS d(x) ORDER BY x;
xmonth_end
2026-01-152026-01-31
2026-02-102026-02-28
2028-02-102028-02-29

The same building blocks give the first day of the next month ('start of month', '+1 month'), which is the right exclusive upper bound for "all rows in this month".

sql
WITH d(x) AS (VALUES ('2026-01-15'), ('2026-02-10'), ('2028-02-10'))
SELECT x, date(x, 'start of month', '+1 month', '-1 day') AS month_end
FROM d ORDER BY x;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • start of month, +1 month, -1 day
  • Starting from the 1st avoids normalization issues
  • Handles leap years automatically
  • The first of next month is a good exclusive bound

Common mistakes

  • Adding 30 days and calling it a month
  • Building month-end from the original day number

Follow-ups

  • How would you get the first Monday of a month?
  • How would you count business days in a month?

Tips

  • Explain why starting at the 1st is safe
157.sql-0157Mediummid

What day-of-week numbers do SQLite and PostgreSQL return for Sunday 2026-03-01 and Monday 2026-03-02?

SQLite's strftime('%w') returns 0 for Sunday and 1 for Monday. PostgreSQL's EXTRACT(DOW) uses the same 0 = Sunday scheme, while EXTRACT(ISODOW) returns 1 for Monday and 7 for Sunday. Weekend filters must use the numbering of the function in use.

Full answer
sql
SELECT strftime('%w', '2026-03-01') AS sun_w, strftime('%w', '2026-03-02') AS mon_w,
       typeof(strftime('%w', '2026-03-01')) AS t;
sun_wmon_wt
01text
sql
SELECT EXTRACT(DOW FROM DATE '2026-03-01') AS sun_dow, EXTRACT(ISODOW FROM DATE '2026-03-01') AS sun_isodow,
       EXTRACT(ISODOW FROM DATE '2026-03-02') AS mon_isodow;
sun_dowsun_isodowmon_isodow
071

SQLite 3.46 also accepts %u (ISO, Monday = 1 to Sunday = 7), matching PostgreSQL's ISODOW:

sql
SELECT strftime('%u', '2026-03-01') AS sun_u, strftime('%u', '2026-03-02') AS mon_u;
sun_umon_u
71

A filter such as strftime('%w', d) IN ('0', '6') selects weekends in SQLite. Note that strftime returns text, so compare with '0' and '6', or cast the result. Many off-by-one bugs come from mixing Sunday-first and Monday-first numbering across tools.

sql
SELECT strftime('%w', '2026-03-01') AS sun_w, strftime('%w', '2026-03-02') AS mon_w,
       typeof(strftime('%w', '2026-03-01')) AS t;

SELECT strftime('%u', '2026-03-01') AS sun_u, strftime('%u', '2026-03-02') AS mon_u;

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 %w: 0 = Sunday
  • PostgreSQL DOW: 0 = Sunday; ISODOW: 7 = Sunday
  • SQLite %u gives ISO numbering
  • strftime returns text, not numbers

Common mistakes

  • Comparing strftime output to integers
  • Assuming Monday = 0 or 1 without checking

Follow-ups

  • How would you count orders per weekday?
  • How would you compute ISO week numbers?

Tips

  • Ask which week convention the business uses
158.sql-0158Mediummid

Write a query that returns each employee's age in whole years on 2026-12-01, given a birth date.

Subtract the birth year from the reference year, then subtract one more if the birthday has not happened yet that year: compare the month-day parts as text. Dividing days by 365.25 is close but can be off by one around birthdays. PostgreSQL has age() and EXTRACT(YEAR FROM age(...)).

Full answer
sql
WITH p(name, born) AS (VALUES ('A', '1996-12-01'), ('B', '1996-12-02'), ('C', '2000-02-29'))
SELECT name, born,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', born) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', born)) AS age
FROM p ORDER BY name;
namebornage
A1996-12-0130
B1996-12-0229
C2000-02-2926

The year difference over-counts by one for anyone whose birthday falls later in the year. Comparing 'MM-DD' strings fixes it, because ISO month-day text sorts in calendar order. Someone born on 2 December is still 29 on 1 December, and someone born on 1 December has just turned 30.

PostgreSQL's age returns an interval of years, months and days:

sql
SELECT name, EXTRACT(YEAR FROM age(DATE '2026-12-01', born))::int AS age
FROM (VALUES ('A', DATE '1996-12-01'), ('B', DATE '1996-12-02'), ('C', DATE '2000-02-29')) AS p(name, born) ORDER BY name;
nameage
A30
B29
C26

The 29 February case needs a rule (is the birthday 28 February or 1 March in non-leap years?). Decide it with the business; the string comparison above treats 1 March as the birthday.

sql
WITH p(name, born) AS (VALUES ('A', '1996-12-01'), ('B', '1996-12-02'), ('C', '2000-02-29'))
SELECT name, born,
       CAST(strftime('%Y', '2026-12-01') AS INTEGER) - CAST(strftime('%Y', born) AS INTEGER)
       - (strftime('%m-%d', '2026-12-01') < strftime('%m-%d', born)) AS age
FROM p ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Year difference minus one if the birthday has not passed
  • Compare 'MM-DD' strings for the birthday check
  • PostgreSQL: EXTRACT(YEAR FROM age(ref, birth))
  • Dividing days by 365.25 can be off by one

Common mistakes

  • Using the year difference alone
  • Ignoring 29 February births

Follow-ups

  • How would you list employees with birthdays next week?
  • How would you compute age in months?

Tips

  • Test with a birthday the day before and the day of the reference date
159.sql-0159Mediummid

How should timestamps be stored when users are in different time zones?

Store instants in UTC, using timestamptz in PostgreSQL or UTC ISO text or Unix seconds in SQLite, and convert to the viewer's zone only for display. Store the user's IANA zone name (such as 'Asia/Kolkata') separately when local wall-clock time matters, for example for recurring 9 AM reminders.

Full answer

SQLite's datetime('now') returns UTC, and 'localtime' converts using the server's zone, not the user's:

sql
SELECT datetime('2026-03-01 10:00:00') AS stored_utc,
       datetime(1772359200, 'unixepoch') AS from_unix_utc;
stored_utcfrom_unix_utc
2026-03-01 10:00:002026-03-01 10:00:00

PostgreSQL's timestamptz stores an absolute instant. AT TIME ZONE turns it into the wall-clock time of a named zone:

sql
SELECT TIMESTAMPTZ '2026-03-01 10:00:00+00' AT TIME ZONE 'UTC'          AS wall_clock_utc,
       TIMESTAMPTZ '2026-03-01 10:00:00+00' AT TIME ZONE 'Asia/Kolkata' AS wall_clock_kolkata,
       TIMESTAMPTZ '2026-03-01 10:00:00+00' AT TIME ZONE 'Europe/Berlin' AS wall_clock_berlin;
wall_clock_utcwall_clock_kolkatawall_clock_berlin
2026-03-01 10:00:002026-03-01 15:30:002026-03-01 11:00:00

One stored instant becomes 10:00 in UTC, 15:30 in Kolkata and 11:00 in Berlin. Storage is unambiguous; display is local. A session's TIME ZONE setting has the same effect on how timestamptz values are printed.

Two cases need more than a UTC instant:

  • Future local events ("every day at 09:00 in Berlin") should store local time plus the zone name, because daylight-saving rules can change before the event.
  • Reports "by day" must state which zone defines the day; a UTC day boundary is 05:30 in India.

Avoid storing fixed offsets such as +05:30 as the zone, since offsets change with daylight saving in many regions.

sql
SELECT datetime('2026-03-01 10:00:00') AS stored_utc,
       datetime(1772359200, 'unixepoch') AS from_unix_utc;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Store instants in UTC or timestamptz
  • Convert to the viewer's zone at display time
  • Store IANA zone names for local recurring events
  • Define the zone used for daily reports

Common mistakes

  • Storing local times without a zone
  • Using the server's zone for users elsewhere

Follow-ups

  • How would you group orders by the customer's local day?
  • What goes wrong with a fixed offset during daylight saving changes?

Tips

  • Separate instants from wall-clock schedules
160.sql-0160Mediummid

Dates were stored as text in the format '5/3/2026'. Why does ORDER BY and a range filter on that column give wrong results?

Text compares character by character, so '10/1/2026' sorts before '5/3/2026' because '1' comes before '5'. Ranges fail for the same reason. Convert the column to ISO 'YYYY-MM-DD' once, then sorting and comparisons work as dates.

Full answer
sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025'))
SELECT d, d < '5/3/2026' AS before_may3_as_text FROM t ORDER BY d;
dbefore_may3_as_text
10/1/20261
12/25/20251
5/3/20260

The order is alphabetical, not chronological. The filter is also wrong: as text, '12/25/2025' is less than '5/3/2026', so a December 2025 date passes a filter meant for 2026.

Convert with string functions into zero-padded ISO text:

sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025')),
 p AS (SELECT d, INSTR(d, '/') AS s1 FROM t),
 q AS (SELECT d, s1, s1 + INSTR(SUBSTR(d, s1 + 1), '/') AS s2 FROM p)
SELECT d,
       SUBSTR(d, s2 + 1) || '-' || printf('%02d', SUBSTR(d, 1, s1 - 1)) || '-' || printf('%02d', SUBSTR(d, s1 + 1, s2 - s1 - 1)) AS iso
FROM q ORDER BY iso;
diso
12/25/20252025-12-25
5/3/20262026-05-03
10/1/20262026-10-01

The conversion assumes month/day/year; a mixed column where some rows are day/month needs a source-by-source rule. After converting, add CHECK (d = date(d)) in SQLite so only valid ISO dates can be stored.

sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025'))
SELECT d, d < '5/3/2026' AS before_may3_as_text FROM t ORDER BY d;

WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025')),
 p AS (SELECT d, INSTR(d, '/') AS s1 FROM t),
 q AS (SELECT d, s1, s1 + INSTR(SUBSTR(d, s1 + 1), '/') AS s2 FROM p)
SELECT d,
       SUBSTR(d, s2 + 1) || '-' || printf('%02d', SUBSTR(d, 1, s1 - 1)) || '-' || printf('%02d', SUBSTR(d, s1 + 1, s2 - s1 - 1)) AS iso
FROM q ORDER BY iso;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Non-ISO text dates sort as strings
  • Range filters on them give wrong answers
  • Convert once to YYYY-MM-DD
  • A CHECK with date() keeps the column valid

Common mistakes

  • Sorting display-formatted dates
  • Guessing day/month order without checking the source

Follow-ups

  • How would you detect rows that are not valid dates?
  • How would you convert day/month data from another source?

Tips

  • Show one wrong comparison concretely