In this project, we'll continue to use postgres.devmountain.com to create more intermediate SQL queries.
When creating tables we can specify a column as having a foreign key. The datatype of our column must match the datatype of the column we are linking to. The most common foriegn key is a primary key which is usually an integer.
- Create a new table called moviewith amovie_id,title, andmedia_type_id.- Make media_type_ida foreign key to themedia_type_idcolumn on themedia_typetable.
 
- Make 
- Add a new entry into the movietable with atitleandmedia_type_id.
- Query the movietable to get your entry.
  SQL Solutions  
  Create movie table  
CREATE TABLE movie (
  movie_id SERIAL,
  title TEXT,
  media_type_id INTEGER, 
  FOREIGN KEY(media_type_id) REFERENCES media_type(media_type_id)
);  Add movie  
INSERT INTO movie ( title, media_type_id ) VALUES ( 'Aladdin', 3 );  Query movie Table  
SELECT * FROM movie;We can also add a foreign key to an existing table. Let's add one to our movie table that references genre_id on the genre table.
- Add a new column called genre_idthat referencesgenre_idon thegenretable.
- Query the movietable to see your entry.
  SQL Solutions  
  Add Foreign Key  
ALTER TABLE movie ADD COLUMN genre_id INTEGER REFERENCES genre(genre_id);  Query movie Table  
SELECT * FROM movie;We don't want to leave the genre_id equal to null so let's add a value using the update command. With an update command you always want to use a WHERE clause. If you don't you will overwrite data on all records.
- Update the first entry in the movietable to agenre_idof22.
- Query the movietable to see your entry.
  SQL Solutions  
  Updating First Entry  
UPDATE movie SET genre_id=22 WHERE movie_id=1;  Query movie Table  
SELECT * FROM movie;Now that we know how to make foreign keys and change data, let's do some practice queries. The simplest way to use a foreign key is via a join statement.
- Join the artistandalbumtables to list out the artist name and album name.
  artist and album Join  
SELECT a.title, ar.name 
FROM album a 
JOIN artist ar ON a.artist_id = ar.artist_id;The next way to use a primary key is with a nested query/sub-select statement. By using parenthesis we can do a select inside of a select. This is really effective when you have a foreign key link between two tables because now we can filter our main query by criteria on a referenced table.
- Use a sub-select statement to get all tracks from the Tracktable where thegenre_idis eitherJazzorBlues.
  Sub-Select  
SELECT * FROM Track 
WHERE genre_id IN ( SELECT genre_id FROM genre WHERE name = 'Jazz' OR name = 'Blues' );- Update Phoneon theEmployeetable tonullwhere theEmployeeIdis1.
- Query the Employeetable to get the employee you just updated.
  SQL Solutions  
  Setting to null  
UPDATE Employee SET Phone = null WHERE EmployeeId = 1;  Query the Employee Table  
SELECT * FROM Employee WHERE EmployeeId = 1;Sometimes you want to know when there is no value. For example, let's use the customer table to figure out which customers do not have a company.
- Get all customers from the customertable who do not have a company.
  No Company customers  
SELECT * from customer WHERE Company IS null;How many albums does each artist have? We could count manually, but no! Group by allows us to do aggregate counts.
- Select all artist ids, artist names, and count how many albums they have.
  Group By  
SELECT ar.artist_id, ar.name, COUNT(*) 
FROM artist ar
JOIN album a ON ar.artist_id = a.artist_id 
GROUP BY ar.artist_id;Modify the solution to order the album count by largest to smallest.
Distinct is great if you want to get a dataset with no duplicates.
- Get all countries from the customertable with no duplicates.
  No Duplicate Countries  
SELECT DISTINCT country FROM customer;Deleting rows can be dangerous if you are not cautious. Always do a select of what you plan to delete to make sure that you are going to delete the correct records.
- Select all records from the customertable where fax is null;
- Delete all records from the customertable where fax is null;
  SQL Solutions  
  All null fax numbers  
SELECT * FROM customer WHERE fax IS null;  Delete null fax customers  
/* The delete won't work since they are children using a foreign key. However, if there wasn't a foreign key, you would successfully delete all customers WHERE fax is null */
DELETE FROM customer WHERE fax IS null;If you see a problem or a typo, please fork, make the necessary changes, and create a pull request so we can review your changes and merge them into the master repo and branch.
© DevMountain LLC, 2017. Unauthorized use and/or duplication of this material without express and written permission from DevMountain, LLC is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to DevMountain with appropriate and specific direction to the original content.
