To filter database records by date in SQL, you use the WHERE clause with a date condition—such as =, >, <, or BETWEEN—applied to a date-type column. This works only if the column stores date/time data (e.g., DATE, DATETIME, or TIMESTAMP), and your database supports standard SQL date literals or functions. No special tools or setup beyond a working SQL client and table with date data are required.
What You'll Need
- A database with a table containing a column of date or datetime type (e.g.,
order_date,created_at) - SQL client or interface (e.g., psql, MySQL Workbench, DBeaver, or a web-based console)
- Basic familiarity with SQL syntax (especially
SELECTandWHERE) - Correct date format for your database system (e.g.,
'YYYY-MM-DD'for most systems)
Step-by-Step
- Identify the date column and table. First, confirm which table holds your data and which column stores the date value. Run
DESCRIBE table_name;(MySQL, MariaDB) or\d table_name;(PostgreSQL) to inspect the schema. Ensure the column is of a proper date type—DATE,DATETIME, orTIMESTAMP. Avoid filtering on text-based date columns (e.g.,VARCHAR), as this leads to incorrect comparisons. - Write a basic
WHEREclause for an exact date. To find all rows where the date equals a specific day (e.g., April 5, 2023), use:SELECT * FROM orders WHERE order_date = '2023-04-05';
For MySQL and PostgreSQL, enclose the date in single quotes. SQL Server accepts both single quotes and theCONVERTfunction:WHERE order_date = CONVERT(date, '2023-04-05'). - Filter for dates before or after a given day. To get orders placed before a date, use
<:SELECT * FROM orders WHERE order_date < '2023-04-05';
For dates on or after, use>=:SELECT * FROM orders WHERE order_date >= '2023-04-05';
Be precise:>excludes the target date, while>=includes it. - Use
BETWEENfor a date range. To capture records within a start and end date (inclusive), write:SELECT * FROM orders WHERE order_date BETWEEN '2023-04-01' AND '2023-04-30';
This returns all rows from April 1 through April 30, 2023. For datetime columns, ensure the end date includes the full final day—e.g., use'2023-04-30 23:59:59'or'2023-05-01'with<to avoid missing late-night entries. - Handle time zones and time components. If your column stores timestamps (e.g.,
2023-04-05 14:30:00), a simple equality like= '2023-04-05'may fail because it compares against2023-04-05 00:00:00. Instead, use a range:SELECT * FROM logs WHERE log_timestamp >= '2023-04-05' AND log_timestamp < '2023-04-06';
This safely captures all moments on April 5, regardless of time. - Use database-specific date functions for relative dates. To filter for “today,” “last 7 days,” or “this month,” use built-in functions:
- MySQL:
WHERE order_date = CURDATE()orWHERE order_date >= DATE_SUB(NOW(), INTERVAL 7 DAY) - PostgreSQL:
WHERE order_date = CURRENT_DATEorWHERE order_date >= CURRENT_DATE - INTERVAL '7 days' - SQL Server:
WHERE CAST(order_date AS DATE) = CAST(GETDATE() AS DATE)orWHERE order_date >= DATEADD(DAY, -7, GETDATE())
DATE(in SQL Server and PostgreSQL) removes the time portion, simplifying same-day matches. - MySQL:
Common Mistakes
- Using string formatting that mismatches the database. For example, entering
'04-05-2023'in MySQL may be interpreted as April 5, but in SQL Server with certain settings, it could become May 4. Always useYYYY-MM-DDfor unambiguous results. - Ignoring time components in datetime columns. Comparing
= '2023-04-05'against aDATETIMEcolumn only matches rows with exactly00:00:00time—often zero rows. Use a half-open range (>= start AND < end) instead. - Assuming
BETWEENis safe for datetime.BETWEEN '2023-04-30' AND '2023-04-30'only matches midnight on April 30. To include the entire day, use< '2023-05-01'as the upper bound. - Filtering on non-date columns. If a date is stored as text (e.g.,
'2023-04-05'in aVARCHAR), lexicographic sorting may work forYYYY-MM-DD, but it’s fragile. Convert the column to a proper date type for reliability. - Forgetting locale settings. Some systems interpret
'2023/04/05'based on regional settings. Stick to ISO 8601 (YYYY-MM-DD) to avoid ambiguity.
Tips
- Index your date columns. Adding an index (e.g.,
CREATE INDEX idx_orders_date ON orders(order_date);) dramatically speeds upWHEREqueries on large tables. - Prefer
<over<=for upper bounds. Using>= '2023-04-01' AND < '2023-05-01'is safer and clearer thanBETWEENfor datetime ranges. - Test with a small dataset first. Run
SELECT COUNT(*)with yourWHEREclause to verify the expected number of rows before selecting all columns. - Use
CASTorCONVERTonly when necessary. Casting in theWHEREclause (e.g.,CAST(order_date AS DATE)) can prevent index usage. If possible, adjust the literal instead. - Store dates in UTC. When building new systems, keep timestamps in UTC and convert to local time in the application layer to avoid daylight saving surprises.
Troubleshooting
If your query returns no results or incorrect rows, follow these checks:
- Verify the date format. Run
SELECT order_date FROM orders LIMIT 1;to see the actual stored format. Compare it to yourWHEREliteral—mismatched formats (e.g.,DD/MM/YYYYvs.YYYY-MM-DD) cause silent failures. - Check for trailing spaces or time parts. If the column is
VARCHAR, useTRIM()orDATE()functions to clean it. ForDATETIME, confirm whether your comparison includes time. - Confirm column type. Run
DESCRIBE table_name;orSELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'table_name';(PostgreSQL:SELECT column_name, data_type FROM information_schema.columns ...). If the type isTEXT, convert the column:ALTER TABLE orders ALTER COLUMN order_date TYPE DATE USING order_date::DATE;(PostgreSQL syntax). - Test with a known row. Insert a test row with a simple date (e.g.,
INSERT INTO orders (order_date) VALUES ('2023-04-05');), then re-run yourWHEREclause to see if it appears. - Check database-specific quirks. In Oracle, use
TO_DATE('2023-04-05', 'YYYY-MM-DD'). In SQLite, dates are stored as strings, so ensure consistent formatting and avoid arithmetic that changes the string representation.
Frequently Asked Questions
Can I use NOW() directly in a WHERE clause?
Yes—but only for relative comparisons. For example: WHERE created_at < NOW() - INTERVAL '1 day' (PostgreSQL) or WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 DAY) (MySQL). Never use = NOW() expecting exact matches, as timestamps include microseconds.
Why does my BETWEEN query miss records on the last day?
Because BETWEEN '2023-04-30' only matches rows where the time is exactly 00:00:00. For full-day coverage, use WHERE date_col >= '2023-04-01' AND date_col < '2023-05-01'.
How do I get all records from the current month?
Use:
MySQL: WHERE order_date >= DATE_FORMAT(NOW(), '%Y-%m-01') AND order_date < DATE_FORMAT(NOW() + INTERVAL 1 MONTH, '%Y-%m-01')
PostgreSQL: WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE) AND order_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month'
Can I filter by day of the week (e.g., all Fridays)?
Yes. Use DAYOFWEEK() (MySQL), EXTRACT(DOW FROM date_col) (PostgreSQL), or DATEPART(WEEKDAY, date_col) (SQL Server). Example for Friday: MySQL WHERE DAYOFWEEK(order_date) = 6; (where Sunday=1, Monday=2, …, Saturday=7).
Is STR_TO_DATE() safe for converting text columns?
Only as a temporary fix. Using STR_TO_DATE() in queries prevents index usage and slows large tables. The correct fix is altering the column type: ALTER TABLE table MODIFY column_name DATE; after verifying data integrity.
Do time zones affect date comparisons?
Yes—if your data is stored in local time but you query in UTC (or vice versa). Always store timestamps in UTC and convert at the application level. If comparisons must be local, ensure both the stored data and your query use the same time zone context.