Search code examples
sqlgoogle-cloud-sql

How to exclude the results of an inner query in SQL?


I am trying to exclude the results of an inner query in SQL (I am currently working on Googles cloud platform), I have the following table:

date       | name 
-----------+------------
2019-09-10 | gas_300x10
2019-09-10 | gas_250x10
2019-09-10 | gas_3x3
2019-09-11 | gas_300x10
2019-09-11 | gas_250x10
2019-09-11 | gas_4x4

I am trying to exclude the values where the name is equal to gas_300x10 and gas_250x10 for the date of 2019-09-10 only!

I want to keep the other values from that date and also want to keep where gas_300x10 and gas_250x10 occur on other days for example on the day 2019-09-11.

I have the following query which excludes the values for the date I do not want - so I don't want those two values for 2019-09-10:

SELECT * 
FROM my_table 
WHERE date = '2019-09-10' 
  AND (name = 'gas_300x10' OR name = 'gas_250x10') 

This query would essentially return those values I do not want - how can I embed this as an inner query so that these results are excluded from the rest of the data?

I have tried using EXCEPT and NOT IN as a subquery but have not found any luck!

I think the code would work like this but I am unsure:

SELECT * 
FROM my_table 
EXCEPT
SELECT * 
FROM my_table 
WHERE date = '2019-09-10' 
  AND (name = 'gas_300x10' OR name = 'gas_250x10') 

Solution

  • Use a combined expression:

    select *
    from mytable
    where not (date = date '2019-09-10' and name in ('gas_300x10', 'gas_250x10'));
    

    or

    select *
    from mytable
    where date <> date '2019-09-10' or name not in ('gas_300x10', 'gas_250x10');