Skip to content
Advertisement

How to use WHERE EXISTS in a SQL subquery?

I need to find the distinct drinkers who have ordered drinks at a pub on VICTORIA AVE. in March 2020.

Here are the tables I am trying to retrieve data from:

CREATE TABLE ORDERS(    /* Drinkers visit pubs and consumes drinks */
DRINKER     VARCHAR(30) NOT NULL,   /* Drinker name */
PUB         VARCHAR(30) NOT NULL,   /* Pub name */
ODATE       DATE        NOT NULL,   /* Order date   */
DRINK       VARCHAR(30) NOT NULL,   /* Drink name   */
DRINK_NO    DECIMAL(2)  NOT NULL,   /* A sequence number of a drink */
    CONSTRAINT ORDERS_PKEY PRIMARY KEY(DRINKER, PUB, ODATE, DRINK, DRINK_NO),
    CONSTRAINT ORDERS_FKEY1 FOREIGN KEY(PUB, DRINK) REFERENCES SERVES(PUB, DRINK),
    CONSTRAINT ORDERS_FKEY2 FOREIGN KEY(DRINKER) REFERENCES DRINKERS(DRINKER)   );

CREATE TABLE LOCATED(   /* Pubs have locations */
PUB         VARCHAR(30) NOT NULL,   /* Pub name */
STREET      VARCHAR(30) NOT NULL,   /* Street name  */
BLDG_NO     DECIMAL(4)  NOT NULL,   /* Building number  */
    CONSTRAINT LOCATED_PKEY PRIMARY KEY(PUB) );

Here is my SELECT statement so far:

SELECT DISTINCT DRINKER 
FROM ORDERS 
WHERE EXISTS (SELECT PUB 
              FROM LOCATED
              WHERE STREET = 'VICTORIA AVE.' 
              AND ORDERS.ODATE >= STR_TO_DATE('01-MAR-2020','%d-%M-%Y')
              AND ORDERS.ODATE <= STR_TO_DATE('01-MAR-2020','%d-%M-%Y'));

Advertisement

Answer

The subquery needs to be correlated to the main query in its WHERE clause.

SELECT DISTINCT DRINKER 
FROM ORDERS 
WHERE EXISTS (SELECT PUB 
              FROM LOCATED
              WHERE LOCATED.PUB = ORDERS.PUB
              AND STREET = 'VICTORIA AVE.' 
              AND ORDERS.ODATE >= STR_TO_DATE('01-MAR-2020','%d-%M-%Y')
              AND ORDERS.ODATE <= STR_TO_DATE('31-MAR-2020','%d-%M-%Y'));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement