SQL

Select Data for Last N Days with SQL Date Functions

Discover how to query data within a specific date range, like the last 30 days, using common SQL date manipulation functions for recent activity reports.

SELECT
  order_id,
  customer_id,
  order_date,
  total_amount
FROM
  Orders
WHERE
  order_date >= DATE('now', '-30 days');
How it works: This snippet retrieves all orders placed within the last 30 days. It utilizes the `DATE('now', '-30 days')` function (common in SQLite and PostgreSQL, with similar functions available in MySQL like `CURDATE() - INTERVAL 30 DAY` or MS SQL Server `DATEADD(day, -30, GETDATE())`) to calculate the date 30 days prior to the current date. This is a highly practical technique for generating recent activity reports or populating dashboards with timely information.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs