UNION, UNION ALL, EXCEPT, INTERSECT Flashcards
How does UNION work?
It returns all rows from the two queries, discarding duplicates.
SQL Server 70-461 04-02b to 04-03
What is the general format of two queries using UNION?
<qry1 Select Statement> UNION <qry2 Select Statement>
Just making a sentence long enough so the code will left justify for this flash card.
SQL Server 70-461 04-02b to 04-03
How is UNION ALL different from UNION?
It doesn’t elminate duplicates
SQL Server 70-461 04-02b to 04-03
If UNION and UNION ALL will return the same results, i.e. there are no duplicates, which should you use?
UNION ALL. UNION may attempt to eliminate duplicates, even though there aren’t any, and it could cause a performance issue.
SQL Server 70-461 04-02b to 04-03
How does INTERSECT work?
It returns only distinct rows that are common to both sets. If a row appears at least one time in the first set and one time in the second set it will be included one time in the result of the INTERSECT.
SQL Server 70-461 04-02b to 04-03
What is the general form of two queries using INTERSECT?
<qry1 Select Statement> INTERSECT <qry2 Select Statement>
Just making a sentence long enough so the code will left justify for this flash card.
SQL Server 70-461 04-02b to 04-03
What is the general form of two queries using EXCEPT?
<qry1 Select Statement> EXCEPT <qry2 Select Statement>
Just making a sentence long enough so the code will left justify for this flash card.
SQL Server 70-461 04-02b to 04-03
How would <qry1> UNION <qry2> INTERSECT <qry3> be evaluated?
- The intersection between qry2 and qry3 happens first.
- Next, a union between the result of the intersection and qry1 takes place.
SQL Server 70-461 04-02b to 04-03
What can you do to force precendence the way you want it to be for joins involving more than one set operator?
- Use Parentheses
- From previous example:
(<qry1> UNION <qry2>)
INTERSECT <qry3>
SQL Server 70-461 04-02b to 04-03
What are the three types of set operators?
- UNION
- INTERSECT
- EXCEPT
SQL Server 70-461 04-02b to 04-03
What is the multi-set operator?
UNION ALL
SQL Server 70-461 04-02b to 04-03
How does EXCEPT work?
- It returns distinct rows that appear in the first query but not in the second.
- If a row occurs at least once in the first query and zero times in the second, it’s returned once in the output.
SQL Server 70-461 04-02b to 04-03
What four guidelines must you follow when working with set operators?
- Number of columns has to be the same and column types of corresponding columns must be compatable.
- The individual queries can’t use ORDER BY but the result of the set operator can.
- Column names determined by first query.
- Set operators consider two NULLS equal.
SQL Server 70-461 04-02b to 04-03
What is the order of precedence for set operators?
- Intersect precedes UNION and EXCEPT
- UNION and EXCEPT are evaluated from left to right based on their position in the expression.
SQL Server 70-461 04-02b to 04-03