UPDATE raw_candidate_data
SET gender = ‘f’
WHERE firstname IN (SELECT firstname
FROM firstname_gender_lookup
WHERE gender = ‘f’);
The inner query is the clause in brackets, in this instance it is a shorthand way of building a list for an “IN” comparison. Often an inner query returns a single value, i.e. for an average or maximum in a list.
This expression contains a correlated subquery:
UPDATE raw_candidate_data
SET party_id = (SELECT party_id
FROM parties
WHERE raw_candidate_data.party = parties.party_name);
The inner query requires information from the outer query to work, this expression acts as a look up.
Complex queries can be given aliases using the VIEW keyword, for example:
CREATE VIEW web_designer AS SELECT mc.first_name, mc.last_name, mc.phone,
mc.email FROM my_contacts mc NATURAL JOIN job_desired jd WHERE jd.title=‘Web Designer’;
Can subsequently be used by:
SELECT * FROM web_designers;
The view web_designers can be treated just as any other table.
The results of multiple select commands can be combined using the keywords: UNION, UNION ALL, INTERSECT and EXCEPT. UNION returns the distinct union of the results of all the selects, i.e. with no repeats, UNION ALL includes the repeats. INTERSECT returns items that are common to both SELECTs and EXCEPT returns those items that are returned by the first SELECT but not the second. The general form for these combination operations is as follows:
SELECT title FROM job_current
UNION
SELECT title FROM job_desired
UNION
SELECT title FROM job_listings
ORDER BY title;
Each SELECT statement must return the same number of columns and each column must be coercible to the same datatype. Only a single ORDER BY statement for the set of SELECTs can be used.
Keywords: UNION, UNION ALL, INTERSECT, EXCEPT, VIEW