How can MySQL return all rows that are less than a certain date?

How to Retrieve Rows with Dates Before a Specified Date in MySQL

Efficiently querying data based on temporal criteria is a fundamental requirement in database management. When working with MySQL, retrieving records that occurred prior to a specific cutoff date is a common task. This filtering is achieved primarily through the use of the SELECT statement combined with the powerful WHERE clause.

The core mechanism involves setting a condition that mandates a comparison between the date stored in a specified column and the target date provided in the query. By utilizing the “less than” comparison operator (<), the database engine rigorously checks every row against this temporal threshold. This ensures that only data entries with a date value strictly earlier than the defined benchmark are included in the final result set, effectively excluding any records that fall on or after that particular date.

Mastering this technique allows developers and analysts to perform precise historical data analysis, generate accurate reports, and manage time-sensitive information within their relational databases. Understanding the proper syntax for date handling in SQL is crucial for avoiding common errors related to data type conversion and formatting issues, guaranteeing accurate query execution.


Implementing the Basic Date Comparison Syntax

To successfully filter records in MySQL based on a date being earlier than a given value, you must structure your query using standard SQL conventions. The query must specify which columns to retrieve, the source table, and the filtering condition enforced by the WHERE clause. The fundamental syntax is designed to be clear and efficient, targeting the specific date column for temporal evaluation.

The following structure illustrates the basic command needed to return all rows in a table where a date column is strictly less than a specific, predefined date. Note the strict requirement for the date literal format ('YYYY-MM-DD') when performing the comparison, ensuring that the database engine handles the temporal comparison correctly.

SELECT *
FROM sales
WHERE sales_date < '2020-01-01';

In this particular example, we instruct MySQL to utilize the SELECT statement to retrieve all columns (indicated by *) from the table named sales. The crucial filtering occurs in the WHERE clause, where we specify that the value in the sales_date column must be temporally less than, or earlier than, the date January 1st, 2020. Any records matching this condition will be included in the resulting dataset, while sales occurring on 2020-01-01 or later are discarded.

The following comprehensive example demonstrates this syntax in action, guiding you through the creation of a sample dataset and the subsequent execution of the date-filtering query.

Demonstration: Returning Rows Earlier Than a Specified Date in MySQL

To fully grasp how date filtering works, let us establish a practical scenario involving sales data. We will create a sample table designed to track transaction details, including a unique identifier, the item sold, and a precise timestamp for when the sale occurred. This setup ensures we have realistic data to test our temporal filtering conditions using the less than comparison operator.

Imagine we are managing a database for various grocery store sales. We require a table named sales that includes essential columns such as store_ID, item, and the critical time-based column, sales_date, which uses the DATETIME data type to store both date and time information. The structure is defined as follows, along with five distinct data entries spanning several years to provide diverse test cases.

The following SQL commands illustrate the creation of the sales table and the insertion of sample rows, preparing our environment for the filtering operation:

-- create table 
CREATE TABLE sales (
  store_ID INT PRIMARY KEY,
  item TEXT NOT NULL,
  sales_date DATETIME NOT NULL
);

-- insert rows into table
INSERT INTO sales VALUES (0001, 'Oranges', '2015-01-12 03:45:00');
INSERT INTO sales VALUES (0002, 'Apples', '2020-11-25 15:25:01');
INSERT INTO sales VALUES (0003, 'Bananas', '2009-06-30 09:01:39');
INSERT INTO sales VALUES (0004, 'Melons', '2022-04-09 03:29:55');
INSERT INTO sales VALUES (0005, 'Grapes', '2023-05-19 23:10:04');

-- view all rows in table
SELECT * FROM sales;

After executing the setup commands, we can view the entire contents of our newly populated sales table. This unfiltered view represents the complete dataset before we apply any temporal restrictions. Observing this raw output helps confirm that the data has been inserted correctly and provides a baseline against which we can compare the filtered results.

The resulting table structure and data points are clearly displayed below, showing the various years and times associated with each transaction:

Output:
+----------+---------+---------------------+
| store_ID | item    | sales_date          |
+----------+---------+---------------------+
|        1 | Oranges | 2015-01-12 03:45:00 |
|        2 | Apples  | 2020-11-25 15:25:01 |
|        3 | Bananas | 2009-06-30 09:01:39 |
|        4 | Melons  | 2022-04-09 03:29:55 |
|        5 | Grapes  | 2023-05-19 23:10:04 |
+----------+---------+---------------------+

Applying the Temporal Filter Condition

Our objective is now to isolate only those sales records that were logged before a specific date, which we define as January 1st, 2020. This process requires modifying the standard SELECT statement by integrating the restrictive WHERE clause and the appropriate temporal comparison operator.

When using the less than operator (<) against a date column containing DATETIME values, MySQL performs a chronological comparison. It checks if the timestamp recorded in sales_date occurred before the midnight of the specified cutoff date (2020-01-01 00:00:00). Any record matching this criterion will pass the filter and be returned to the user, providing a clean historical snapshot.

The syntax below executes this precise filtering operation, targeting the sales_date column:

SELECT *
FROM sales
WHERE sales_date < '2020-01-01';

Interpreting the Filtered Results

Upon execution of the query, MySQL processes the condition defined in the WHERE clause against every row in the sales table. Rows 2, 4, and 5 (Apples, Melons, and Grapes) have sales dates in 2020, 2022, and 2023, respectively, which are chronologically greater than the cutoff date of 2020-01-01. Consequently, these rows are systematically excluded from the result set.

