Thinking habit: Check the type before the maths
Days between two dates in SQL (and the text date trap)
The question: For each user, show how many days passed between signing up and their first order.
users
| user_id | signup_date | first_order_date |
|---|---|---|
| 1 | 2026-03-01 | 2026-03-04 |
| 2 | 2026-03-10 | 2026-04-02 |
| 3 | 2026-03-15 | 2026-03-15 |
This query looks right. Run it, decide if it is, and fix it.
Show the answer and why the first query is wrong
Why the usual answer is wrong
SELECT user_id, first_order_date - signup_date AS days FROM users;
SQLite stores these dates as text. Text minus text turns each date into its leading number, the year, so every row shows 2026 - 2026 = 0.
The answer
SELECT user_id, CAST(julianday(first_order_date) - julianday(signup_date) AS INTEGER) AS days FROM users;
julianday turns a date into a day number, so subtracting two of them gives the days between. CAST keeps it a whole number.
In PostgreSQL, date - date works directly; in MySQL use DATEDIFF(b, a); in SQL Server DATEDIFF(day, a, b). Mention you'd check the column type first.
Practise more like this, on real business data
324 interview-style questions on 35 tables with the duplicates, NULLs and missing weeks interviewers test. Free.