Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Set Difference

Tags:

sql

mysql

How would I do the following in SQL:

select distinct(territory_id) from main_territorypricing

"minus"

select distinct(territory_id) from main_territorypricing where store_url is not null

Basically, I want all territory_ids that are contained in the top line that are not contained in the second line.

like image 492
David542 Avatar asked Jan 15 '15 21:01

David542


People also ask

What is set difference in SQL?

The set difference operation returns all the rows in one table not in another. You can do this with not exists. For example: select colour, shape from your_brick_collection ybc where not exists ( select null from my_brick_collection mbc where ybc. colour = mbc.

What are the different set operators in SQL?

Learn Python + JavaScript + Microsoft SQL for Data science The SET operators available in Oracle 11g are UNION,UNION ALL,INTERSECT,and MINUS. The UNION set operator returns the combined results of the two SELECT statements.

How do I find the difference between two values in SQL?

SQL Server DIFFERENCE() Function The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. 0 indicates weak or no similarity between the SOUNDEX values.

Why we use set operators in SQL?

SQL provides set operators to compare rows from two or more tables or to combine the results obtained from two or more queries to obtain the final result. These operators are used to join the results of two (or more) SELECT statements.


2 Answers

If you want to do as you said:

select distinct territory_id 
from main_territorypricing
where territory_id not in (
    select territory_id from main_territorypricing where store_url is not null
    )

But based on the logic of what you have described, the easier solution is:

select territory_id 
    from main_territorypricing
    where store_url is null

This, is, provided that you have only these two fields (territory_id and store_url) and the rows are unique.

Otherwise, there is another tricky solution:

select territory_id 
from main_territorypricing
group by territory_id 
having (max(store_url) is null)
like image 123
Alisa Avatar answered Oct 03 '22 18:10

Alisa


select distinct(territory_id) from main_territorypricing
where
    territory_id in
      (select territory_id from main_territorypricing)
and territory_id not in 
    (select territory_id from main_territorypricing where store_url is not null)
like image 42
David542 Avatar answered Oct 03 '22 19:10

David542