Home > Database > Mysql Tutorial > How to Retrieve Rows with Timestamps from Today Only in SQL?

How to Retrieve Rows with Timestamps from Today Only in SQL?

Susan Sarandon
Release: 2024-12-03 05:01:13
Original
493 people have browsed it

How to Retrieve Rows with Timestamps from Today Only in SQL?

How to Select Rows with Timestamps from Today Only

In a relational database, selecting rows with specific timestamps can be essential for data analysis and reporting. A common scenario is to retrieve records from the current day, excluding any time component.

The Current Approach and Its Limitation

The provided query, SELECT * FROM table WHERE (timestamp > DATE_SUB(now(), INTERVAL 1 DAY));, retrieves results within the last 24 hours. This is because it subtracts one day from the current time using DATE_SUB, which includes all timestamps from the previous day.

Using DATE and CURDATE() for Precision

To select results based solely on the date, ignoring the time component, the following query can be used:

SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE();
Copy after login

Here, DATE() extracts only the date portion of the timestamp, and CURDATE() returns the current date. By comparing these values, the query effectively filters out timestamps that are not from today.

Efficient Index Usage

It's important to note that the above query may not utilize indexes efficiently. Consider using this alternative query instead:

SELECT * FROM `table` WHERE `timestamp` >= DATE(NOW()) AND `timestamp` < DATE(NOW()) + INTERVAL 1 DAY;
Copy after login

This query utilizes an index on the timestamp column, which is a common optimization technique in SQL.

The above is the detailed content of How to Retrieve Rows with Timestamps from Today Only in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template