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;| name | hire_date | days |
|---|---|---|
| Asha | 2019-03-01 | 2832 |
| Omar | 2024-09-09 | 813 |
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;| name | days |
|---|---|
| Asha | 2832 |
| Omar | 813 |
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