Forgly

SQL to get rows from the last 30 days

Filter rows whose timestamp falls within the last 30 days.

PostgreSQL
SELECT *
FROM orders
WHERE created_at >= NOW() - INTERVAL '30 days';
MySQL
SELECT *
FROM orders
WHERE created_at >= NOW() - INTERVAL 30 DAY;
SQL Server
SELECT *
FROM orders
WHERE created_at >= DATEADD(DAY, -30, GETDATE());
SQLite
SELECT *
FROM orders
WHERE created_at >= datetime('now', '-30 days');

How to select rows from the last 30 days

Compare the timestamp column against 'now minus 30 days'. The interval syntax differs by dialect.

How it works

  • Each query computes a cutoff timestamp 30 days before the current time.
  • Keeping created_at >= cutoff returns everything from the cutoff up to now.
  • Comparing the raw column (not a function of it) lets the database use an index on created_at.

Tip

Avoid wrapping the column in a function (e.g. DATE(created_at)) in the WHERE clause — it usually disables the index.

Related SQL queries

Frequently asked questions

How do I select rows from the last 30 days in SQL?

Compare the timestamp column against 'now minus 30 days'. The interval syntax differs by dialect. Each query computes a cutoff timestamp 30 days before the current time. Keeping created_at >= cutoff returns everything from the cutoff up to now. Comparing the raw column (not a function of it) lets the database use an index on created_at.

Does this work in PostgreSQL, MySQL, SQL Server, and SQLite?

Yes — this page lists the query for each dialect, since the syntax can differ between database engines.

Can I generate this query for my own tables?

Yes. Describe what you want in plain English with Forgly's free AI SQL Generator and it writes the query for your dialect.