Skip to content
Advertisement

SQL Find list of tuples that fulfil at least one of the conditions

Question: Find the restaurant A that fulfils at least one of the following conditions:

Conditions

  1. Restaurant A that is situated in ‘Central’ area or
  2. Restaurant A that sells at least 10 pizzas or
  3. Price of every pizza sold by A is at most $20

Expected outcomes: List with (restaurant name)

Database Schema: Customers(cname, area), Restaurants(rname, area), Pizzas(pizza), Sells(rname,pizza,price), Likes(cname, pizza)

Restaurants Table

  rname  |  area   
---------+---------
 Alpha   | East
 Beta    | East
 Gamma   | Central
 Delta   | Central
 Epsilon | North
 Zeta    | North
 Eta     | South
 Theta   | South
 Iota    | West
 Lambda  | West

Sells table

  rname  |   pizza    | price 
---------+------------+-------
 Gamma   | Funghi     |    30
 Gamma   | Margherita |    30
 Gamma   | Marinara   |    19
 Delta   | Funghi     |    34
 Delta   | Margherita |    15
 Delta   | Marinara   |    22
 Epsilon | Hawaiian   |    28
 Zeta    | Funghi     |    17
 Eta     | Marinara   |    24
 Theta   | Diavola    |    15
 Theta   | Hawaiian   |    26
 Iota    | Funghi     |    27
 Lambda  | Diavola    |    21
 Lambda  | Funghi     |    30
 Lambda  | Hawaiian   |    16
 Lambda  | Margherita |    18
 Lambda  | Marinara   |    32

My SQL Query

SELECT DISTINCT R.rname
FROM Restaurants R
NATURAL JOIN Sells S
WHERE (
    (CASE WHEN (R.area = 'Central') THEN 1 ELSE 0 END) +
    (CASE WHEN ((SELECT COUNT(DISTINCT S2.pizza) FROM Sells S2 WHERE R.rname = S2.rname)>= 10) THEN 1 ELSE 0 END) +
    (CASE WHEN (S.price <= 20) THEN 1 ELSE 0 END) 
) >= 1;

Issue I cant seem to get the correct answer for what the question is asking for. Appreciate if you can help me to see what is wrong with my sql query.

Advertisement

Answer

I think I would use subqueries in the where clause for this:

select r.*
from restaurants r
where r.location = 'Central' or
      (select count(*)
       from sells s
       where s.rname = r.rname
      ) >= 10 or
      (select max(s.price)
       from sells s
       where s.rname = r.rname
      ) <= 20;

There are ways to handle this query using JOIN and aggregation as well:

select r.*
from restaurants r left join
     sells s
     using (rname)
group by r.rname  -- assumes this is a unique or primary key
having r.location = 'Central' or
       count(*) >= 10 or
       max(s.price) <= 20;

Both of these assume that the sells table has only pizzas.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement