Sub topic 2
Using IN with a subquery
This chapter assumes you know SELECT and WHERE, comparison operators, AND and OR, and the list form of IN, such as department IN ('Sales', 'Support'). It covers IN with a subquery, BETWEEN for ranges, and the end-of-day trap in date and timestamp filters.
IN with a subquery
A subquery is a query nested inside another query. When IN receives a subquery instead of a fixed list, the database runs the inner query and tests each row against the values it returns. The subquery must return exactly one column.
SELECT id, name
FROM employees
WHERE department_id IN (
SELECT id
FROM departments
WHERE location = 'Berlin'
);This returns employees who work in a department located in Berlin. The filter stays correct when the set of Berlin departments changes, because you never type the department IDs by hand.
Filtering ranges with BETWEEN
BETWEEN tests whether a value falls inside a range. Both endpoints are included, so the two queries below return the same rows.
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000;
SELECT id, name, salary
FROM employees
WHERE salary >= 50000 AND salary <= 70000;Date and timestamp ranges: avoiding the end-of-day trap
Suppose you want all orders placed in March 2026. A natural attempt is:
SELECT id, created_at
FROM orders
WHERE created_at BETWEEN '2026-03-01' AND '2026-03-31';For a DATE column, this works. For a TIMESTAMP column, the text '2026-03-31' means midnight at the start of that day. An order created at 14:00 on March 31 is later than that value, so the query excludes it.
Use a half-open range instead. It includes the start and excludes the first moment after the range:
SELECT id, created_at
FROM orders
WHERE created_at >= '2026-03-01'
AND created_at < '2026-04-01';Exercise
Exercise
Write a query that returns the id and createdat of orders placed on 2026-06-15 from a TIMESTAMP column named createdat, using a half-open range.
Show answer
SELECT id, createdat FROM orders WHERE createdat >= '2026-06-15' AND created_at < '2026-06-16';