Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL – Subqueries.

Similar presentations


Presentation on theme: "SQL – Subqueries."— Presentation transcript:

1 SQL – Subqueries

2 Chinook Dataset chinookdatabase.codeplex.com It is a large (~1MB) of many tables representing a media library (a la iTunes and a linked employee database.

3 Union UNION combines the result sets of two queries.
Column data types in the two queries must match. UNION combines by column position rather than column name. If we wanted all the names of Artists and Albums: SELECT Artist.Name FROM Artist UNION SELECT Album.Title FROM Album;

4 union all UNION performs a DISTINCT on the result set, eliminating any duplicate rows. UNION ALL does not remove duplicates, and it therefore faster to perform than UNION. If I wanted the Artists and Album names, but duplicates were okay: SELECT Artist.Name FROM Artist UNION ALL SELECT Album.Title FROM Album;

5 FULL OUTER JOIN (Take 2) If I wanted all the Artist and Album pairs (with NULL if unmatched): SELECT Artist.Name, Album.Title FROM Artist LEFT OUTER JOIN Album ON Artist.ArtistId = Album.ArtistId UNION ALL -- combining two left joins FROM Album LEFT OUTER JOIN Artist WHERE Artist.ArtistID IS NULL; -- exclude repeated inner join

6 Can you write a FULL Outer join now?
Perhaps with a few minutes of time. Sure, it makes sense to me. Josh is a bastard.

7 When is a Left outer join the same as an inner join?
Never. When the left rows always has a match. When the left rows don't have NULLs. Is this the set up of a joke?

8 http://www. codeproject

9 Subqueries A subquery is a SQL query within a query.
Subqueries are nested queries that provide data to the enclosing query. Subqueries can return individual values or a list of records Subqueries must be enclosed with parenthesis If I wanted all the Artists who released an Album with just their own name: SELECT Artist.Name FROM Artist WHERE Artist.Name IN (SELECT Album.Title FROM Album);

10 Exists WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. EXISTS is commonly used with correlated subqueries (nested subqueries that use values in the outer query). If I want all the Tracks that appear in a Playlist: SELECT Track.Name FROM Track WHERE EXISTS (SELECT PlaylistTrack.TrackId FROM PlaylistTrack WHERE Track.TrackId = PlaylistTrack.TrackId);

11 Does the columns returned by an exists subquery matter?
The first value returned matters, the rest don't Yes you can only have one column returned Nope Can you go back one slide?

12 All the same SELECT * FROM Track WHERE EXISTS
(SELECT PlaylistTrack.TrackId FROM PlaylistTrack WHERE Track.TrackId = PlaylistTrack.TrackId); (SELECT * FROM PlaylistTrack (SELECT 1 FROM PlaylistTrack


Download ppt "SQL – Subqueries."

Similar presentations


Ads by Google