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 film more than 12 months ago, and either have not returned it yet or returned it the last 12 months. Additionally, these customers should not have any rentals in the last 12 months.

  1. Suggesting optimization for PostgreSQL:

To optimize the SQL statement for PostgreSQL, we can do the following:

  • Use EXTRACT(YEAR FROM age(CURRENT_DATE, r.rental_date)) >= 1 instead of using INTERVAL.
  • Instead of using NOT IN, use a LEFT JOIN with a condition on the joined table being NULL.
  1. Writing a better SQL statement:

Here's the optimized SQL statement for PostgreSQL:

            
SELECT c.customer_id, c.first_name, c.last_name FROM customer c INNER JOIN rental r ON c.customer_id = r.customer_id LEFT JOIN rental recent_rental ON c.customer_id = recent_rental.customer_id AND EXTRACT(YEAR FROM age(CURRENT_DATE, recent_rental.rental_date)) < 1 WHERE EXTRACT(YEAR FROM age(CURRENT_DATE, r.rental_date)) >= 1 AND (r.return IS NULL OR EXTRACT(YEAR FROM age(CURRENT_DATE, r.return_date)) < 1) AND recent_rental.customer_id IS NULL GROUP BY c.customer_id;

This optimized SQL statement should perform better in PostgreSQL while providing the same result as the original statement.

  • Public
  • ·
  • Tue, 11 Apr 2023 09:35:12 GMT