SQL Practice Problem #012

Find orders placed in January 2019

Return orders created during January 2019 using a range condition.

Problem

Task

Return orders created during January 2019 using a range condition.

Schema

Table Schema

orders(id, customer_id, total_amount, created_at)

Input

Sample Data

idcustomer_idtotal_amountcreated_at
2011722019-01-01
202288.52019-01-31
2033912019-02-01

Output

Expected Output

idcustomer_idtotal_amountcreated_at
2011722019-01-01
202288.52019-01-31

Answer

Check Your Solution

Show Answer and Explanation

Correct Answer

SELECT *
FROM orders
WHERE created_at >= '2019-01-01'
  AND created_at < '2019-02-01'
ORDER BY created_at, id;

Explanation

The start date is inclusive and the next month boundary is exclusive. This pattern also works when created_at contains time values. ORDER BY keeps the displayed output deterministic.

Common Mistakes

  • Using created_at <= '2019-01-31' when the column may include times later that day.
  • Applying a function to every row when a range condition is enough.
  • Using OR instead of AND for the two date boundaries.

Concepts

Related Concepts

Date Ranges WHERE Sargable Conditions Date Range Comparison

Next practice

Related Problems