Friday, April 22, 2016

SQL: exclude records of a subquery from SELECT resultset; NOT EXISTS, NOT IN, and MINUS - resolved

Lets say you have the following two tables in your database.

FRUIT
fruitId            name            price

1                    Apple           1.89
2                   Orange          0.98
3                   Pear               1.25
4                   Banana          1.23
. . . . . .

SALE
itemId          charge          employeeId        Date
1                   55.50           34                       2016-03-03

. . . . . .

You want to see which fruits have not had any business in the last 30 days. All the SQLs below shall work.

(* Current date: Oracle is SYSDATE, PostgreSQL CURRENT_DATE or NOW(), MySQL CURRENT_DATE or NOW())

1. SELECT name FROM FRUIT f WHERE NOT EXISTS (SELECT * FROM SALE s  WHERE f.fruitId = s.itemId and s.Date > (SYSDATE - 30));

2. SELECT name FROM FRUIT f WHERE f.fruitId not in (SELECT s.itemId FROM SALE s WHERE s.Date > (SYSDATE - 30));

3, SELECT name FROM FRUIT
    MINUS
    SELECT name FROM FRUIT f INNER JOIN SALE s ON s.itemId = f.fruitId and s.Date > (SYSDATE - 30);

Among these, 2 is the least effective.

---------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment