SQLAI.ai

SELECT c.customer_id, c.first_name, c.last_name FROM customer c INNER JOIN rental r ON c.customer_id = r.customer_id WHERE r.rental_date < (CURRENT_DATE - INTERVAL '12 months') AND ( r.return_date IS NULL OR r.return_date > (CURRENT_DATE - INTERVAL '12 months') ) AND c.customer_id NOT IN ( SELECT customer_id FROM rental WHERE rental_date >= (CURRENT_DATE - INTERVAL '12 months') ) GROUP BY c.customer_id;

  1. Understanding the SQL statement:

The given SQL statement is trying to fetch the customer_id, first_name, and last_name of customers who have rented a movie more than 12 months ago and haven't rented any movie in the last 12 months. The rental table is joined with the customer table using an INNER JOIN, and the result is filtered based on the rental_date and return_date conditions. The result is then grouped by the customer_id.

  1. Suggesting optimization for PostgreSQL:

To optimize the SQL statement for PostgreSQL we can use the following approaches:

  • Use a Common Table Expression (CTE) to fetch the filtered rental data before joining it with the customer table.
  • Remove the GROUP BY clause and use DISTINCT instead to eliminate duplicate customer records.
  1. Writing a better SQL statement:

Here's the optimized SQL statement for PostgreSQL:

            
WITH filtered_rentals AS ( SELECT customer_id FROM rental WHERE rental_date < (CURRENT_DATE - INTERVAL '12 months') AND ( return_date IS NULL OR return_date > (CURRENT_DATE - INTERVAL '12 months') ) EXCEPT SELECT customer_id FROM rental WHERE rental_date >= (CURRENT_DATE - INTERVAL '12 months') ) SELECT DISTINCT c.customer_id, c.first_name, c.last_name FROM customer c INNER JOIN filtered_rentals fr ON c.customer_id = fr.customer_id;

In this optimized SQL statement we use a CTE named filtered_rentals to fetch the filtered rental data before joining it with the customer table. We also use the EXCEPT clause to exclude customers who have rented a movie in the last 12 months. Finally, instead of using GROUP BY, we use DISTINCT to eliminate duplicate customer records.

  • Public
  • ·
  • Tue, 11 Apr 2023 09:37:37 GMT