SQL / MySQL Beginner Queries · 7 min read

MySQL Date Functions

Lesson 23 of 33 in the SQL / MySQL learning path.

How do I filter rows from the last seven days?

"Last seven days" is a range on the datetime column, not a function wrapped around that column. The start is included and the end is excluded, so the window is exactly seven days long. DATE_SUB builds the start from a known instant, and DATE, DATE_FORMAT, and DATEDIFF describe the rows that fall inside it.

The examples use a fixed instant, @as_of, so the result does not change every time you run the file. The same shape with CURRENT_TIMESTAMP answers "the last seven days from now." Compare the column with the range so an index on created_at can still be used. PHP can compute the same two bounds with DateTimeImmutable and bind them.

Syntax & Parameters

Syntax
WHERE created_at >= DATE_SUB(@as_of, INTERVAL 7 DAY)
  AND created_at < @as_of

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE lessons (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(160) NOT NULL,
  track VARCHAR(80) NOT NULL,
  published_at DATETIME NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE enrollments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  lesson_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  status VARCHAR(20) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
  CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
  CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, created_at) VALUES
  ('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
  ('Grace Hopper', 'grace@school.test', '2026-03-13 15:00:00'),
  ('Alan Turing', 'alan@school.test', '2026-03-18 08:30:00'),
  ('Katherine Johnson', 'katherine@school.test', '2026-03-20 14:59:59'),
  ('Sam Rivera', 'sam@school.test', '2026-03-20 15:00:00');

INSERT INTO lessons (title, track, published_at) VALUES
  ('Algebra I', 'math', '2026-03-18 09:00:00'),
  ('SQL Basics', 'data', '2026-03-01 09:00:00'),
  ('Studio Draft', 'art', NULL);

INSERT INTO enrollments (lesson_id, user_id, status) VALUES
  (1, 2, 'confirmed');

SET @as_of = '2026-03-20 15:00:00';

SELECT
  id,
  name,
  email,
  created_at,
  DATE(created_at) AS created_on,
  DATE_FORMAT(created_at, '%Y-%m-%d') AS created_label,
  DATEDIFF(DATE(@as_of), DATE(created_at)) AS days_before
FROM users
WHERE created_at >= DATE_SUB(@as_of, INTERVAL 7 DAY)
  AND created_at < @as_of
ORDER BY created_at, id
LIMIT 20;

SELECT id, title, published_at
FROM lessons
WHERE published_at >= DATE_SUB(@as_of, INTERVAL 7 DAY)
  AND published_at < @as_of
ORDER BY published_at, id
LIMIT 20;

SELECT id, name, created_at
FROM users
WHERE created_at >= CURRENT_TIMESTAMP - INTERVAL 7 DAY
  AND created_at < CURRENT_TIMESTAMP
ORDER BY created_at, id
LIMIT 20;

Expected Output

id | name              | email                 | created_at          | created_on | created_label | days_before
2  | Grace Hopper      | grace@school.test     | 2026-03-13 15:00:00 | 2026-03-13 | 2026-03-13    | 7
3  | Alan Turing       | alan@school.test      | 2026-03-18 08:30:00 | 2026-03-18 | 2026-03-18    | 2
4  | Katherine Johnson | katherine@school.test | 2026-03-20 14:59:59 | 2026-03-20 | 2026-03-20    | 0
3 rows in set

id | title     | published_at
1  | Algebra I | 2026-03-18 09:00:00
1 row in set

The CURRENT_TIMESTAMP query follows the server clock. The March 2026 seed rows are outside that live window when you run the file months later.

Line-by-Line Walkthrough

  1. @as_of is the fixed end of the demo window, 2026-03-20 15:00:00. DATE_SUB of that instant by INTERVAL 7 DAY is 2026-03-13 15:00:00.
  2. The users filter keeps created_at greater than or equal to the start and strictly less than @as_of. That is seven days of time.
  3. Grace equals the start, so she is included. Alan is in the middle. Katherine is one second before the end, so she is included.
  4. Ada registered on 1 March, before the start. Sam equals @as_of, so the strict upper bound leaves him out.
  5. DATE and DATE_FORMAT appear in the SELECT list, where they format a value. They are not wrapped around created_at in the WHERE clause.
  6. DATEDIFF compares dates only. Grace is 7 days before 20 March, Alan is 2, and Katherine is 0 even though her timestamp is inside the window.
  7. The lessons query uses the same bounds on published_at. Algebra I qualifies. SQL Basics is too old. Studio Draft is NULL and fails the comparison.
  8. The last query is the live form: CURRENT_TIMESTAMP minus INTERVAL 7 DAY, up to but not including the current timestamp. Those March seed rows fall outside it when the server clock is much later.
  9. DATETIME literals in this table have no time zone. Bind the two bounds from PHP with DateTimeImmutable when the application owns the clock, and still compare the bare column.

Common Pitfalls & Security

Date filters fail quietly when the end boundary is inclusive by accident or when a function hides the column. A seven-day window that uses created_at <= @as_of also keeps Sam, whose timestamp is the endpoint, and the range is then a hair longer than seven days.

  • WHERE DATE(created_at) = some date applies the function to every row and blocks an index on created_at. Compare the column with a start and an end instead.
  • DATEDIFF ignores the clock time. Katherine has days_before 0 and is still inside the timestamp window. Do not use DATEDIFF alone to decide membership.
  • NULL published_at does not match a range. A draft stays out, which is what you want, and it will not appear as zero either.
  • CURRENT_TIMESTAMP uses the session time zone. A DATETIME column does not. Mixing a UTC session with values stored as local wall time shifts the window.
  • Building the SQL text by concatenating a date string is unnecessary. Bind the two bounds, or compute them in SQL from CURRENT_TIMESTAMP.

Best Practices & Modern Standards

Write a last-seven-days filter as column >= start AND column < end. Compute start with DATE_SUB(end, INTERVAL 7 DAY) or with end - INTERVAL 7 DAY. Both mean the same thing. Put DATE, DATE_FORMAT, and DATEDIFF in the SELECT list when you need a label or a day count.

Use a fixed end instant in examples and tests so the rows stay put. Use CURRENT_TIMESTAMP in the live query, or bind two instants produced by DateTimeImmutable in PHP. Add ORDER BY created_at, id when the list must be stable, and LIMIT it when the screen only shows a page.

Real-World Use

On Monday the registrar asks who created an account in the last seven days and which lessons were published in that same stretch. The query compares created_at and published_at with a start instant and an excluded end instant. Grace, Alan, and Katherine are inside the sample window, and Algebra I is the lesson published in that stretch.

Frequently Asked Questions

Why is the end of the window excluded?

created_at < @as_of keeps the span at exactly seven days. Sam is stored at the end instant, so he stays outside. Grace is stored at the start, and >= includes her.

What instant does DATE_SUB produce here?

DATE_SUB of 2026-03-20 15:00:00 by INTERVAL 7 DAY is 2026-03-13 15:00:00. The time of day stays 15:00:00.

Why is Katherine included when DATEDIFF returns 0?

DATEDIFF compares calendar dates and ignores the time. Her timestamp is still earlier than @as_of, so the range keeps her.

How do I ask for the last seven days from now?

Compare the column with CURRENT_TIMESTAMP - INTERVAL 7 DAY and CURRENT_TIMESTAMP, using >= for the start and < for the end. The rows move forward as the clock moves.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…