Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alternative to using WHERE as a subquery

Tags:

sql

postgresql

I'm learning SQL using PostgreSQL, and I'm trying to modify one of the queries from the PostgreSQL Tutorial website.

The original query is this:

SELECT film_id, title
FROM film
WHERE film_id IN (
    SELECT inventory.film_id
    FROM rental
    INNER JOIN inventory ON inventory.inventory_id = rental.inventory_id
    WHERE return_date BETWEEN '2005-05-29' AND '2005-05-30'
);

This works, however I want to include rental.return_date in my output. I was able to achieve this using the following modifications, but it is terribly slow (takes 46096ms instead of 40ms):

SELECT film_id, title, return_date
FROM film, rental
WHERE film_id IN (
   SELECT inventory.film_id
   FROM rental
   INNER JOIN inventory ON inventory.inventory_id = rental.inventory_id
   WHERE return_date BETWEEN '2005-05-29' AND '2005-05-30'
)
ORDER BY return_date;

I poked around this site and I suspect that I need to change the WHERE clause to an INNER JOIN, but my attempts have all failed thus far. Is there a simple way to speed up this query?

like image 623
Automatic Bazooty Avatar asked May 16 '26 05:05

Automatic Bazooty


1 Answers

You shouldn't need a subquery at all.

Just join the tables in what appears the only logical way to join the tables at all, and then borrow the where clause from the previous subquery to use as the where clause for your query.

SELECT film.film_id, film.title, rental.return_date
FROM film
    INNER JOIN inventory ON inventory.film_id = film.film_id
    INNER JOIN rental ON rental.inventory_id = inventory.inventory_id
WHERE rental.return_date BETWEEN '2005-05-29' AND '2005-05-30'
ORDER BY rental.return_date
like image 161
nhgrif Avatar answered May 18 '26 18:05

nhgrif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!