0

i am a bit comfused about when do i have to use intersect in sql.The example that i am given is the following:

I have two tables:

 MovieStar(name, address, gender, birthdate)
 MovieExec(name, address, cert#, netWorth)

The example asks to find the name and address of all female actors who also are a movie executor and have networth over 10000000.The solution of the example in the book is the following:

(SELECT name, address
 FROM MovieStar
 WHERE gender = 'F')
   INTERSECT
 (SELECT name, address
  FROM MovieExec
  WHERE netWorth > 10000000);

So my problem is why i have to use INTERSECT while i could use the "AND" operator like:

SELECT name, address
FROM MovieStar, MovieExec
WHERE gender = 'F' AND netWorth > 10000000

Is there any tricky way to figure out when is better to use INTERSECT or "AND"?

Zisis Diamantis
  • 121
  • 1
  • 2
  • 10

1 Answers1

3

Use INTERSECT when it suits you and you get correct results. Second always compare execution plan and statistics, because the way you get result may vary.

SqlFiddleDemo

1)

 SELECT name, address
 FROM MovieStar
 WHERE gender = 'F'
 INTERSECT
 SELECT name, address
 FROM MovieExec
 WHERE netWorth > 10000000;

It means take name and addresses from MovieStar where gender is 'F', take name and address from MovieExec where networth > 100000 and find records which are in both sets.

2)

SELECT ms.name, ms.address
FROM MovieStar AS ms, MovieExec AS me
WHERE gender = 'F' AND netWorth > 10000000

It means that you generate CROSS JOIN Cartesian Product(MxN records) and then take only records where gender = 'F' AND netWorth > 10000000

I guess that the first approach will returns result faster and use less memory(but Query Optimizer can do a lot).

When you should use INTERSECT:

  • you want to get intersection of both sets and you cannot JOIN them explicitly
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • I think i understand, so with the first solution i would get only the records which are both female and networth > 1000000 but in the second one i will get both records of females and records of networth > 10000000.Thank you! – Zisis Diamantis Aug 31 '15 at 14:21
  • @ZisisDiamantis See m updated answer and check sqlfiddle example. In both cases you will get female and networth > 1000000 but in the second you will get the same answer multiple times, it's how CROSS JOIN works, if you don't want this you need to use `SELECT DISTINCT ms.name, ms.address` – Lukasz Szozda Aug 31 '15 at 14:31