Explain Codes LogoExplain Codes Logo

Mysql Select last 7 days

sql
date-time
interval
database-functions
Nikita BarsukovbyNikita Barsukov·Oct 24, 2024
TLDR

Extract the past 7 days' data using CURDATE() - INTERVAL 7 DAY within the WHERE clause:

SELECT * FROM your_table WHERE date_column >= CURDATE() - INTERVAL 7 DAY;

This statement scans the your_table records where the date_column falls within the previous week. It's essential to verify date_column being a DATE/DATETIME type.

Time-sensitive selections

For DATETIME or TIMESTAMP columns, factor in the time component. Here's how:

SELECT * FROM your_table WHERE date_time_column >= CURDATE() - INTERVAL 7 DAY AND date_time_column < CURDATE() + INTERVAL 1 DAY;

This ensures records up to the current time are considered, not just those up to the start of the day.

Time Zone Trek

In case of multiple time zones, the CONVERT_TZ function adjusts the returned data to match the correct time zone for a coherent date range.

Data Precision & Storage

Retain date-associated data in DATE, DATETIME or TIMESTAMP types for an accurate reference point and optimal usage of database functions.

Choosing the Right Temporal Type

Discern the differences between DATE, DATETIME, and TIMESTAMP:

  • DATE is for date-only comparisons.
  • DATETIME or TIMESTAMP seeks precision including hours, minutes, and seconds.

DATE_ADD vs. INTERVAL: A Syntax Showdown

Subtly modify dates with DATE_ADD and DATE_SUB, counterparts to + INTERVAL or - INTERVAL:

SELECT * FROM your_table WHERE date_column >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);

Ideal for more intricate date operations beyond the purview of the INTERVAL syntax.

Trial and Error: Testing date expressions

Test the validity of your date expressions:

SELECT CURDATE() - INTERVAL 7 DAY;

Verify the output before incorporating it into the more complex WHERE clause.

JOINING the Party

Filter data post JOIN to avoid processing redundant information:

SELECT e.* FROM events e INNER JOIN users u ON e.user_id = u.id WHERE e.event_date >= CURDATE() - INTERVAL 7 DAY;

Striking a balance is critical - reasonable use of joins maintains optimal performance.