Monday, September 8, 2014

Union, Intersect and Except



SELECT title FROM job_current
UNION
SELECT title FROM job_desired
UNION
SELECT title FROM job_listings;

Rules

1. UNION can only take one ORDER BY at the end of the statement.

SELECT title FROM job_current
UNION
SELECT title FROM job_desired
UNION
SELECT title FROM job_listings
ORDER BY title;

2. The number of columns in each SELECT must match.
3. Must also have the same expressions and aggregate functions in each SELECT statement.
4. SQL suppresses duplicate values from the results of a union.

UNION ALL

same as UNION but does not suppress duplicates

SELECT title FROM job_current
UNION ALL
SELECT title FROM job_desired
UNION ALL
SELECT title FROM job_listings
ORDER BY title;

Creating a table from your union

CREATE TABLE my_union AS
SELECT title FROM job_current UNION
SELECT title FROM job_desired
UNION SELECT title FROM job_listings

INTERSECT

To find parts of queries that overlap.

SELECT title FROM job_current
INTERSECT
SELECT title FROM job_desired;


EXCEPT

EXCEPT returns only those columns that are in the first query, but not in the second query.

SELECT title FROM job_current
EXCEPT
SELECT title FROM job_desired;


No comments:

Post a Comment