Questions 161–180 of 501 · 0 of 20 on this page marked learned
161.sql-0161Mediummid
How do you get the ISO week number of a date, and why can the first days of January belong to week 52 or 53?
ISO weeks start on Monday, and week 1 is the week containing the year's first Thursday. So 1 January 2027, a Friday, belongs to ISO week 53 of 2026. Use strftime('%V') with '%G' for the ISO year in SQLite 3.46+, or EXTRACT(WEEK) and EXTRACT(ISOYEAR) in PostgreSQL. SQLite's older '%W' uses a different rule.
Full answer
sql
SELECT strftime('%G-W%V', '2027-01-01') AS iso_week, strftime('%Y-%W', '2027-01-01') AS pct_w,
strftime('%G-W%V', '2027-01-04') AS first_monday;
iso_week
pct_w
first_monday
2026-W53
2027-00
2027-W01
%V is the ISO week and %G the ISO year that the week belongs to. 1 January 2027 falls in week 53 of ISO year 2026, so grouping by calendar year plus ISO week would put it in the wrong bucket. Pair %V with %G, never with %Y.
%W counts weeks starting on the first Monday of the calendar year, with earlier days in week 00, which is a different scheme.
PostgreSQL:
sql
SELECT EXTRACT(ISOYEAR FROM DATE '2027-01-01') AS iso_year, EXTRACT(WEEK FROM DATE '2027-01-01') AS iso_week;
iso_year
iso_week
2026
53
sql
SELECT strftime('%G-W%V', '2027-01-01') AS iso_week, strftime('%Y-%W', '2027-01-01') AS pct_w,
strftime('%G-W%V', '2027-01-04') AS first_monday;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
ISO weeks start Monday; week 1 contains the first Thursday
Early January can be in week 52 or 53 of the previous ISO year
Pair ISO week with ISO year (%G or ISOYEAR)
%W is not the ISO week
Common mistakes
Combining calendar year with ISO week
Using %W and calling it the ISO week
Follow-ups
How would you group sales by ISO week?
Which countries use Sunday-start weeks in reporting?
Tips
Give the 1 January example
162.sql-0162Mediummid
Write a query that lists customers whose most recent order is more than 30 days before 2026-03-15.
Group orders by customer, take MAX(order_date) as the last order, and keep groups where it is earlier than date('2026-03-15', '-30 days'). Compare against a computed cut-off rather than computing a difference per row, so the condition stays simple and comparable.
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 c.name, MAX(o.order_date) AS last_order
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING MAX(o.order_date) < date('2026-03-15', '-30 days')
ORDER BY c.name;
name
last_order
Ana
2026-02-11
The cut-off is 2026-02-13. Ana's latest order is 11 February, so she qualifies. Bilal ordered on 9 March and Chloe on 1 March, so both are recent.
Two choices to discuss with the business: whether cancelled orders count as activity (here they do), and whether customers who never ordered should appear. Dev never ordered; add a LEFT JOIN and OR MAX(o.order_date) IS NULL to include such customers.
In production, the reference date would be date('now') or CURRENT_DATE, passed in as a parameter for testable queries.
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 c.name, MAX(o.order_date) AS last_order
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING MAX(o.order_date) < date('2026-03-15', '-30 days')
ORDER BY c.name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
MAX(order_date) per customer gives the last order
Compare against a precomputed cut-off date
Decide whether cancelled orders count
Handle never-ordered customers explicitly
Common mistakes
Filtering individual orders in WHERE instead of the latest per customer
Hard-coding today's date and making tests flaky
Follow-ups
How would you list customers with no orders in the last 30 days, including those who never ordered?
How would you compute a churn rate per month?
Tips
Ask whether cancelled orders count as activity
163.sql-0163Easyfresher
Convert the Unix timestamp 1772359200 to a readable date and time, and convert a date back to Unix seconds.
In SQLite use datetime(1772359200, 'unixepoch') and strftime('%s', '2026-03-01 10:00:00'), or unixepoch() in 3.38+. In PostgreSQL use to_timestamp(1772359200) and EXTRACT(EPOCH FROM ts). Unix time is in UTC, so the readable value is UTC unless converted.
Full answer
sql
SELECT datetime(1772359200, 'unixepoch') AS readable,
unixepoch('2026-03-01 10:00:00') AS back_to_unix,
typeof(strftime('%s', '2026-03-01 10:00:00')) AS strftime_type;
readable
back_to_unix
strftime_type
2026-03-01 10:00:00
1772359200
text
The 'unixepoch' modifier tells SQLite to read the number as seconds since 1970-01-01 UTC. Without it, the number would be read as a Julian day. unixepoch() returns an integer, while strftime('%s') returns text.
PostgreSQL:
sql
SET TIME ZONE 'UTC';
SELECT to_timestamp(1772359200) AS readable,
EXTRACT(EPOCH FROM TIMESTAMPTZ '2026-03-01 10:00:00+00')::bigint AS back_to_unix;
readable
back_to_unix
2026-03-01 10:00:00+00:00
1772359200
Some systems store milliseconds. Divide by 1000 first, or the result lands tens of thousands of years in the future.
sql
SELECT datetime(1772359200, 'unixepoch') AS readable,
unixepoch('2026-03-01 10:00:00') AS back_to_unix,
typeof(strftime('%s', '2026-03-01 10:00:00')) AS strftime_type;
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: datetime(n, 'unixepoch') and unixepoch()
PostgreSQL: to_timestamp(n) and EXTRACT(EPOCH FROM ...)
Unix time counts seconds from 1970 in UTC
Check for millisecond values
Common mistakes
Forgetting the 'unixepoch' modifier
Treating millisecond timestamps as seconds
Follow-ups
How would you store event times compactly?
How would you show the time in a user's zone?
Tips
Mention the milliseconds trap
164.sql-0164Mediummid
In SQLite, what does typeof() return after inserting '42', '4.5' and 'abc' into a column declared INTEGER?
SQLite uses type affinity: a declared INTEGER column converts text that looks like a number, so '42' is stored as integer 42 and '4.5' as real 4.5. Text that is not numeric, such as 'abc', is stored as text. PostgreSQL rejects 'abc' for an integer column.
Full answer
sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('42'), ('4.5'), ('abc');
SELECT n, typeof(n) AS stored_as FROM t ORDER BY rowid;
n
stored_as
42
integer
4.5
real
abc
text
The declared type is a preference, not a rule. SQLite tries to convert to the column's affinity and keeps the original value when conversion would lose information.
PostgreSQL enforces the type:
sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('abc');
-- error on purpose
text
Error: invalid input syntax for type integer: "abc"
This flexibility makes SQLite forgiving in prototypes and surprising in production data. Bad values slip in silently and show up later as odd sorting or failed joins. STRICT tables, a CHECK on typeof(col), or validation in the application close the gap.
sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('42'), ('4.5'), ('abc');
SELECT n, typeof(n) AS stored_as FROM t ORDER BY rowid;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Declared types in SQLite set an affinity, not a hard type
Numeric-looking text is converted to numbers
Non-numeric text is stored as text
PostgreSQL rejects values that do not fit the type
Common mistakes
Assuming an INTEGER column in SQLite only contains integers
Discovering mixed types only when sorting or joining
Follow-ups
What are STRICT tables?
How would you find rows with the wrong storage type?
Tips
Use typeof() to show the evidence
165.sql-0165Mediummid
What is a STRICT table in SQLite, and what does it change?
A table created with the STRICT keyword (SQLite 3.37+) enforces declared column types: inserting text that cannot convert into an INTEGER column raises an error. Allowed types are limited to INT, INTEGER, REAL, TEXT, BLOB and ANY. It brings SQLite closer to PostgreSQL's strict typing.
Full answer
sql
CREATE TABLE s (n INTEGER) STRICT;
INSERT INTO s VALUES ('42');
SELECT n, typeof(n) AS stored_as FROM s;
n
stored_as
42
integer
The value '42' is still accepted, because it converts losslessly to an integer. 'abc' cannot, so the insert fails:
sql
CREATE TABLE s_bad (n INTEGER) STRICT;
INSERT INTO s_bad VALUES ('abc');
-- error on purpose
text
Error: cannot store TEXT value in INTEGER column s_bad.n
STRICT also rejects unknown type names such as VARCHAR(20) or DATE, which ordinary SQLite tables accept silently:
sql
CREATE TABLE s2 (name VARCHAR(20)) STRICT; -- error on purpose
text
Error: unknown datatype for s2.name: "VARCHAR(20)"
A column declared ANY in a STRICT table keeps any value unchanged. Existing tables cannot be switched to STRICT in place; the usual path is to create a new table and copy the data.
sql
CREATE TABLE s (n INTEGER) STRICT;
INSERT INTO s VALUES ('42');
SELECT n, typeof(n) AS stored_as FROM s;
-- error on purpose
CREATE TABLE s_bad (n INTEGER) STRICT;
INSERT INTO s_bad VALUES ('abc');
-- error on purpose
CREATE TABLE s2 (name VARCHAR(20)) STRICT;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
STRICT enforces declared column types
Lossless conversions such as '42' to 42 still happen
Only INT, INTEGER, REAL, TEXT, BLOB and ANY are allowed
Requires SQLite 3.37 or later
Common mistakes
Using VARCHAR or DATE names in a STRICT table
Assuming old SQLite versions understand STRICT
Follow-ups
How would you migrate an existing table to STRICT?
When might ANY be useful?
Tips
Contrast with type affinity
166.sql-0166Easyfresher
How do you test whether a number is even, and what does the % operator return for negative numbers?
Use n % 2 = 0 for even numbers. The result of % takes the sign of the left operand on both SQLite and PostgreSQL, so -7 % 2 is -1, not 1. Test odd numbers with n % 2 <> 0 rather than n % 2 = 1, which misses negative odd values.
Full answer
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, -7 % 2 = 1 AS b_is_one;
a
b
c
b_is_one
1
-1
1
0
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, mod(-7, 2) AS mod_fn;
a
b
c
mod_fn
1
-1
1
-1
Both engines truncate integer division toward zero, and % is defined to match: a = (a / b) * b + a % b. With a = -7 and b = 2, a / b is -3, so the remainder must be -1.
Checks written as n % 2 = 1 therefore treat -7 as even. n % 2 <> 0 works for both signs. The same sign rule matters for bucketing by id % 10 when ids can be negative, for example when an import uses negative ids for temporary rows.
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, -7 % 2 = 1 AS b_is_one;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
n % 2 = 0 tests for even numbers
% takes the sign of the left operand
-7 % 2 is -1 on SQLite and PostgreSQL
Use n % 2 <> 0 for odd numbers
Common mistakes
Writing n % 2 = 1 and missing negative odd numbers
Assuming modulo always returns a non-negative value
Follow-ups
How would you return every third row by id?
How would you compute a positive remainder for negative numbers?
Tips
Connect the sign rule to truncating division
167.sql-0167Mediummid
What does CAST('12abc' AS INTEGER) return in SQLite and in PostgreSQL?
SQLite reads the longest numeric prefix and returns 12; for text with no numeric prefix it returns 0. PostgreSQL raises an error for invalid integer input. Validate before casting, because SQLite's lenient cast can turn bad data into plausible numbers.
Full answer
sql
SELECT CAST('12abc' AS INTEGER) AS prefix, CAST('abc' AS INTEGER) AS none, CAST('3.9' AS INTEGER) AS truncated;
prefix
none
truncated
12
0
3
sql
SELECT CAST('12abc' AS INTEGER); -- error on purpose
text
Error: invalid input syntax for type integer: "12abc"
SQLite never fails a CAST to INTEGER; it extracts what it can. That means a typo such as '1O0' (letter O) becomes 1, silently.
To find values that would not convert cleanly in SQLite, compare the cast back to the original:
sql
WITH v(x) AS (VALUES ('12'), ('12abc'), ('007'), ('abc'))
SELECT x, CAST(CAST(x AS INTEGER) AS TEXT) = x AS clean
FROM v ORDER BY x;
x
clean
007
0
12
1
12abc
0
abc
0
The value '007' fails the check too, because the cast drops the leading zeros. Whether that counts as bad data depends on the column: for a quantity it is fine, for a code it is not.
PostgreSQL 16 added pg_input_is_valid('12abc', 'integer') for the same check without raising an error (not run here).
sql
SELECT CAST('12abc' AS INTEGER) AS prefix, CAST('abc' AS INTEGER) AS none, CAST('3.9' AS INTEGER) AS truncated;
WITH v(x) AS (VALUES ('12'), ('12abc'), ('007'), ('abc'))
SELECT x, CAST(CAST(x AS INTEGER) AS TEXT) = x AS clean
FROM v 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
SQLite CAST takes the numeric prefix
Non-numeric text casts to 0 in SQLite
PostgreSQL errors on invalid input
Compare the cast back to the original to detect bad values
Common mistakes
Trusting SQLite casts to validate input
Importing data into PostgreSQL without cleaning it first
Follow-ups
How would you count invalid numeric strings in a column?
What does CAST('3.9' AS INTEGER) return?
Tips
Show the silent conversion risk
168.sql-0168Mediummid
Why might SELECT 0.1 + 0.2 = 0.3 return false, and which type should hold money amounts?
0.1 and 0.2 have no exact binary floating-point representation, so their sum is 0.30000000000000004. SQLite's REAL and PostgreSQL's double precision show this. For money, use PostgreSQL's NUMERIC, which is exact decimal, or store integer minor units such as cents on any engine.
Full answer
sql
SELECT 0.1 + 0.2 = 0.3 AS equal, (0.1 + 0.2) - 0.3 AS difference;
equal
difference
0
5.551115123125783e-17
SQLite stores 0.1 as a binary double, so the sum is slightly above 0.3; the difference is tiny but not zero. PostgreSQL treats the literal 0.1 as numeric, which is exact, unless you ask for double precision:
sql
SELECT 0.1 + 0.2 = 0.3 AS numeric_equal,
0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal,
0.1::float8 + 0.2::float8 AS float_sum;
numeric_equal
float_equal
float_sum
true
false
0.30000000000000004
SQLite has no exact decimal type; DECIMAL(10,2) is accepted as a type name but gets NUMERIC affinity and stores floats or integers. So in SQLite, store cents as INTEGER:
sql
CREATE TABLE payments (id INTEGER PRIMARY KEY, amount_cents INTEGER NOT NULL);
INSERT INTO payments VALUES (1, 10), (2, 20);
SELECT SUM(amount_cents) = 30 AS exact, printf('%.2f', SUM(amount_cents) / 100.0) AS shown FROM payments;
exact
shown
1
0.30
Floating point is fine for measurements where tiny errors do not matter. For balances, invoices and anything that must add up exactly, use exact types.
sql
SELECT 0.1 + 0.2 = 0.3 AS equal, (0.1 + 0.2) - 0.3 AS difference;
CREATE TABLE payments (id INTEGER PRIMARY KEY, amount_cents INTEGER NOT NULL);
INSERT INTO payments VALUES (1, 10), (2, 20);
SELECT SUM(amount_cents) = 30 AS exact, printf('%.2f', SUM(amount_cents) / 100.0) AS shown FROM payments;
Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
Binary floats cannot represent most decimal fractions exactly
PostgreSQL NUMERIC is exact decimal
SQLite has no exact decimal; store integer cents
Floats are fine for measurements, not money
Common mistakes
Comparing floats with =
Declaring DECIMAL in SQLite and assuming exact arithmetic
Follow-ups
How would you round money for display?
What happens when you sum many REAL amounts?
Tips
Mention integer cents as the portable answer
169.sql-0169Easyfresher
How are boolean values stored in SQLite compared with PostgreSQL?
SQLite has no separate boolean type; TRUE and FALSE are aliases for 1 and 0, and comparisons return 1 or 0. PostgreSQL has a real boolean type with true, false and NULL, and it will not compare a boolean with an integer directly. Write conditions as col = 1 in SQLite and col in PostgreSQL, or use a CHECK to restrict SQLite values to 0 and 1.
Full answer
sql
SELECT TRUE AS t, FALSE AS f, TRUE + TRUE AS two, 5 > 3 AS cmp, typeof(5 > 3) AS cmp_type;
t
f
two
cmp
cmp_type
1
0
2
1
integer
In SQLite, TRUE is simply 1, so TRUE + TRUE is 2 and a comparison like 5 > 3 produces the integer 1.
PostgreSQL keeps booleans separate:
sql
SELECT TRUE AS t, 5 > 3 AS cmp, pg_typeof(5 > 3) AS cmp_type;
t
cmp
cmp_type
true
true
boolean
sql
SELECT TRUE + TRUE; -- error on purpose
text
Error: operator does not exist: boolean + boolean
A portable SQLite schema can restrict a flag column with CHECK (active IN (0, 1)), otherwise any value can be stored. Summing a flag (SUM(active)) counts true rows in SQLite; PostgreSQL needs COUNT(*) FILTER (WHERE active) or SUM(active::int).
sql
SELECT TRUE AS t, FALSE AS f, TRUE + TRUE AS two, 5 > 3 AS cmp, typeof(5 > 3) AS cmp_type;
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 TRUE and FALSE are 1 and 0
Comparisons in SQLite return integers
PostgreSQL has a strict boolean type
Constrain SQLite flag columns with CHECK
Common mistakes
Adding booleans in PostgreSQL without a cast
Storing 'Y', 'yes' and 1 in the same SQLite flag column
Follow-ups
How would you count active users on each engine?
How does NULL behave in a boolean column?
Tips
Show TRUE + TRUE on SQLite
170.sql-0170Easyfresher
A column is declared VARCHAR(3). What happens when you insert 'abcdef' in SQLite and in PostgreSQL?
SQLite ignores the length and stores all six characters, because VARCHAR(3) only sets TEXT affinity. PostgreSQL raises an error that the value is too long for character varying(3). Use a CHECK on length() to enforce limits in SQLite.
Full answer
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
SELECT code, length(code) AS len FROM v;
code
len
abcdef
6
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
-- error on purpose
text
Error: value too long for type character varying(3)
In PostgreSQL, text and varchar without a length perform the same; varchar(n) adds a length check and nothing else. Many teams use text with a CHECK constraint, which can be changed later without rewriting the column type.
In SQLite, enforce the limit explicitly:
sql
CREATE TABLE v2 (code TEXT CHECK (length(code) <= 3));
INSERT INTO v2 VALUES ('abcdef');
-- error on purpose
text
Error: CHECK constraint failed: length(code) <= 3
Lengths count characters on both engines, not bytes, so 'café' has length 4. When data moves from SQLite to PostgreSQL, values that were silently accepted can make the import fail, so check MAX(length(col)) before migrating.
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
SELECT code, length(code) AS len FROM v;
-- error on purpose
CREATE TABLE v2 (code TEXT CHECK (length(code) <= 3));
INSERT INTO v2 VALUES ('abcdef');
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 ignores VARCHAR lengths
PostgreSQL enforces varchar(n) and errors on longer values
text and varchar perform the same in PostgreSQL
Use CHECK (length(col) <= n) in SQLite
Common mistakes
Relying on VARCHAR(n) to validate data in SQLite
Choosing tiny lengths that later need migrations
Follow-ups
What does CHAR(n) do with shorter values in PostgreSQL?
How would you limit a username to 20 characters on both engines?
Tips
State both engine results plainly
171.sql-0171Mediummid
In SQLite, how do values of different storage classes compare, such as 10 < '9' or 10 < 9?
Without a column affinity involved, SQLite orders storage classes as NULL < numbers < text < blob, so the integer 10 is less than any text, including '9'. Numbers compare numerically and text compares by collation. Comparing a column with a numeric affinity to text converts the text first, which changes the result.
Full answer
sql
SELECT 10 < '9' AS num_vs_text, '10' < '9' AS text_vs_text, 10 < 9 AS num_vs_num;
num_vs_text
text_vs_text
num_vs_num
1
1
0
The literals have no affinity, so 10 versus '9' compares a number with text, and every number sorts before every text value. Between two text values, '10' < '9' because '1' comes before '9'.
When one side is a column with INTEGER affinity, SQLite applies the affinity to the text literal first:
sql
CREATE TABLE n (x INTEGER);
INSERT INTO n VALUES (10);
SELECT x < '9' AS col_vs_text FROM n;
col_vs_text
0
The column comparison converts '9' to 9, so 10 is not less than it. Mixed storage classes in one column produce mixed sort orders:
sql
CREATE TABLE m (x);
INSERT INTO m VALUES (10), ('9'), (2), ('abc'), (NULL);
SELECT x, typeof(x) AS t FROM m ORDER BY x;
x
t
NULL
null
2
integer
10
integer
9
text
abc
text
sql
SELECT 10 < '9' AS num_vs_text, '10' < '9' AS text_vs_text, 10 < 9 AS num_vs_num;
CREATE TABLE n (x INTEGER);
INSERT INTO n VALUES (10);
SELECT x < '9' AS col_vs_text FROM n;
CREATE TABLE m (x);
INSERT INTO m VALUES (10), ('9'), (2), ('abc'), (NULL);
SELECT x, typeof(x) AS t FROM m ORDER BY x;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Storage class order: NULL, numbers, text, blob
Text compares as text, so '10' < '9'
Column affinity can convert the other operand
Mixed types in one column sort in groups
Common mistakes
Storing numbers as text and sorting them
Assuming literal comparisons behave like column comparisons
Follow-ups
How would you sort a text column numerically?
What does PostgreSQL do with 10 < '9'?
Tips
Use typeof() on the column to diagnose
172.sql-0172Hardsenior
What does ROUND(2.5) return, and does ROUND(-2.5) round away from zero on SQLite and PostgreSQL?
SQLite rounds halves away from zero, giving 3.0 and -3.0. PostgreSQL's round on numeric also rounds halves away from zero (3 and -3), but round on double precision uses the platform's rounding, which is round-half-to-even, giving 2 and -2. The type of the argument decides the rule.
Full answer
sql
SELECT ROUND(2.5) AS pos, ROUND(-2.5) AS neg, ROUND(3.5) AS pos2, typeof(ROUND(2.5)) AS t;
pos
neg
pos2
t
3.0
-3.0
4.0
real
SQLite returns a real (3.0), not an integer.
sql
SELECT ROUND(2.5) AS pos, ROUND(-2.5) AS neg, ROUND(3.5) AS pos2;
pos
neg
pos2
3
-3
4
PostgreSQL treats 2.5 as numeric, so halves go away from zero. Cast to double precision and the result changes:
sql
SELECT ROUND(2.5::float8) AS pos, ROUND(-2.5::float8) AS neg, ROUND(3.5::float8) AS pos2;
pos
neg
pos2
2.0
-2.0
4.0
Banker's rounding (half to even) avoids upward bias when rounding many values, which matters in finance and statistics. When rounding rules matter, use exact types, apply the rule explicitly, and test the halfway cases.
sql
SELECT ROUND(2.5) AS pos, ROUND(-2.5) AS neg, ROUND(3.5) AS pos2, typeof(ROUND(2.5)) AS t;
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 rounds halves away from zero and returns a real
PostgreSQL numeric rounds halves away from zero
PostgreSQL double precision rounds half to even
The argument type decides the rounding rule
Common mistakes
Assuming every engine and type rounds 2.5 to 3
Rounding money stored as floats
Follow-ups
What does ROUND(1.005, 2) return with floats?
When is banker's rounding preferred?
Tips
Test halfway values explicitly
173.sql-0173Easyfresher
Should postal codes and phone numbers be stored as integers or as text?
Store them as text. They are identifiers, not quantities: you never add them, they can have leading zeros ('02134'), and they often contain non-digits such as '+', spaces or letters (UK postcodes). An integer column silently drops leading zeros.
Full answer
sql
CREATE TABLE addr (zip_int INTEGER, zip_text TEXT);
INSERT INTO addr VALUES ('02134', '02134');
SELECT zip_int, zip_text FROM addr;
zip_int
zip_text
2134
02134
The INTEGER column turned '02134' into 2134. The text column kept it. The same applies to account numbers, product codes and ids from other systems: if arithmetic on the value makes no sense, it is not a number.
Text also handles international formats such as 'SW1A 1AA' or '+44 20 7946 0018'. Validate the format with a CHECK or in the application, and normalize (for example to E.164 for phones) so that comparisons work.
sql
CREATE TABLE addr (zip_int INTEGER, zip_text TEXT);
INSERT INTO addr VALUES ('02134', '02134');
SELECT zip_int, zip_text FROM addr;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Identifiers that are never calculated belong in text
Integers drop leading zeros
Many codes contain letters or symbols
Validate and normalize text identifiers
Common mistakes
Storing ZIP codes as integers and losing leading zeros
Using numeric types for credit card or account numbers
Follow-ups
How would you validate a 5-digit postal code column?
Would you ever store an id from another system as an integer?
Tips
Ask: would you ever add two of these values?
174.sql-0174Mediummid
When would you choose a UUID primary key over an auto-incrementing integer?
UUIDs can be generated anywhere without coordination, are safe to expose in URLs without revealing counts, and make merging data from several systems easy. Integers are smaller, faster to index and easier to read. Random UUIDs (v4) scatter inserts across a B-tree index; time-ordered UUIDs (v7) reduce that cost.
Full answer
Integer keys use 4 or 8 bytes and grow in order, so inserts append to the end of the index. They also leak information: /orders/1042 suggests roughly a thousand orders, and anyone can try 1043.
UUIDs use 16 bytes (36 as text). Clients, offline devices or several services can create them without asking the database, which helps with replication and imports.
Costs to mention:
Every secondary index and foreign key also stores the larger key.
Random v4 values land anywhere in the index, so inserts touch more pages and caches work less well.
UUIDv7 puts a timestamp first, so new keys are mostly increasing.
PostgreSQL has a native uuid type and gen_random_uuid():
sql
SELECT pg_typeof(gen_random_uuid()) AS type, length(gen_random_uuid()::text) AS text_length;
type
text_length
uuid
36
SQLite has no UUID type or built-in generator; store 16-byte BLOBs or text generated by the application. A common compromise is an integer primary key for joins plus a unique public UUID column for external use.
Key points
UUIDs can be created without coordination
Integers are smaller and insert in order
Random UUIDs fragment B-tree inserts; v7 is time-ordered
Exposed integer ids reveal counts and invite guessing
Integer internal key plus public UUID is a common compromise
Common mistakes
Storing UUIDs as 36-character text in large tables
Using sequential ids in public URLs without access checks
Follow-ups
How does key size affect secondary indexes?
How would you migrate from integer to UUID keys?
Tips
Give both sides and a compromise
175.sql-0175Easyfresher
How do a primary key and a unique constraint differ?
A table has at most one primary key; its columns must be unique and NOT NULL, and it is the row's main identifier that foreign keys usually reference. A table can have many unique constraints, and in most engines a unique column may hold several NULLs. Both are enforced with a unique index.
Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users VALUES (1, 'a@x.com'), (2, NULL), (3, NULL);
SELECT id, email FROM users ORDER BY id;
Two NULL emails are accepted, because NULL is not equal to NULL, so they do not clash. A second identical email is rejected:
sql
CREATE TABLE users2 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users2 VALUES (1, 'a@x.com'), (2, 'a@x.com');
-- error on purpose
text
Error: UNIQUE constraint failed: users2.email
The primary key rejects a duplicate id just the same:
sql
CREATE TABLE users3 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users3 VALUES (1, 'a@x.com'), (1, 'b@x.com');
-- error on purpose
text
Error: UNIQUE constraint failed: users3.id
One SQLite quirk: unless the table is declared STRICT or WITHOUT ROWID, or the key is an INTEGER PRIMARY KEY, a primary key column accepts NULL for historical reasons. Declare key columns NOT NULL explicitly to be safe.
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users VALUES (1, 'a@x.com'), (2, NULL), (3, NULL);
SELECT id, email FROM users ORDER BY id;
-- error on purpose
CREATE TABLE users2 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users2 VALUES (1, 'a@x.com'), (2, 'a@x.com');
-- error on purpose
CREATE TABLE users3 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users3 VALUES (1, 'a@x.com'), (1, 'b@x.com');
Checked on SQLite 3.46.1, run twice with identical output.
Key points
One primary key per table; many unique constraints
Primary key columns are unique and not null
Unique columns usually allow several NULLs
Both are backed by a unique index
Common mistakes
Assuming UNIQUE also means NOT NULL
Relying on SQLite to reject NULL in a non-integer primary key
Follow-ups
What is a natural key versus a surrogate key?
How would you allow only one NULL in a unique column?
Tips
Mention the NULL behaviour of UNIQUE
176.sql-0176Easyfresher
What does a foreign key enforce, and why might SQLite not enforce it by default?
A foreign key requires that every non-NULL value in the child column exists in the referenced parent key, and it controls what happens when a parent row is deleted or updated. SQLite enforces foreign keys only when PRAGMA foreign_keys = ON is set for each connection, for backward compatibility. PostgreSQL always enforces them.
Full answer
With enforcement off (SQLite's default), an order can point at a customer that does not exist:
sql
CREATE TABLE customers (id INTEGER PRIMARY KEY);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id));
INSERT INTO orders VALUES (1, 99);
SELECT id, customer_id FROM orders;
id
customer_id
1
99
With the pragma on, the same insert fails:
sql
PRAGMA foreign_keys = ON;
CREATE TABLE customers2 (id INTEGER PRIMARY KEY);
CREATE TABLE orders2 (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers2(id));
INSERT INTO orders2 VALUES (1, 99);
-- error on purpose
text
Error: FOREIGN KEY constraint failed
The pragma is per connection and is not stored in the database file, so every application connection must set it. A NULL foreign key value is always allowed; add NOT NULL if the relationship is mandatory.
The referenced columns must be a primary key or have a unique constraint. Index the child column too: neither engine does it automatically, and deletes on the parent need it to find child rows quickly.
sql
CREATE TABLE customers (id INTEGER PRIMARY KEY);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id));
INSERT INTO orders VALUES (1, 99);
SELECT id, customer_id FROM orders;
-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE customers2 (id INTEGER PRIMARY KEY);
CREATE TABLE orders2 (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers2(id));
INSERT INTO orders2 VALUES (1, 99);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Foreign keys require child values to exist in the parent
NULL child values are allowed unless NOT NULL is added
SQLite needs PRAGMA foreign_keys = ON per connection
Index the child column yourself
Common mistakes
Assuming SQLite enforces foreign keys by default
Forgetting the index on the referencing column
Follow-ups
What do ON DELETE CASCADE and SET NULL do?
How do you find orphaned rows created before enforcement was on?
Tips
State the SQLite pragma explicitly
177.sql-0177Mediummid
Compare ON DELETE CASCADE, SET NULL and RESTRICT. Which would you choose for order lines, and which for an employee's manager?
CASCADE deletes child rows with the parent, SET NULL clears the reference, and RESTRICT (or the default NO ACTION) blocks the delete while children exist. Order lines belong to their order, so CASCADE fits. An employee should not vanish when their manager leaves, so SET NULL or RESTRICT fits, with reassignment handled explicitly.
Full answer
sql
PRAGMA foreign_keys = ON;
CREATE TABLE orders (id INTEGER PRIMARY KEY);
CREATE TABLE lines (order_id INTEGER REFERENCES orders(id) ON DELETE CASCADE, product TEXT);
CREATE TABLE emp (id INTEGER PRIMARY KEY, manager_id INTEGER REFERENCES emp(id) ON DELETE SET NULL);
INSERT INTO orders VALUES (1), (2);
INSERT INTO lines VALUES (1, 'Pen'), (1, 'Bag'), (2, 'Lamp');
INSERT INTO emp VALUES (10, NULL), (11, 10);
DELETE FROM orders WHERE id = 1;
DELETE FROM emp WHERE id = 10;
SELECT 'lines' AS t, COUNT(*) AS n FROM lines UNION ALL SELECT 'emp 11 manager', manager_id FROM emp WHERE id = 11;
t
n
lines
1
emp 11 manager
NULL
Deleting order 1 removed its lines. Deleting manager 10 kept employee 11 and cleared the link.
RESTRICT prevents the delete instead:
sql
PRAGMA foreign_keys = ON;
CREATE TABLE cust (id INTEGER PRIMARY KEY);
CREATE TABLE inv (id INTEGER PRIMARY KEY, cust_id INTEGER REFERENCES cust(id) ON DELETE RESTRICT);
INSERT INTO cust VALUES (1);
INSERT INTO inv VALUES (100, 1);
DELETE FROM cust WHERE id = 1;
-- error on purpose
text
Error: FOREIGN KEY constraint failed
Guidelines that hold up in practice:
CASCADE for parts that have no meaning alone (order lines, comment attachments).
SET NULL for optional relationships (manager, assigned reviewer).
RESTRICT for references that must be resolved by a person first (a customer with invoices).
CASCADE chains can delete far more than expected; review every path before using it on central tables.
sql
PRAGMA foreign_keys = ON;
CREATE TABLE orders (id INTEGER PRIMARY KEY);
CREATE TABLE lines (order_id INTEGER REFERENCES orders(id) ON DELETE CASCADE, product TEXT);
CREATE TABLE emp (id INTEGER PRIMARY KEY, manager_id INTEGER REFERENCES emp(id) ON DELETE SET NULL);
INSERT INTO orders VALUES (1), (2);
INSERT INTO lines VALUES (1, 'Pen'), (1, 'Bag'), (2, 'Lamp');
INSERT INTO emp VALUES (10, NULL), (11, 10);
DELETE FROM orders WHERE id = 1;
DELETE FROM emp WHERE id = 10;
SELECT 'lines' AS t, COUNT(*) AS n FROM lines UNION ALL SELECT 'emp 11 manager', manager_id FROM emp WHERE id = 11;
-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE cust (id INTEGER PRIMARY KEY);
CREATE TABLE inv (id INTEGER PRIMARY KEY, cust_id INTEGER REFERENCES cust(id) ON DELETE RESTRICT);
INSERT INTO cust VALUES (1);
INSERT INTO inv VALUES (100, 1);
DELETE FROM cust WHERE id = 1;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
CASCADE deletes dependent rows
SET NULL keeps children and clears the reference
RESTRICT or NO ACTION blocks the delete
Choose by whether the child makes sense without the parent
Common mistakes
Using CASCADE on a central table and losing history
Using SET NULL on a NOT NULL column, which then fails
Follow-ups
When do RESTRICT and NO ACTION behave differently?
How would you soft-delete instead?
Tips
Tie each option to a concrete relationship
178.sql-0178Easyfresher
Write a table definition that rejects negative prices and an end date before the start date.
Use CHECK constraints: CHECK (price >= 0) on the column and a table-level CHECK (end_date IS NULL OR end_date >= start_date). A CHECK passes when the expression is true or NULL, so add NOT NULL where a value is required.
Full answer
sql
CREATE TABLE promos (
id INTEGER PRIMARY KEY,
price INTEGER NOT NULL CONSTRAINT price_non_negative CHECK (price >= 0),
start_date TEXT NOT NULL,
end_date TEXT,
CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date)
);
INSERT INTO promos VALUES (1, 100, '2026-03-01', NULL), (2, 0, '2026-03-01', '2026-03-31');
SELECT * FROM promos ORDER BY id;
id
price
start_date
end_date
1
100
2026-03-01
NULL
2
0
2026-03-01
2026-03-31
Both bad rows are rejected:
sql
CREATE TABLE p2 (price INTEGER NOT NULL CHECK (price >= 0));
INSERT INTO p2 VALUES (-5);
-- error on purpose
text
Error: CHECK constraint failed: price >= 0
sql
CREATE TABLE p3 (start_date TEXT NOT NULL, end_date TEXT, CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date));
INSERT INTO p3 VALUES ('2026-03-10', '2026-03-01');
-- error on purpose
text
Error: CHECK constraint failed: dates_in_order
The NULL rule matters: CHECK (price >= 0) lets a NULL price through, because the check evaluates to unknown, not false. That is why price is also NOT NULL here, while end_date is allowed to be NULL for open-ended promotions.
Name constraints (CONSTRAINT price_non_negative CHECK (...)) so error messages and later migrations are clear.
sql
CREATE TABLE promos (
id INTEGER PRIMARY KEY,
price INTEGER NOT NULL CONSTRAINT price_non_negative CHECK (price >= 0),
start_date TEXT NOT NULL,
end_date TEXT,
CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date)
);
INSERT INTO promos VALUES (1, 100, '2026-03-01', NULL), (2, 0, '2026-03-01', '2026-03-31');
SELECT * FROM promos ORDER BY id;
-- error on purpose
CREATE TABLE p2 (price INTEGER NOT NULL CHECK (price >= 0));
INSERT INTO p2 VALUES (-5);
-- error on purpose
CREATE TABLE p3 (start_date TEXT NOT NULL, end_date TEXT, CONSTRAINT dates_in_order CHECK (end_date IS NULL OR end_date >= start_date));
INSERT INTO p3 VALUES ('2026-03-10', '2026-03-01');
Checked on SQLite 3.46.1, run twice with identical output.
Key points
CHECK enforces a rule per row
Table-level CHECKs can compare columns
NULL makes a CHECK pass; combine with NOT NULL
Name constraints for clearer errors
Common mistakes
Assuming CHECK rejects NULLs
Enforcing simple row rules only in application code
Follow-ups
Can a CHECK refer to other rows or tables?
How would you add a CHECK to an existing table with bad data?
Tips
Mention the NULL pass-through
179.sql-0179Mediummid
What is a composite primary key, and when is it a better choice than a surrogate id?
A composite primary key uses several columns together, such as (student_id, course_id) in an enrolment table. It fits junction tables and other rows whose identity is the combination, because it prevents duplicates directly. A surrogate id is simpler for rows referenced by many other tables, but then the natural combination still needs a UNIQUE constraint.
Full answer
sql
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol VALUES (1, 10), (1, 20), (2, 10);
SELECT * FROM enrol ORDER BY student_id, course_id;
student_id
course_id
1
10
1
20
2
10
The second enrolment of student 1 in course 10 is rejected:
With a surrogate id instead, the duplicate would be accepted unless a separate UNIQUE (student_id, course_id) existed. Forgetting that constraint is a common source of duplicate rows.
Column order matters for the index behind the key: (student_id, course_id) supports lookups by student alone, but not by course alone, so add an index on course_id if that query is common.
Composite keys get awkward when other tables must reference the row, because every referencing table then needs all the columns.
sql
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol VALUES (1, 10), (1, 20), (2, 10);
SELECT * FROM enrol ORDER BY student_id, course_id;
-- error on purpose
CREATE TABLE enrol2 (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol2 VALUES (1, 10), (1, 10);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Composite keys combine columns into one identity
Ideal for junction tables
Surrogate ids still need a UNIQUE on the natural key
Column order affects which lookups the index serves
Common mistakes
Adding a surrogate id to a junction table and forgetting the UNIQUE
Ignoring index order for lookups by the second column
Follow-ups
How would a grade-history table reference an enrolment?
When would you add a surrogate id to a junction table?
Tips
Mention the index order point
180.sql-0180Easyfresher
What does a DEFAULT clause do, and what value does a column get when an INSERT omits it without a default?
DEFAULT supplies a value when the INSERT does not mention the column, such as DEFAULT 'pending' or DEFAULT CURRENT_TIMESTAMP. Without a default, the column gets NULL, and if it is NOT NULL the insert fails. An explicit NULL in the INSERT overrides the default.
Full answer
sql
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
status TEXT DEFAULT 'pending',
created TEXT DEFAULT CURRENT_TIMESTAMP,
note TEXT
);
INSERT INTO tickets (id) VALUES (1);
INSERT INTO tickets (id, status) VALUES (2, NULL);
SELECT id, status, created IS NOT NULL AS has_created, note FROM tickets ORDER BY id;
id
status
has_created
note
1
pending
1
NULL
2
NULL
1
NULL
Row 1 omitted status and created, so both defaults applied. note has no default and became NULL. Row 2 passed NULL for status explicitly, and the default did not apply.
If the column is NOT NULL, the explicit NULL is an error instead:
sql
CREATE TABLE t2 (id INTEGER PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending');
INSERT INTO t2 (id, status) VALUES (1, NULL);
-- error on purpose
text
Error: NOT NULL constraint failed: t2.status
CURRENT_TIMESTAMP in SQLite is UTC text. PostgreSQL's now() returns the transaction start time as timestamptz.
sql
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
status TEXT DEFAULT 'pending',
created TEXT DEFAULT CURRENT_TIMESTAMP,
note TEXT
);
INSERT INTO tickets (id) VALUES (1);
INSERT INTO tickets (id, status) VALUES (2, NULL);
SELECT id, status, created IS NOT NULL AS has_created, note FROM tickets ORDER BY id;
-- error on purpose
CREATE TABLE t2 (id INTEGER PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending');
INSERT INTO t2 (id, status) VALUES (1, NULL);
Checked on SQLite 3.46.1, run twice with identical output.
Key points
DEFAULT applies only when the column is omitted
An explicit NULL overrides the default
No default means NULL, or an error if NOT NULL
CURRENT_TIMESTAMP gives a creation time
Common mistakes
Sending NULL from an ORM and expecting the default