The resulting output clearly shows only the records where the sales_date is strictly prior to January 1st, 2020. Specifically, the sales for Oranges (2015) and Bananas (2009) meet the less than condition, confirming the accuracy of the temporal filter applied to the dataset. This focused result set is essential for reporting on past periods or analyzing legacy transactions.

The filtered output is presented below, confirming that only the qualifying historical records remain:

Output:
+----------+---------+---------------------+
| store_ID | item    | sales_date          |
+----------+---------+---------------------+
|        1 | Oranges | 2015-01-12 03:45:00 |
|        3 | Bananas | 2009-06-30 09:01:39 |
+----------+---------+---------------------+

It is important to notice that every row returned in this subset possesses a date in the sales_date column that is chronologically less than (earlier than) the stipulated boundary of 2020-01-01. This validation confirms that the less than comparison operator performed its intended function precisely.

Enhancing Readability: Ordering Filtered Results

While filtering successfully reduces the dataset to the required historical records, the order in which these records are displayed might not be intuitive. By default, the output order is often dictated by the physical storage mechanism or the primary key, which may not align with chronological sequence. For reports or analysis where time progression is critical, incorporating sorting is necessary.

To present the data in a logical time series—for instance, from the oldest sales transaction to the most recent qualifying transaction—we append the ORDER BY clause to our existing SELECT statement. Ordering by the sales_date column in ascending order (which is the default behavior if ASC is omitted) ensures that the results are displayed chronologically, improving data interpretation.

This combined approach first filters the data using the temporal condition and then structures the reduced dataset based on the date field. This two-step process—filter then sort—is common practice for producing readable, useful database outputs.

SELECT *
FROM sales
WHERE sales_date < '2020-01-01'
ORDER BY sales_date;

By applying the ORDER BY sales_date clause, the records are reorganized to show the oldest sale first (Bananas, 2009) followed by the next oldest (Oranges, 2015), providing a chronological progression of sales that occurred before the cutoff date.

+----------+---------+---------------------+
| store_ID | item    | sales_date          |
+----------+---------+---------------------+
|        3 | Bananas | 2009-06-30 09:01:39 |
|        1 | Oranges | 2015-01-12 03:45:00 |
+----------+---------+---------------------+

Crucial Considerations for Date Querying

Working with dates in MySQL requires careful attention to data types and formatting standards to ensure reliable query execution. If the database engine cannot correctly interpret the date literal provided in the WHERE clause, the query may fail, or, worse, return incorrect results without an explicit error, leading to data integrity issues.

The most important rule when comparing dates in MySQL is the adherence to the standard DATETIME format, which is defined as ‘YYYY-MM-DD HH:MM:SS’, or simply ‘YYYY-MM-DD’ if time components are omitted. When only the date is provided (as in '2020-01-01'), MySQL implicitly treats the time component as midnight (00:00:00) of that day during comparison.

If you were to use alternative date formats, such as MM/DD/YYYY or DD-MM-YYYY, MySQL might fail to parse the string correctly, resulting in an error or converting the date literal into an unexpected format, thereby corrupting the comparison. Always confirm that your application or query adheres strictly to the ISO 8601 standard representation for dates when communicating with the database engine.

Note: When querying with dates in MySQL, you must use a YYYY-MM-DD format or a full YYYY-MM-DD HH:MM:SS format, otherwise you may receive an error or inaccurate filtering results.

Summary of Date Filtering Techniques

Filtering database records based on historical temporal conditions is a foundational skill in data manipulation. By effectively combining the SELECT statement, the WHERE clause, and the less than (<) comparison operator, developers can precisely retrieve all data points that precede a specific moment in time.

This technique is vital for applications requiring audit trails, historical reporting, or time-based data segmentation. Remember to always use the correct DATETIME format and consider using the ORDER BY clause to ensure the resulting data set is not only accurate but also chronologically logical and easy to analyze.

For those looking to expand their knowledge of temporal querying in MySQL, the following tutorials explain how to perform other common tasks involving date ranges and comparisons:

MySQL: How to Return All Rows Between Two Dates

Cite this article

mohammed looti (2026). How to Retrieve Rows with Dates Before a Specified Date in MySQL. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-mysql-return-all-rows-that-are-less-than-a-certain-date/

mohammed looti. "How to Retrieve Rows with Dates Before a Specified Date in MySQL." PSYCHOLOGICAL SCALES, 5 Jan. 2026, https://scales.arabpsychology.com/stats/how-can-mysql-return-all-rows-that-are-less-than-a-certain-date/.

mohammed looti. "How to Retrieve Rows with Dates Before a Specified Date in MySQL." PSYCHOLOGICAL SCALES, 2026. https://scales.arabpsychology.com/stats/how-can-mysql-return-all-rows-that-are-less-than-a-certain-date/.

mohammed looti (2026) 'How to Retrieve Rows with Dates Before a Specified Date in MySQL', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-mysql-return-all-rows-that-are-less-than-a-certain-date/.

[1] mohammed looti, "How to Retrieve Rows with Dates Before a Specified Date in MySQL," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, January, 2026.

mohammed looti. How to Retrieve Rows with Dates Before a Specified Date in MySQL. PSYCHOLOGICAL SCALES. 2026;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top