SQL

Select Customers Who Have Placed Orders in the Last 30 Days

Use a SQL subquery with EXISTS to efficiently filter and retrieve a list of customers who have made at least one purchase within the last month, optimizing for performance.

SELECT
    c.customer_id,
    c.first_name,
    c.last_name,
    c.email
FROM
    customers c
WHERE EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.customer_id = c.customer_id
      AND o.order_date >= CURRENT_DATE - INTERVAL '30 days' -- PostgreSQL/SQL Server. For MySQL: DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
);
How it works: This query uses a correlated subquery with the EXISTS clause to identify customers who have placed an order in the last 30 days. For each customer in the `customers` table, the subquery checks if there's at least one corresponding order in the `orders` table that meets the date criterion. This is an efficient way to filter records based on the existence of related data without aggregating all related rows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs