From a6e73954f305de5a9ce68593ee2797593d889fc1 Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Wed, 17 May 2017 10:19:56 -0700 Subject: [PATCH 1/7] initial commit --- Day 1/1 SQL Basics.md | 85 +++++ Day 1/2 Advanced SQL queries.md | 487 ++++++++++++++++++++++++ Day 2/3 Relational Queries.md | 336 ++++++++++++++++ Day 2/4 Modifying databases with SQL.md | 127 ++++++ 4 files changed, 1035 insertions(+) create mode 100644 Day 1/1 SQL Basics.md create mode 100644 Day 1/2 Advanced SQL queries.md create mode 100644 Day 2/3 Relational Queries.md create mode 100644 Day 2/4 Modifying databases with SQL.md diff --git a/Day 1/1 SQL Basics.md b/Day 1/1 SQL Basics.md new file mode 100644 index 0000000..1a0e81c --- /dev/null +++ b/Day 1/1 SQL Basics.md @@ -0,0 +1,85 @@ +# SQL BASICS + +## Challenge: Book list database + +[x] What are your favorite books? You can make a database table to store them in! In this first step, create a table to store your list of books. It should have columns for id, name, and rating. + +CREATE TABLE favorite_books (id INTEGER PRIMARY KEY, name TEXT, rating INTEGER); + +[x] Now, add three of your favorite books into the table. + +CREATE TABLE favorite_books (id INTEGER PRIMARY KEY, name TEXT, rating INTEGER); +INSERT INTO favorite_books VALUES ( 1, "Revelation Space", 10 ); +INSERT INTO favorite_books VALUES ( 2, "Harry Potter", 8); +INSERT INTO favorite_books VALUES ( 3, "The Godfather", 7); + + +## Challenge: Box office hits database + +### Select them all +[x] This database contains an incomplete list of box office hits and their release year. In this challenge, you're going to get the results back out of the database in different ways! In this first step, just select all the movies. + +CREATE TABLE movies (id INTEGER PRIMARY KEY, name TEXT, release_year INTEGER); +INSERT INTO movies VALUES (1, "Avatar", 2009); +INSERT INTO movies VALUES (2, "Titanic", 1997); +INSERT INTO movies VALUES (3, "Star Wars: Episode IV - A New Hope", 1977); +INSERT INTO movies VALUES (4, "Shrek 2", 2004); +INSERT INTO movies VALUES (5, "The Lion King", 1994); +INSERT INTO movies VALUES (6, "Disney's Up", 2009); +SELECT * FROM movies; + +### Filter recent movies +[x] Now, add a second query after the first, that retrieves only the movies that were released in the year 2000 or later, not before. Sort the results so that the earlier movies are + +CREATE TABLE movies (id INTEGER PRIMARY KEY, name TEXT, release_year INTEGER); +INSERT INTO movies VALUES (1, "Avatar", 2009); +INSERT INTO movies VALUES (2, "Titanic", 1997); +INSERT INTO movies VALUES (3, "Star Wars: Episode IV - A New Hope", 1977); +INSERT INTO movies VALUES (4, "Shrek 2", 2004); +INSERT INTO movies VALUES (5, "The Lion King", 1994); +INSERT INTO movies VALUES (6, "Disney's Up", 2009); +SELECT * FROM movies; +SELECT * FROM movies WHERE release_year >= 2000 ORDER BY release_year; + + +## Challenge: TODO list database stats + +### Step 1 +[x] Here's a table containing a TODO list with the number of minutes it will take to complete each item. Insert another item to your todo list with the estimated minutes it will take + +CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); +INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); +INSERT INTO todo_list VALUES (2, "vacuuming", 20); +INSERT INTO todo_list VALUES (3, "Learn some stuff on KA", 30); +INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); + +### Step 2 +[x] Select the SUM of minutes it will take to do all of the items on your TODO list. You should only have one SELECT statement. + +CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); +INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); +INSERT INTO todo_list VALUES (2, "vacuuming", 20); +INSERT INTO todo_list VALUES (3, "Learn some stuff on KA", 30); +INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); +SELECT SUM(minutes) FROM todo_list; + +## Project: Design a store database +[x] Create your own store! Your store should sell one type of things, like clothing or bikes, whatever you want your store to specialize in. You should have a table for all the items in your store, and at least 5 columns for the kind of data you think you'd need to store. You should sell at least 15 items, and use select statements to order your items by price and show at least one statistic about the items. + +CREATE TABLE wow_chars(id INTEGER, class TEXT, spec TEXT, race TEXT, cost INTEGER); +INSERT INTO wow_chars VALUES(1, "Paladin", "Protection", "Tauren", 500); +INSERT INTO wow_chars VALUES(1, "Paladin", "Holy", "Blood-Elf", 350); +INSERT INTO wow_chars VALUES(1, "Paladin", "Retribution", "Blood-Elf", 100); +INSERT INTO wow_chars VALUES(1, "Archer", "Marksmanship", "Blood-Elf", 300); +INSERT INTO wow_chars VALUES(1, "Archer", "Beast Mastery", "Troll", 350); +INSERT INTO wow_chars VALUES(1, "Paladin", "Protection", "Blood-Elf", 400); +INSERT INTO wow_chars VALUES(1, "Rogue", "Subtlety", "Goblin", 350); +INSERT INTO wow_chars VALUES(1, "Priest", "Holy", "Undead", 500); +INSERT INTO wow_chars VALUES(1, "Priest", "Holy", "Tauren", 400); +INSERT INTO wow_chars VALUES(1, "Monk", "Brew Master", "Pandaren", 350); +INSERT INTO wow_chars VALUES(1, "Shaman", "Elemental", "Pandaren", 400); +INSERT INTO wow_chars VALUES(1, "Archer", "Survival", "Blood-Elf", 350); +INSERT INTO wow_chars VALUES(1, "Druid", "Feral", "Orc", 200); +INSERT INTO wow_chars VALUES(1, "Warrior", "Arms", "Blood-Elf", 200); +INSERT INTO wow_chars VALUES(1, "Deathknight", "Frost", "Goblin", 200); +SELECT class, cost FROM wow_chars ORDER BY cost; diff --git a/Day 1/2 Advanced SQL queries.md b/Day 1/2 Advanced SQL queries.md new file mode 100644 index 0000000..7b82f0c --- /dev/null +++ b/Day 1/2 Advanced SQL queries.md @@ -0,0 +1,487 @@ +# More Advanced SQL queries + +## Challenge: Karaoke song selector +### Step 1 +[x] Ever sung karaoke? It's a place where you sing songs with your friends, and it's a lot of fun. We've created a table with songs, and in this challenge, you'll use queries to decide what songs to sing. For the first step, select all the song titles. + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY, + title TEXT, + artist TEXT, + mood TEXT, + duration INTEGER, + released INTEGER); + +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Bohemian Rhapsody", "Queen", "epic", 60, 1975); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Let it go", "Idina Menzel", "epic", 227, 2013); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will survive", "Gloria Gaynor", "epic", 198, 1978); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Twist and Shout", "The Beatles", "happy", 152, 1963); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("La Bamba", "Ritchie Valens", "happy", 166, 1958); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will always love you", "Whitney Houston", "epic", 273, 1992); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Sweet Caroline", "Neil Diamond", "happy", 201, 1969); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Call me maybe", "Carly Rae Jepsen", "happy", 193, 2011); + +SELECT title FROM songs; + +### Step 2 +[x]epic song released after 1990 + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY, + title TEXT, + artist TEXT, + mood TEXT, + duration INTEGER, + released INTEGER); + +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Bohemian Rhapsody", "Queen", "epic", 60, 1975); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Let it go", "Idina Menzel", "epic", 227, 2013); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will survive", "Gloria Gaynor", "epic", 198, 1978); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Twist and Shout", "The Beatles", "happy", 152, 1963); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("La Bamba", "Ritchie Valens", "happy", 166, 1958); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will always love you", "Whitney Houston", "epic", 273, 1992); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Sweet Caroline", "Neil Diamond", "happy", 201, 1969); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Call me maybe", "Carly Rae Jepsen", "happy", 193, 2011); + +SELECT title FROM songs; +SELECT title FROM songs WHERE mood = "epic" OR released > 1989; + +### Step 3 +[x]People get picky at the end of the night. Add another SELECT that uses AND to show the titles of songs that are 'epic', and released after 1990, and less than 4 minutes long. +Note that the duration column is measured in seconds. + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY, + title TEXT, + artist TEXT, + mood TEXT, + duration INTEGER, + released INTEGER); + +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Bohemian Rhapsody", "Queen", "epic", 60, 1975); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Let it go", "Idina Menzel", "epic", 227, 2013); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will survive", "Gloria Gaynor", "epic", 198, 1978); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Twist and Shout", "The Beatles", "happy", 152, 1963); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("La Bamba", "Ritchie Valens", "happy", 166, 1958); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("I will always love you", "Whitney Houston", "epic", 273, 1992); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Sweet Caroline", "Neil Diamond", "happy", 201, 1969); +INSERT INTO songs (title, artist, mood, duration, released) + VALUES ("Call me maybe", "Carly Rae Jepsen", "happy", 193, 2011); + +SELECT title FROM songs; +SELECT title FROM songs WHERE mood = "epic" OR released > 1989; +SELECT title From songs WHERE mood = "epic" AND released > 1989 AND duration < 240; + +## Challenge: Playlist maker +### Step 1 +[x] We've created a database of songs and artists, and you'll make playlists from them in this challenge. In this first step, select the title of all the songs by the artist named 'Queen'. + +CREATE TABLE artists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + country TEXT, + genre TEXT); + +INSERT INTO artists (name, country, genre) + VALUES ("Taylor Swift", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Led Zeppelin", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("ABBA", "Sweden", "Disco"); +INSERT INTO artists (name, country, genre) + VALUES ("Queen", "UK", "Rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Celine Dion", "Canada", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Meatloaf", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Garth Brooks", "US", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Shania Twain", "Canada", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Rihanna", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Guns N' Roses", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Gloria Estefan", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Bob Marley", "Jamaica", "Reggae"); + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + artist TEXT, + title TEXT); + +INSERT INTO songs (artist, title) + VALUES ("Taylor Swift", "Shake it off"); +INSERT INTO songs (artist, title) + VALUES ("Rihanna", "Stay"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "My heart will go on"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "A new day has come"); +INSERT INTO songs (artist, title) + VALUES ("Shania Twain", "Party for two"); +INSERT INTO songs (artist, title) + VALUES ("Gloria Estefan", "Conga"); +INSERT INTO songs (artist, title) + VALUES ("Led Zeppelin", "Stairway to heaven"); +INSERT INTO songs (artist, title) + VALUES ("ABBA", "Mamma mia"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bicycle Race"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bohemian Rhapsody"); +INSERT INTO songs (artist, title) + VALUES ("Guns N' Roses", "Don't cry"); + +SELECT title FROM songs WHERE artist="Queen"; + +### Step 2 +[x] pop genre + +CREATE TABLE artists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + country TEXT, + genre TEXT); + +INSERT INTO artists (name, country, genre) + VALUES ("Taylor Swift", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Led Zeppelin", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("ABBA", "Sweden", "Disco"); +INSERT INTO artists (name, country, genre) + VALUES ("Queen", "UK", "Rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Celine Dion", "Canada", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Meatloaf", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Garth Brooks", "US", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Shania Twain", "Canada", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Rihanna", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Guns N' Roses", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Gloria Estefan", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Bob Marley", "Jamaica", "Reggae"); + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + artist TEXT, + title TEXT); + +INSERT INTO songs (artist, title) + VALUES ("Taylor Swift", "Shake it off"); +INSERT INTO songs (artist, title) + VALUES ("Rihanna", "Stay"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "My heart will go on"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "A new day has come"); +INSERT INTO songs (artist, title) + VALUES ("Shania Twain", "Party for two"); +INSERT INTO songs (artist, title) + VALUES ("Gloria Estefan", "Conga"); +INSERT INTO songs (artist, title) + VALUES ("Led Zeppelin", "Stairway to heaven"); +INSERT INTO songs (artist, title) + VALUES ("ABBA", "Mamma mia"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bicycle Race"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bohemian Rhapsody"); +INSERT INTO songs (artist, title) + VALUES ("Guns N' Roses", "Don't cry"); + +SELECT title FROM songs WHERE artist="Queen"; +SELECT name FROM artists WHERE genre ="Pop"; + +### Step 3 +[x] To finish creating the 'Pop' playlist, add another query that will select the title of all the songs from the 'Pop' artists. It should use IN on a nested subquery that's based on your previous query. + +CREATE TABLE artists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + country TEXT, + genre TEXT); + +INSERT INTO artists (name, country, genre) + VALUES ("Taylor Swift", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Led Zeppelin", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("ABBA", "Sweden", "Disco"); +INSERT INTO artists (name, country, genre) + VALUES ("Queen", "UK", "Rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Celine Dion", "Canada", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Meatloaf", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Garth Brooks", "US", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Shania Twain", "Canada", "Country"); +INSERT INTO artists (name, country, genre) + VALUES ("Rihanna", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Guns N' Roses", "US", "Hard rock"); +INSERT INTO artists (name, country, genre) + VALUES ("Gloria Estefan", "US", "Pop"); +INSERT INTO artists (name, country, genre) + VALUES ("Bob Marley", "Jamaica", "Reggae"); + +CREATE TABLE songs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + artist TEXT, + title TEXT); + +INSERT INTO songs (artist, title) + VALUES ("Taylor Swift", "Shake it off"); +INSERT INTO songs (artist, title) + VALUES ("Rihanna", "Stay"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "My heart will go on"); +INSERT INTO songs (artist, title) + VALUES ("Celine Dion", "A new day has come"); +INSERT INTO songs (artist, title) + VALUES ("Shania Twain", "Party for two"); +INSERT INTO songs (artist, title) + VALUES ("Gloria Estefan", "Conga"); +INSERT INTO songs (artist, title) + VALUES ("Led Zeppelin", "Stairway to heaven"); +INSERT INTO songs (artist, title) + VALUES ("ABBA", "Mamma mia"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bicycle Race"); +INSERT INTO songs (artist, title) + VALUES ("Queen", "Bohemian Rhapsody"); +INSERT INTO songs (artist, title) + VALUES ("Guns N' Roses", "Don't cry"); + +SELECT title FROM songs WHERE artist="Queen"; +SELECT name FROM artists WHERE genre ="Pop"; +SELECT title FROM songs WHERE artist IN (SELECT name From artists WHERE genre = "Pop"); + +## Challenge: The wordiest author +### Step 1 +[x] We've created a database of a few popular authors and their books, with word counts for each book. In this first step, select all the authors who have written more than 1 million words, using GROUP BY and HAVING. Your results table should include the 'author' and their total word count as a 'total_words' column. + +CREATE TABLE books ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + author TEXT, + title TEXT, + words INTEGER); + +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Philosopher's Stone", 79944); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Chamber of Secrets", 85141); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Prisoner of Azkaban", 107253); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Goblet of Fire", 190637); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Order of the Phoenix", 257045); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Half-Blood Prince", 168923); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Deathly Hallows", 197651); + +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Twilight", 118501); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "New Moon", 132807); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Eclipse", 147930); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Breaking Dawn", 192196); + +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "The Hobbit", 95022); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Fellowship of the Ring", 177227); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Two Towers", 143436); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Return of the King", 134462); + +SELECT author, SUM(words) AS total_words FROM books +GROUP BY author +HAVING total_words > 1000000 +; + +### Step 2 +[x] Now select all the authors that write more than an average of 150,000 words per book. Your results table should include the 'author' and average words as an 'avg_words' column. + +CREATE TABLE books ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + author TEXT, + title TEXT, + words INTEGER); + +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Philosopher's Stone", 79944); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Chamber of Secrets", 85141); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Prisoner of Azkaban", 107253); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Goblet of Fire", 190637); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Order of the Phoenix", 257045); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Half-Blood Prince", 168923); +INSERT INTO books (author, title, words) + VALUES ("J.K. Rowling", "Harry Potter and the Deathly Hallows", 197651); + +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Twilight", 118501); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "New Moon", 132807); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Eclipse", 147930); +INSERT INTO books (author, title, words) + VALUES ("Stephenie Meyer", "Breaking Dawn", 192196); + +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "The Hobbit", 95022); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Fellowship of the Ring", 177227); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Two Towers", 143436); +INSERT INTO books (author, title, words) + VALUES ("J.R.R. Tolkien", "Return of the King", 134462); + +SELECT author, SUM(words) AS total_words FROM books +GROUP BY author +HAVING total_words > 1000000 +; +SELECT author, AVG(words) AS avg_words FROM books +GROUP BY author +HAVING avg_words > 150000 +; +## Challenge: Gradebook +### Step 1 +[x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. + +CREATE TABLE student_grades ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + number_grade INTEGER, + fraction_completed REAL); + +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winston", 90, 0.805); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winnefer", 95, 0.901); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winsteen", 85, 0.906); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Wincifer", 66, 0.7054); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winster", 76, 0.5013); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winstonia", 82, 0.9045); + +SELECT name, number_grade, ROUND(fraction_completed*100) AS percent_completed FROM student_grades; + +### Step 2 +[x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. + +CREATE TABLE student_grades ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + number_grade INTEGER, + fraction_completed REAL); + +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winston", 90, 0.805); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winnefer", 95, 0.901); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winsteen", 85, 0.906); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Wincifer", 66, 0.7054); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winster", 76, 0.5013); +INSERT INTO student_grades (name, number_grade, fraction_completed) + VALUES ("Winstonia", 82, 0.9045); + +SELECT name, number_grade, ROUND(fraction_completed*100) AS percent_completed FROM student_grades; + +SELECT COUNT(*), + CASE + WHEN ROUND(fraction_completed*100) > 90 THEN "A" + WHEN ROUND(fraction_completed*100) > 80 THEN "B" + WHEN ROUND(fraction_completed*100) > 70 THEN "C" + ELSE "F" + END AS "letter_grade" +FROM student_grades +GROUP BY letter_grade; + +## Project Data dig +[x] We’ve curated a set of interesting data sets for you: Top movies, Top countries by population, Solar system objects by size, Marvel characters, Furniture store sales, Earned KA badges, Winston's donut logs, Card game results, and NFL draft picks. +Pick one of those data sets or create a data set like that, and use advanced SELECT queries to discover things about the data. What sort of questions might one have about that data, like if they were using it for an app or a business idea? Here are some ideas: + +CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, rating INTEGER); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Shawshank Redemption", 1994, "Drama", 9.2); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Godfather", 1972, "Drama", 9.2); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", 9.0); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Dark Knight", 2008, "Action", 8.9); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Schindler's List", 1993, "Drama", 8.9); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Pulp Fiction", 1994, "Drama", 8.9); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", 8.9); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Fight Club", 1999, "Suspense", 8.8); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", 8.8); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Forrest Gump", 1994, "Drama", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Inception", 2010, "Suspense", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Goodfellas", 1990, "Drama", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Matrix", 1999, "Science Fiction", 8.7); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", 8.6); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("City of God", 2002, "Drama", 8.6); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Se7en", 1995, "Suspense", 8.6); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Silence of the Lambs", 1991, "Suspense", 8.6); +INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Leon: The Professional", 1994, "Action", 8.5); +SELECT * FROM top_movies; +SELECT name FROM top_movies WHERE year_released < 2000 AND genre = "Suspense"; +SELECT COUNT(*), + CASE + WHEN year_released > 2010 THEN "2010+" + WHEN year_released > 2000 THEN "2000 - 2009" + WHEN year_released > 1990 THEN "1990 - 1999" + ELSE "before 1989" + END AS "year_group" +FROM top_movies +GROUP BY year_group; +SELECT genre, AVG(rating) AS avg_rating FROM top_movies GROUP BY genre; \ No newline at end of file diff --git a/Day 2/3 Relational Queries.md b/Day 2/3 Relational Queries.md new file mode 100644 index 0000000..8abd36e --- /dev/null +++ b/Day 2/3 Relational Queries.md @@ -0,0 +1,336 @@ +# Relational queries in SQL +## Challenge: Bobby's Hobbies +### Step 1 +[x] We've created a database of people and hobbies, and each row in hobbies is related to a row in persons via the person_id column. In this first step, insert one more row in persons and then one more row in hobbies that is related to the newly inserted person. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); + +### Step 2 +[x] results = persons name next to their hobby +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); + +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id; + +### Step 3 +[x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id; + +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + WHERE persons.name = "Bobby McBobbyFace"; + +## Challenge: Customer's Orders +### Step 1 +[x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. + +CREATE TABLE customers ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + email TEXT); + +INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); +INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); +INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); + +CREATE TABLE orders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + customer_id INTEGER, + item TEXT, + price REAL); + +INSERT INTO orders (customer_id, item, price) + VALUES (1, "Sonic Screwdriver", 1000.00); +INSERT INTO orders (customer_id, item, price) + VALUES (2, "High Quality Broomstick", 40.00); +INSERT INTO orders (customer_id, item, price) + VALUES (1, "TARDIS", 1000000.00); + +SELECT customers.name, customers.email, orders.item, orders.price + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id; + +### Step 2 +[x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. +(Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) + +CREATE TABLE customers ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + email TEXT); + +INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); +INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); +INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); + +CREATE TABLE orders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + customer_id INTEGER, + item TEXT, + price REAL); + +INSERT INTO orders (customer_id, item, price) + VALUES (1, "Sonic Screwdriver", 1000.00); +INSERT INTO orders (customer_id, item, price) + VALUES (2, "High Quality Broomstick", 40.00); +INSERT INTO orders (customer_id, item, price) + VALUES (1, "TARDIS", 1000000.00); + +SELECT customers.name, customers.email, orders.item, orders.price + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id; + +SELECT customers.name, customers.email, SUM(price) AS orders + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id + GROUP BY name + ORDER BY price DESC; + +## Challenge: Sequels in SQL +### Step 1 +[x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). + +CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + released INTEGER, + sequel_id INTEGER); + +INSERT INTO movies + VALUES (1, "Harry Potter and the Philosopher's Stone", 2001, 2); +INSERT INTO movies + VALUES (2, "Harry Potter and the Chamber of Secrets", 2002, 3); +INSERT INTO movies + VALUES (3, "Harry Potter and the Prisoner of Azkaban", 2004, 4); +INSERT INTO movies + VALUES (4, "Harry Potter and the Goblet of Fire", 2005, 5); +INSERT INTO movies + VALUES (5, "Harry Potter and the Order of the Phoenix ", 2007, 6); +INSERT INTO movies + VALUES (6, "Harry Potter and the Half-Blood Prince", 2009, 7); +INSERT INTO movies + VALUES (7, "Harry Potter and the Deathly Hallows – Part 1", 2010, 8); +INSERT INTO movies + VALUES (8, "Harry Potter and the Deathly Hallows – Part 2", 2011, NULL); + +SELECT movies.title, sequel.title as sequel + FROM movies + LEFT OUTER JOIN movies sequel + ON movies.sequel_id = sequel.id; + + +## Challenge: FriendBook +### Step 1 +[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fullname TEXT, + age INTEGER); + +INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); + +CREATE table friends ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person1_id INTEGER, + person2_id INTEGER); + +INSERT INTO friends (person1_id, person2_id) + VALUES (1, 4); +INSERT INTO friends (person1_id, person2_id) + VALUES (2, 3); + +SELECT persons.fullname, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + ; + +### Step 2 +[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fullname TEXT, + age INTEGER); + +INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); + +CREATE table friends ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person1_id INTEGER, + person2_id INTEGER); + +INSERT INTO friends (person1_id, person2_id) + VALUES (1, 4); +INSERT INTO friends (person1_id, person2_id) + VALUES (2, 3); + +SELECT persons.fullname, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + ; + +SELECT a.fullname, b.fullname + FROM friends + JOIN persons a + ON person1_id = a.id + JOIN persons b + ON person2_id = b.id +; + +## Project: Famous people +[x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. + +CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); + +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather", 1972, "Drama", "Al Pacino", 9.2); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", "Al Pacino", 9.0); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Dark Knight", 2008, "Action", "Christian Bale", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The DArk Knight Rises", 2009, "Action", "Christian Bale", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Pulp Fiction", 1994, "Drama", "Samuel L Jackson", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", "Elijah Wood", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Fight Club", 1999, "Suspense", "Edward Norton", 8.8); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", "Elijah Wood", 8.8); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", "Mark Hammil", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Forrest Gump", 1994, "Drama", "Tom Hanks", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Inception", 2010, "Suspense", "Leonardo DiCaprio", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", "Elijah Wood", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Titanic", 2000, "Drama", "Leonardo DiCaprio", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Matrix", 1999, "Science Fiction", "Keanu Reeves", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", "Mark Hammil", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("John Wick", 2002, "Action", "Keanu Reeves", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Se7en", 1995, "Suspense", "Morgan Freeman", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Avengers", 1991, "Suspense", "Samuel L Jackson", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon: The Professional", 1994, "Action", "Natalie Portman", 8.5); + +SELECT actor FROM top_movies +GROUP BY actor; diff --git a/Day 2/4 Modifying databases with SQL.md b/Day 2/4 Modifying databases with SQL.md new file mode 100644 index 0000000..a3bef26 --- /dev/null +++ b/Day 2/4 Modifying databases with SQL.md @@ -0,0 +1,127 @@ +# Modifying databases with SQL +## Challenge: Dynamic Documents +### Step 1 +[x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. + +CREATE table documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + content TEXT, + author TEXT); + +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); + +SELECT * FROM documents; +UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +SELECT * FROM documents; + +### Step 2 +[x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. + +CREATE table documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + content TEXT, + author TEXT); + +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); + +SELECT * FROM documents; +UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +SELECT * FROM documents; +DELETE FROM documents WHERE title = "Things I'm Afraid Of"; +SELECT * FROM documents + +## Challenge: Clothing alterations +### Step 1 +[x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +### Step 2 +[x] update cloths pricing + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +UPDATE clothes SET price = 10 WHERE id = 1; +UPDATE clothes SET price = 20 WHERE id = 2; +UPDATE clothes SET price = 30 WHERE id = 3; + +SELECT * FROM clothes; + + + +### Step 3 +[x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +UPDATE clothes SET price = 10 WHERE id = 1; +UPDATE clothes SET price = 20 WHERE id = 2; +UPDATE clothes SET price = 30 WHERE id = 3; + +SELECT * FROM clothes; + +INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); + +SELECT * FROM clothes; \ No newline at end of file From 2fa34f74026d6e1ebb275671ec1cd160080eebeb Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Wed, 17 May 2017 10:34:52 -0700 Subject: [PATCH 2/7] fixed Day 2 files --- Day 2/3 Relational Queries.md | 562 ++++++++++++------------ Day 2/4 Modifying databases with SQL.md | 210 +++++---- 2 files changed, 385 insertions(+), 387 deletions(-) diff --git a/Day 2/3 Relational Queries.md b/Day 2/3 Relational Queries.md index 8abd36e..dcda50a 100644 --- a/Day 2/3 Relational Queries.md +++ b/Day 2/3 Relational Queries.md @@ -2,110 +2,111 @@ ## Challenge: Bobby's Hobbies ### Step 1 [x] We've created a database of people and hobbies, and each row in hobbies is related to a row in persons via the person_id column. In this first step, insert one more row in persons and then one more row in hobbies that is related to the newly inserted person. - -CREATE TABLE persons ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT, - age INTEGER); - -INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -INSERT INTO persons(name, age) VALUES ("Rob C", 26); - -CREATE table hobbies ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person_id INTEGER, - name TEXT); - -INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); +
+
CREATE TABLE persons ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
name TEXT, +
age INTEGER); +
+
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +
INSERT INTO persons(name, age) VALUES ("Rob C", 26); +
+
CREATE table hobbies ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person_id INTEGER, +
name TEXT); +
+
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); ### Step 2 [x] results = persons name next to their hobby -CREATE TABLE persons ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT, - age INTEGER); - -INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -INSERT INTO persons(name, age) VALUES ("Rob C", 26); - -CREATE table hobbies ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person_id INTEGER, - name TEXT); - -INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); - -SELECT persons.name, hobbies.name FROM persons - JOIN hobbies - ON persons.id = hobbies.person_id; - +
CREATE TABLE persons ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
name TEXT, +
age INTEGER); +
+
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +
INSERT INTO persons(name, age) VALUES ("Rob C", 26); +
+
CREATE table hobbies ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person_id INTEGER, +
name TEXT); +
+
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); +
+
SELECT persons.name, hobbies.name FROM persons +
JOIN hobbies +
ON persons.id = hobbies.person_id; +
### Step 3 [x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. -CREATE TABLE persons ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT, - age INTEGER); - -INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -INSERT INTO persons(name, age) VALUES ("Rob C", 26); - -CREATE table hobbies ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person_id INTEGER, - name TEXT); - -INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); -SELECT persons.name, hobbies.name FROM persons - JOIN hobbies - ON persons.id = hobbies.person_id; - -SELECT persons.name, hobbies.name FROM persons - JOIN hobbies - ON persons.id = hobbies.person_id - WHERE persons.name = "Bobby McBobbyFace"; - +
+
CREATE TABLE persons ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
name TEXT, +
age INTEGER); +
+
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +
INSERT INTO persons(name, age) VALUES ("Rob C", 26); +
+
CREATE table hobbies ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person_id INTEGER, +
name TEXT); +
+
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); +
SELECT persons.name, hobbies.name FROM persons +
JOIN hobbies +
ON persons.id = hobbies.person_id; +
+
SELECT persons.name, hobbies.name FROM persons +
JOIN hobbies +
ON persons.id = hobbies.person_id +
WHERE persons.name = "Bobby McBobbyFace"; +
## Challenge: Customer's Orders ### Step 1 [x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. @@ -140,197 +141,196 @@ SELECT customers.name, customers.email, orders.item, orders.price ### Step 2 [x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. (Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) - -CREATE TABLE customers ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT, - email TEXT); - -INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); -INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); -INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); - -CREATE TABLE orders ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - customer_id INTEGER, - item TEXT, - price REAL); - -INSERT INTO orders (customer_id, item, price) - VALUES (1, "Sonic Screwdriver", 1000.00); -INSERT INTO orders (customer_id, item, price) - VALUES (2, "High Quality Broomstick", 40.00); -INSERT INTO orders (customer_id, item, price) - VALUES (1, "TARDIS", 1000000.00); - -SELECT customers.name, customers.email, orders.item, orders.price - FROM customers - LEFT OUTER JOIN orders - ON customers.id = orders.customer_id; - -SELECT customers.name, customers.email, SUM(price) AS orders - FROM customers - LEFT OUTER JOIN orders - ON customers.id = orders.customer_id - GROUP BY name - ORDER BY price DESC; - +
+
CREATE TABLE customers ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
name TEXT, +
email TEXT); +
+
INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); +
INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); +
INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); +
+
CREATE TABLE orders ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
customer_id INTEGER, +
item TEXT, +
price REAL); +
+
INSERT INTO orders (customer_id, item, price) +
VALUES (1, "Sonic Screwdriver", 1000.00); +
INSERT INTO orders (customer_id, item, price) +
VALUES (2, "High Quality Broomstick", 40.00); +
INSERT INTO orders (customer_id, item, price) +
VALUES (1, "TARDIS", 1000000.00); +
+
SELECT customers.name, customers.email, orders.item, orders.price +
FROM customers +
LEFT OUTER JOIN orders +
ON customers.id = orders.customer_id; +
+
SELECT customers.name, customers.email, SUM(price) AS orders +
FROM customers +
LEFT OUTER JOIN orders +
ON customers.id = orders.customer_id +
GROUP BY name +
ORDER BY price DESC; +
## Challenge: Sequels in SQL ### Step 1 [x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). - -CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT, - released INTEGER, - sequel_id INTEGER); - -INSERT INTO movies - VALUES (1, "Harry Potter and the Philosopher's Stone", 2001, 2); -INSERT INTO movies - VALUES (2, "Harry Potter and the Chamber of Secrets", 2002, 3); -INSERT INTO movies - VALUES (3, "Harry Potter and the Prisoner of Azkaban", 2004, 4); -INSERT INTO movies - VALUES (4, "Harry Potter and the Goblet of Fire", 2005, 5); -INSERT INTO movies - VALUES (5, "Harry Potter and the Order of the Phoenix ", 2007, 6); -INSERT INTO movies - VALUES (6, "Harry Potter and the Half-Blood Prince", 2009, 7); -INSERT INTO movies - VALUES (7, "Harry Potter and the Deathly Hallows – Part 1", 2010, 8); -INSERT INTO movies - VALUES (8, "Harry Potter and the Deathly Hallows – Part 2", 2011, NULL); - -SELECT movies.title, sequel.title as sequel - FROM movies - LEFT OUTER JOIN movies sequel - ON movies.sequel_id = sequel.id; - - +
+
CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, +
title TEXT, +
released INTEGER, +
sequel_id INTEGER); +
+
INSERT INTO movies +
VALUES (1, "Harry Potter and the Philosopher's Stone", 2001, 2); +
INSERT INTO movies +
VALUES (2, "Harry Potter and the Chamber of Secrets", 2002, 3); +
INSERT INTO movies +
VALUES (3, "Harry Potter and the Prisoner of Azkaban", 2004, 4); +
INSERT INTO movies +
VALUES (4, "Harry Potter and the Goblet of Fire", 2005, 5); +
INSERT INTO movies +
VALUES (5, "Harry Potter and the Order of the Phoenix ", 2007, 6); +
INSERT INTO movies +
VALUES (6, "Harry Potter and the Half-Blood Prince", 2009, 7); +
INSERT INTO movies +
VALUES (7, "Harry Potter and the Deathly Hallows – Part 1", 2010, 8); +
INSERT INTO movies +
VALUES (8, "Harry Potter and the Deathly Hallows – Part 2", 2011, NULL); +
+
SELECT movies.title, sequel.title as sequel +
FROM movies +
LEFT OUTER JOIN movies sequel +
ON movies.sequel_id = sequel.id; +
## Challenge: FriendBook ### Step 1 [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. - -CREATE TABLE persons ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - fullname TEXT, - age INTEGER); - -INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); -INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); -INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); -INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); -INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); - -CREATE table hobbies ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person_id INTEGER, - name TEXT); - -INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); - -CREATE table friends ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person1_id INTEGER, - person2_id INTEGER); - -INSERT INTO friends (person1_id, person2_id) - VALUES (1, 4); -INSERT INTO friends (person1_id, person2_id) - VALUES (2, 3); - -SELECT persons.fullname, hobbies.name FROM persons - JOIN hobbies - ON persons.id = hobbies.person_id - ; +
+
CREATE TABLE persons ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
fullname TEXT, +
age INTEGER); +
+
INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); +
+
CREATE table hobbies ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person_id INTEGER, +
name TEXT); +
+
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +
+
CREATE table friends ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person1_id INTEGER, +
person2_id INTEGER); +
+
INSERT INTO friends (person1_id, person2_id) +
VALUES (1, 4); +
INSERT INTO friends (person1_id, person2_id) +
VALUES (2, 3); +
+
SELECT persons.fullname, hobbies.name FROM persons +
JOIN hobbies +
ON persons.id = hobbies.person_id +
; ### Step 2 [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. - -CREATE TABLE persons ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - fullname TEXT, - age INTEGER); - -INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); -INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); -INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); -INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); -INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); - -CREATE table hobbies ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person_id INTEGER, - name TEXT); - -INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); - -CREATE table friends ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - person1_id INTEGER, - person2_id INTEGER); - -INSERT INTO friends (person1_id, person2_id) - VALUES (1, 4); -INSERT INTO friends (person1_id, person2_id) - VALUES (2, 3); - -SELECT persons.fullname, hobbies.name FROM persons - JOIN hobbies - ON persons.id = hobbies.person_id - ; - -SELECT a.fullname, b.fullname - FROM friends - JOIN persons a - ON person1_id = a.id - JOIN persons b - ON person2_id = b.id -; +
+
CREATE TABLE persons ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
fullname TEXT, +
age INTEGER); +
+
INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); +
+
CREATE table hobbies ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person_id INTEGER, +
name TEXT); +
+
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +
+
CREATE table friends ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
person1_id INTEGER, +
person2_id INTEGER); +
+
INSERT INTO friends (person1_id, person2_id) +
VALUES (1, 4); +
INSERT INTO friends (person1_id, person2_id) +
VALUES (2, 3); +
+
SELECT persons.fullname, hobbies.name FROM persons +
JOIN hobbies +
ON persons.id = hobbies.person_id +
; +
+
SELECT a.fullname, b.fullname +
FROM friends +
JOIN persons a +
ON person1_id = a.id +
JOIN persons b +
ON person2_id = b.id +
; ## Project: Famous people [x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. - -CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); - -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather", 1972, "Drama", "Al Pacino", 9.2); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", "Al Pacino", 9.0); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Dark Knight", 2008, "Action", "Christian Bale", 8.9); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The DArk Knight Rises", 2009, "Action", "Christian Bale", 8.9); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Pulp Fiction", 1994, "Drama", "Samuel L Jackson", 8.9); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", "Elijah Wood", 8.9); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Fight Club", 1999, "Suspense", "Edward Norton", 8.8); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", "Elijah Wood", 8.8); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", "Mark Hammil", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Forrest Gump", 1994, "Drama", "Tom Hanks", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Inception", 2010, "Suspense", "Leonardo DiCaprio", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", "Elijah Wood", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Titanic", 2000, "Drama", "Leonardo DiCaprio", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Matrix", 1999, "Science Fiction", "Keanu Reeves", 8.7); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", "Mark Hammil", 8.6); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("John Wick", 2002, "Action", "Keanu Reeves", 8.6); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Se7en", 1995, "Suspense", "Morgan Freeman", 8.6); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Avengers", 1991, "Suspense", "Samuel L Jackson", 8.6); -INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon: The Professional", 1994, "Action", "Natalie Portman", 8.5); - -SELECT actor FROM top_movies -GROUP BY actor; +
+
CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); +
+
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather", 1972, "Drama", "Al Pacino", 9.2); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", "Al Pacino", 9.0); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Dark Knight", 2008, "Action", "Christian Bale", 8.9); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The DArk Knight Rises", 2009, "Action", "Christian Bale", 8.9); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Pulp Fiction", 1994, "Drama", "Samuel L Jackson", 8.9); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", "Elijah Wood", 8.9); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Fight Club", 1999, "Suspense", "Edward Norton", 8.8); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", "Elijah Wood", 8.8); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", "Mark Hammil", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Forrest Gump", 1994, "Drama", "Tom Hanks", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Inception", 2010, "Suspense", "Leonardo DiCaprio", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", "Elijah Wood", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Titanic", 2000, "Drama", "Leonardo DiCaprio", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Matrix", 1999, "Science Fiction", "Keanu Reeves", 8.7); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", "Mark Hammil", 8.6); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("John Wick", 2002, "Action", "Keanu Reeves", 8.6); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Se7en", 1995, "Suspense", "Morgan Freeman", 8.6); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Avengers", 1991, "Suspense", "Samuel L Jackson", 8.6); +
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon: The Professional", 1994, "Action", "Natalie Portman", 8.5); +
+
SELECT actor FROM top_movies +
GROUP BY actor; diff --git a/Day 2/4 Modifying databases with SQL.md b/Day 2/4 Modifying databases with SQL.md index a3bef26..b269819 100644 --- a/Day 2/4 Modifying databases with SQL.md +++ b/Day 2/4 Modifying databases with SQL.md @@ -3,125 +3,123 @@ ### Step 1 [x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. -CREATE table documents ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT, - content TEXT, - author TEXT); - -INSERT INTO documents (author, title, content) - VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); -INSERT INTO documents (author, title, content) - VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); - -SELECT * FROM documents; -UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; -SELECT * FROM documents; +
CREATE table documents ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
title TEXT, +
content TEXT, +
author TEXT); +
+
INSERT INTO documents (author, title, content) +
VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +
INSERT INTO documents (author, title, content) +
VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); +
+
SELECT * FROM documents; +
UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +
SELECT * FROM documents; ### Step 2 [x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. -CREATE table documents ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT, - content TEXT, - author TEXT); - -INSERT INTO documents (author, title, content) - VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); -INSERT INTO documents (author, title, content) - VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); -INSERT INTO documents (author, title, content) - VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); - -SELECT * FROM documents; -UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; -SELECT * FROM documents; -DELETE FROM documents WHERE title = "Things I'm Afraid Of"; -SELECT * FROM documents +
CREATE table documents ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
title TEXT, +
content TEXT, +
author TEXT); +
+
INSERT INTO documents (author, title, content) +
VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +
INSERT INTO documents (author, title, content) +
VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +
INSERT INTO documents (author, title, content) +
VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); +
+
SELECT * FROM documents; +
UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +
SELECT * FROM documents; +
DELETE FROM documents WHERE title = "Things I'm Afraid Of"; +
SELECT * FROM documents ## Challenge: Clothing alterations ### Step 1 [x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. -CREATE TABLE clothes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - type TEXT, - design TEXT); - -INSERT INTO clothes (type, design) - VALUES ("dress", "pink polka dots"); -INSERT INTO clothes (type, design) - VALUES ("pants", "rainbow tie-dye"); -INSERT INTO clothes (type, design) - VALUES ("blazer", "black sequin"); - -ALTER TABLE clothes ADD price INTEGER; - -SELECT * FROM clothes; +
CREATE TABLE clothes ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
type TEXT, +
design TEXT); +
+
INSERT INTO clothes (type, design) +
VALUES ("dress", "pink polka dots"); +
INSERT INTO clothes (type, design) +
VALUES ("pants", "rainbow tie-dye"); +
INSERT INTO clothes (type, design) +
VALUES ("blazer", "black sequin"); +
+
ALTER TABLE clothes ADD price INTEGER; +
+
SELECT * FROM clothes; ### Step 2 [x] update cloths pricing -CREATE TABLE clothes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - type TEXT, - design TEXT); - -INSERT INTO clothes (type, design) - VALUES ("dress", "pink polka dots"); -INSERT INTO clothes (type, design) - VALUES ("pants", "rainbow tie-dye"); -INSERT INTO clothes (type, design) - VALUES ("blazer", "black sequin"); - -ALTER TABLE clothes ADD price INTEGER; - -SELECT * FROM clothes; - -UPDATE clothes SET price = 10 WHERE id = 1; -UPDATE clothes SET price = 20 WHERE id = 2; -UPDATE clothes SET price = 30 WHERE id = 3; - -SELECT * FROM clothes; - - +
CREATE TABLE clothes ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
type TEXT, +
design TEXT); +
+
INSERT INTO clothes (type, design) +
VALUES ("dress", "pink polka dots"); +
INSERT INTO clothes (type, design) +
VALUES ("pants", "rainbow tie-dye"); +
INSERT INTO clothes (type, design) +
VALUES ("blazer", "black sequin"); +
+
ALTER TABLE clothes ADD price INTEGER; +
+
SELECT * FROM clothes; +
+
UPDATE clothes SET price = 10 WHERE id = 1; +
UPDATE clothes SET price = 20 WHERE id = 2; +
UPDATE clothes SET price = 30 WHERE id = 3; +
+
SELECT * FROM clothes; ### Step 3 [x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. - -CREATE TABLE clothes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - type TEXT, - design TEXT); - -INSERT INTO clothes (type, design) - VALUES ("dress", "pink polka dots"); -INSERT INTO clothes (type, design) - VALUES ("pants", "rainbow tie-dye"); -INSERT INTO clothes (type, design) - VALUES ("blazer", "black sequin"); - -ALTER TABLE clothes ADD price INTEGER; - -SELECT * FROM clothes; - -UPDATE clothes SET price = 10 WHERE id = 1; -UPDATE clothes SET price = 20 WHERE id = 2; -UPDATE clothes SET price = 30 WHERE id = 3; - -SELECT * FROM clothes; - -INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); - -SELECT * FROM clothes; \ No newline at end of file +
+
CREATE TABLE clothes ( +
id INTEGER PRIMARY KEY AUTOINCREMENT, +
type TEXT, +
design TEXT); +
+
INSERT INTO clothes (type, design) +
VALUES ("dress", "pink polka dots"); +
INSERT INTO clothes (type, design) +
VALUES ("pants", "rainbow tie-dye"); +
INSERT INTO clothes (type, design) +
VALUES ("blazer", "black sequin"); +
+
ALTER TABLE clothes ADD price INTEGER; +
+
SELECT * FROM clothes; +
+
UPDATE clothes SET price = 10 WHERE id = 1; +
UPDATE clothes SET price = 20 WHERE id = 2; +
UPDATE clothes SET price = 30 WHERE id = 3; +
+
SELECT * FROM clothes; +
+
INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); + +
SELECT * FROM clothes; \ No newline at end of file From ac73533a6f252595edb9ba6b2cd465bdb0b9b4a2 Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Wed, 17 May 2017 10:50:18 -0700 Subject: [PATCH 3/7] updated read me --- Day 1/{1 SQL Basics.md => 1 SQL Basics.txt} | 0 ... queries.md => 2 Advanced SQL queries.txt} | 0 Day 2/3 Relational Queries.md | 336 ------------------ Day 2/3 Relational Queries.txt | 335 +++++++++++++++++ Day 2/4 Modifying databases with SQL.md | 125 ------- Day 2/4 Modifying databases with SQL.txt | 125 +++++++ README.md | 137 +++---- 7 files changed, 517 insertions(+), 541 deletions(-) rename Day 1/{1 SQL Basics.md => 1 SQL Basics.txt} (100%) rename Day 1/{2 Advanced SQL queries.md => 2 Advanced SQL queries.txt} (100%) delete mode 100644 Day 2/3 Relational Queries.md create mode 100644 Day 2/3 Relational Queries.txt delete mode 100644 Day 2/4 Modifying databases with SQL.md create mode 100644 Day 2/4 Modifying databases with SQL.txt diff --git a/Day 1/1 SQL Basics.md b/Day 1/1 SQL Basics.txt similarity index 100% rename from Day 1/1 SQL Basics.md rename to Day 1/1 SQL Basics.txt diff --git a/Day 1/2 Advanced SQL queries.md b/Day 1/2 Advanced SQL queries.txt similarity index 100% rename from Day 1/2 Advanced SQL queries.md rename to Day 1/2 Advanced SQL queries.txt diff --git a/Day 2/3 Relational Queries.md b/Day 2/3 Relational Queries.md deleted file mode 100644 index dcda50a..0000000 --- a/Day 2/3 Relational Queries.md +++ /dev/null @@ -1,336 +0,0 @@ -# Relational queries in SQL -## Challenge: Bobby's Hobbies -### Step 1 -[x] We've created a database of people and hobbies, and each row in hobbies is related to a row in persons via the person_id column. In this first step, insert one more row in persons and then one more row in hobbies that is related to the newly inserted person. -
-
CREATE TABLE persons ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
name TEXT, -
age INTEGER); -
-
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -
INSERT INTO persons(name, age) VALUES ("Rob C", 26); -
-
CREATE table hobbies ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person_id INTEGER, -
name TEXT); -
-
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); - -### Step 2 -[x] results = persons name next to their hobby -
CREATE TABLE persons ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
name TEXT, -
age INTEGER); -
-
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -
INSERT INTO persons(name, age) VALUES ("Rob C", 26); -
-
CREATE table hobbies ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person_id INTEGER, -
name TEXT); -
-
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); -
-
SELECT persons.name, hobbies.name FROM persons -
JOIN hobbies -
ON persons.id = hobbies.person_id; -
-### Step 3 -[x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. -
-
CREATE TABLE persons ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
name TEXT, -
age INTEGER); -
-
INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); -
INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); -
INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); -
INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); -
INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); -
INSERT INTO persons(name, age) VALUES ("Rob C", 26); -
-
CREATE table hobbies ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person_id INTEGER, -
name TEXT); -
-
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -
INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); -
SELECT persons.name, hobbies.name FROM persons -
JOIN hobbies -
ON persons.id = hobbies.person_id; -
-
SELECT persons.name, hobbies.name FROM persons -
JOIN hobbies -
ON persons.id = hobbies.person_id -
WHERE persons.name = "Bobby McBobbyFace"; -
-## Challenge: Customer's Orders -### Step 1 -[x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. - -CREATE TABLE customers ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT, - email TEXT); - -INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); -INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); -INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); - -CREATE TABLE orders ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - customer_id INTEGER, - item TEXT, - price REAL); - -INSERT INTO orders (customer_id, item, price) - VALUES (1, "Sonic Screwdriver", 1000.00); -INSERT INTO orders (customer_id, item, price) - VALUES (2, "High Quality Broomstick", 40.00); -INSERT INTO orders (customer_id, item, price) - VALUES (1, "TARDIS", 1000000.00); - -SELECT customers.name, customers.email, orders.item, orders.price - FROM customers - LEFT OUTER JOIN orders - ON customers.id = orders.customer_id; - -### Step 2 -[x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. -(Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) -
-
CREATE TABLE customers ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
name TEXT, -
email TEXT); -
-
INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); -
INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); -
INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); -
-
CREATE TABLE orders ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
customer_id INTEGER, -
item TEXT, -
price REAL); -
-
INSERT INTO orders (customer_id, item, price) -
VALUES (1, "Sonic Screwdriver", 1000.00); -
INSERT INTO orders (customer_id, item, price) -
VALUES (2, "High Quality Broomstick", 40.00); -
INSERT INTO orders (customer_id, item, price) -
VALUES (1, "TARDIS", 1000000.00); -
-
SELECT customers.name, customers.email, orders.item, orders.price -
FROM customers -
LEFT OUTER JOIN orders -
ON customers.id = orders.customer_id; -
-
SELECT customers.name, customers.email, SUM(price) AS orders -
FROM customers -
LEFT OUTER JOIN orders -
ON customers.id = orders.customer_id -
GROUP BY name -
ORDER BY price DESC; -
-## Challenge: Sequels in SQL -### Step 1 -[x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). -
-
CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, -
title TEXT, -
released INTEGER, -
sequel_id INTEGER); -
-
INSERT INTO movies -
VALUES (1, "Harry Potter and the Philosopher's Stone", 2001, 2); -
INSERT INTO movies -
VALUES (2, "Harry Potter and the Chamber of Secrets", 2002, 3); -
INSERT INTO movies -
VALUES (3, "Harry Potter and the Prisoner of Azkaban", 2004, 4); -
INSERT INTO movies -
VALUES (4, "Harry Potter and the Goblet of Fire", 2005, 5); -
INSERT INTO movies -
VALUES (5, "Harry Potter and the Order of the Phoenix ", 2007, 6); -
INSERT INTO movies -
VALUES (6, "Harry Potter and the Half-Blood Prince", 2009, 7); -
INSERT INTO movies -
VALUES (7, "Harry Potter and the Deathly Hallows – Part 1", 2010, 8); -
INSERT INTO movies -
VALUES (8, "Harry Potter and the Deathly Hallows – Part 2", 2011, NULL); -
-
SELECT movies.title, sequel.title as sequel -
FROM movies -
LEFT OUTER JOIN movies sequel -
ON movies.sequel_id = sequel.id; -
-## Challenge: FriendBook -### Step 1 -[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. -
-
CREATE TABLE persons ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
fullname TEXT, -
age INTEGER); -
-
INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); -
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); -
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); -
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); -
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); -
-
CREATE table hobbies ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person_id INTEGER, -
name TEXT); -
-
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -
-
CREATE table friends ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person1_id INTEGER, -
person2_id INTEGER); -
-
INSERT INTO friends (person1_id, person2_id) -
VALUES (1, 4); -
INSERT INTO friends (person1_id, person2_id) -
VALUES (2, 3); -
-
SELECT persons.fullname, hobbies.name FROM persons -
JOIN hobbies -
ON persons.id = hobbies.person_id -
; - -### Step 2 -[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. -
-
CREATE TABLE persons ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
fullname TEXT, -
age INTEGER); -
-
INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); -
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); -
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); -
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); -
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); -
-
CREATE table hobbies ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person_id INTEGER, -
name TEXT); -
-
INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); -
INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); -
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); -
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); -
-
CREATE table friends ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
person1_id INTEGER, -
person2_id INTEGER); -
-
INSERT INTO friends (person1_id, person2_id) -
VALUES (1, 4); -
INSERT INTO friends (person1_id, person2_id) -
VALUES (2, 3); -
-
SELECT persons.fullname, hobbies.name FROM persons -
JOIN hobbies -
ON persons.id = hobbies.person_id -
; -
-
SELECT a.fullname, b.fullname -
FROM friends -
JOIN persons a -
ON person1_id = a.id -
JOIN persons b -
ON person2_id = b.id -
; - -## Project: Famous people -[x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. -
-
CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); -
-
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather", 1972, "Drama", "Al Pacino", 9.2); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", "Al Pacino", 9.0); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Dark Knight", 2008, "Action", "Christian Bale", 8.9); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The DArk Knight Rises", 2009, "Action", "Christian Bale", 8.9); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Pulp Fiction", 1994, "Drama", "Samuel L Jackson", 8.9); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", "Elijah Wood", 8.9); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Fight Club", 1999, "Suspense", "Edward Norton", 8.8); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", "Elijah Wood", 8.8); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", "Mark Hammil", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Forrest Gump", 1994, "Drama", "Tom Hanks", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Inception", 2010, "Suspense", "Leonardo DiCaprio", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", "Elijah Wood", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Titanic", 2000, "Drama", "Leonardo DiCaprio", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Matrix", 1999, "Science Fiction", "Keanu Reeves", 8.7); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", "Mark Hammil", 8.6); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("John Wick", 2002, "Action", "Keanu Reeves", 8.6); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Se7en", 1995, "Suspense", "Morgan Freeman", 8.6); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Avengers", 1991, "Suspense", "Samuel L Jackson", 8.6); -
INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon: The Professional", 1994, "Action", "Natalie Portman", 8.5); -
-
SELECT actor FROM top_movies -
GROUP BY actor; diff --git a/Day 2/3 Relational Queries.txt b/Day 2/3 Relational Queries.txt new file mode 100644 index 0000000..eb879eb --- /dev/null +++ b/Day 2/3 Relational Queries.txt @@ -0,0 +1,335 @@ +# Relational queries in SQL +## Challenge: Bobby's Hobbies +### Step 1 +[x] We've created a database of people and hobbies, and each row in hobbies is related to a row in persons via the person_id column. In this first step, insert one more row in persons and then one more row in hobbies that is related to the newly inserted person. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); + +### Step 2 +[x] results = persons name next to their hobby +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); + +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id; + +### Step 3 +[x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + age INTEGER); + +INSERT INTO persons (name, age) VALUES ("Bobby McBobbyFace", 12); +INSERT INTO persons (name, age) VALUES ("Lucy BoBucie", 25); +INSERT INTO persons (name, age) VALUES ("Banana FoFanna", 14); +INSERT INTO persons (name, age) VALUES ("Shish Kabob", 20); +INSERT INTO persons (name, age) VALUES ("Fluffy Sparkles", 8); +INSERT INTO persons(name, age) VALUES ("Rob C", 26); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); +INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id; + +SELECT persons.name, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + WHERE persons.name = "Bobby McBobbyFace"; + +## Challenge: Customer's Orders +### Step 1 +[x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. + +CREATE TABLE customers ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + email TEXT); + +INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); +INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); +INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); + +CREATE TABLE orders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + customer_id INTEGER, + item TEXT, + price REAL); + +INSERT INTO orders (customer_id, item, price) + VALUES (1, "Sonic Screwdriver", 1000.00); +INSERT INTO orders (customer_id, item, price) + VALUES (2, "High Qualityomstick", 40.00); +INSERT INTO orders (customer_id, item, price) + VALUES (1, "TARDIS", 1000000.00); + +SELECT customers.name, customers.email, orders.item, orders.price + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id; + +### Step 2 +[x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. +(Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) + +CREATE TABLE customers ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT, + email TEXT); + +INSERT INTO customers (name, email) VALUES ("Doctor Who", "doctorwho@timelords.com"); +INSERT INTO customers (name, email) VALUES ("Harry Potter", "harry@potter.com"); +INSERT INTO customers (name, email) VALUES ("Captain Awesome", "captain@awesome.com"); + +CREATE TABLE orders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + customer_id INTEGER, + item TEXT, + price REAL); + +INSERT INTO orders (customer_id, item, price) + VALUES (1, "Sonic Screwdriver", 1000.00); +INSERT INTO orders (customer_id, item, price) + VALUES (2, "High Qualityomstick", 40.00); +INSERT INTO orders (customer_id, item, price) + VALUES (1, "TARDIS", 1000000.00); + +SELECT customers.name, customers.email, orders.item, orders.price + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id; + +SELECT customers.name, customers.email, SUM(price) AS orders + FROM customers + LEFT OUTER JOIN orders + ON customers.id = orders.customer_id + GROUP BY name + ORDER BY price DESC; + +## Challenge: Sequels in SQL +### Step 1 +[x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). + +CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + released INTEGER, + sequel_id INTEGER); + +INSERT INTO movies + VALUES (1, "Harry Potter and the Philosopher's Stone", 2001, 2); +INSERT INTO movies + VALUES (2, "Harry Potter and the Chamber of Secrets", 2002, 3); +INSERT INTO movies + VALUES (3, "Harry Potter and the Prisoner of Azkaban", 2004, 4); +INSERT INTO movies + VALUES (4, "Harry Potter and the Goblet of Fire", 2005, 5); +INSERT INTO movies + VALUES (5, "Harry Potter and the Order of the Phoenix ", 2007, 6); +INSERT INTO movies + VALUES (6, "Harry Potter and the Half-Blood Prince", 2009, 7); +INSERT INTO movies + VALUES (7, "Harry Potter and the Deathly Hallows – Part 1", 2010, 8); +INSERT INTO movies + VALUES (8, "Harry Potter and the Deathly Hallows – Part 2", 2011, NULL); + +SELECT movies.title, sequel.title as sequel + FROM movies + LEFT OUTER JOIN movies sequel + ON movies.sequel_id = sequel.id; + +## Challenge: FriendBook +### Step 1 +[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fullname TEXT, + age INTEGER); + +INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); + +CREATE table friends ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person1_id INTEGER, + person2_id INTEGER); + +INSERT INTO friends (person1_id, person2_id) + VALUES (1, 4); +INSERT INTO friends (person1_id, person2_id) + VALUES (2, 3); + +SELECT persons.fullname, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + ; + +### Step 2 +[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + +CREATE TABLE persons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fullname TEXT, + age INTEGER); + +INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12"); +INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25"); +INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14"); +INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20"); +INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8"); + +CREATE table hobbies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person_id INTEGER, + name TEXT); + +INSERT INTO hobbies (person_id, name) VALUES (1, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (1, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (2, "dancing"); +INSERT INTO hobbies (person_id, name) VALUES (2, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (3, "skating"); +INSERT INTO hobbies (person_id, name) VALUES (3, "rowing"); +INSERT INTO hobbies (person_id, name) VALUES (3, "drawing"); +INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); +INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); +INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); + +CREATE table friends ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + person1_id INTEGER, + person2_id INTEGER); + +INSERT INTO friends (person1_id, person2_id) + VALUES (1, 4); +INSERT INTO friends (person1_id, person2_id) + VALUES (2, 3); + +SELECT persons.fullname, hobbies.name FROM persons + JOIN hobbies + ON persons.id = hobbies.person_id + ; + +SELECT a.fullname, b.fullname + FROM friends + JOIN persons a + ON person1_id = a.id + JOIN persons b + ON person2_id = b.id +; + +## Project: Famous people +[x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. + +CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); + +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather", 1972, "Drama", "Al Pacino", 9.2); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Godfather: Part 2", 1974, "Drama", "Al Pacino", 9.0); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Dark Knight", 2008, "Action", "Christian Bale", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The DArk Knight Rises", 2009, "Action", "Christian Bale", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Pulp Fiction", 1994, "Drama", "Samuel L Jackson", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Return of the King", 2003, "Fantasy", "Elijah Wood", 8.9); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Fight Club", 1999, "Suspense", "Edward Norton", 8.8); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: the Fellowship of the Ring", 2001, "Fantasy", "Elijah Wood", 8.8); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode V - The Empire Strikes Back", 1980, "Science Fiction", "Mark Hammil", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Forrest Gump", 1994, "Drama", "Tom Hanks", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Inception", 2010, "Suspense", "Leonardo DiCaprio", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Lord of the Rings: The Two Towers", 2002, "Fantasy", "Elijah Wood", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Titanic", 2000, "Drama", "Leonardo DiCaprio", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("The Matrix", 1999, "Science Fiction", "Keanu Reeves", 8.7); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Star Wars: Episode IV", 1977, "Science Fiction", "Mark Hammil", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("John Wick", 2002, "Action", "Keanu Reeves", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Se7en", 1995, "Suspense", "Morgan Freeman", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Avengers", 1991, "Suspense", "Samuel L Jackson", 8.6); +INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon: The Professional", 1994, "Action", "Natalie Portman", 8.5); + +SELECT actor FROM top_movies +GROUP BY actor; diff --git a/Day 2/4 Modifying databases with SQL.md b/Day 2/4 Modifying databases with SQL.md deleted file mode 100644 index b269819..0000000 --- a/Day 2/4 Modifying databases with SQL.md +++ /dev/null @@ -1,125 +0,0 @@ -# Modifying databases with SQL -## Challenge: Dynamic Documents -### Step 1 -[x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. - -
CREATE table documents ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
title TEXT, -
content TEXT, -
author TEXT); -
-
INSERT INTO documents (author, title, content) -
VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); -
INSERT INTO documents (author, title, content) -
VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); -
-
SELECT * FROM documents; -
UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; -
SELECT * FROM documents; - -### Step 2 -[x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. - -
CREATE table documents ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
title TEXT, -
content TEXT, -
author TEXT); -
-
INSERT INTO documents (author, title, content) -
VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); -
INSERT INTO documents (author, title, content) -
VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); -
INSERT INTO documents (author, title, content) -
VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); -
-
SELECT * FROM documents; -
UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; -
SELECT * FROM documents; -
DELETE FROM documents WHERE title = "Things I'm Afraid Of"; -
SELECT * FROM documents - -## Challenge: Clothing alterations -### Step 1 -[x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. - -
CREATE TABLE clothes ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
type TEXT, -
design TEXT); -
-
INSERT INTO clothes (type, design) -
VALUES ("dress", "pink polka dots"); -
INSERT INTO clothes (type, design) -
VALUES ("pants", "rainbow tie-dye"); -
INSERT INTO clothes (type, design) -
VALUES ("blazer", "black sequin"); -
-
ALTER TABLE clothes ADD price INTEGER; -
-
SELECT * FROM clothes; - -### Step 2 -[x] update cloths pricing - -
CREATE TABLE clothes ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
type TEXT, -
design TEXT); -
-
INSERT INTO clothes (type, design) -
VALUES ("dress", "pink polka dots"); -
INSERT INTO clothes (type, design) -
VALUES ("pants", "rainbow tie-dye"); -
INSERT INTO clothes (type, design) -
VALUES ("blazer", "black sequin"); -
-
ALTER TABLE clothes ADD price INTEGER; -
-
SELECT * FROM clothes; -
-
UPDATE clothes SET price = 10 WHERE id = 1; -
UPDATE clothes SET price = 20 WHERE id = 2; -
UPDATE clothes SET price = 30 WHERE id = 3; -
-
SELECT * FROM clothes; - -### Step 3 -[x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. -
-
CREATE TABLE clothes ( -
id INTEGER PRIMARY KEY AUTOINCREMENT, -
type TEXT, -
design TEXT); -
-
INSERT INTO clothes (type, design) -
VALUES ("dress", "pink polka dots"); -
INSERT INTO clothes (type, design) -
VALUES ("pants", "rainbow tie-dye"); -
INSERT INTO clothes (type, design) -
VALUES ("blazer", "black sequin"); -
-
ALTER TABLE clothes ADD price INTEGER; -
-
SELECT * FROM clothes; -
-
UPDATE clothes SET price = 10 WHERE id = 1; -
UPDATE clothes SET price = 20 WHERE id = 2; -
UPDATE clothes SET price = 30 WHERE id = 3; -
-
SELECT * FROM clothes; -
-
INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); - -
SELECT * FROM clothes; \ No newline at end of file diff --git a/Day 2/4 Modifying databases with SQL.txt b/Day 2/4 Modifying databases with SQL.txt new file mode 100644 index 0000000..25c3c1a --- /dev/null +++ b/Day 2/4 Modifying databases with SQL.txt @@ -0,0 +1,125 @@ +# Modifying databases with SQL +## Challenge: Dynamic Documents +### Step 1 +[x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. + +CREATE table documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + content TEXT, + author TEXT); + +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); + +SELECT * FROM documents; +UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +SELECT * FROM documents; + +### Step 2 +[x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. + +CREATE table documents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + content TEXT, + author TEXT); + +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Fancy Stuff", "Ceiling wax, dragon wings, etc."); +INSERT INTO documents (author, title, content) + VALUES ("Puff T.M. Dragon", "Living Things", "They're located in the left ear, you know."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Pirate Recipes", "Cherry pie, apple pie, blueberry pie."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Boat Supplies", "Rudder - guitar. Main mast - bed post."); +INSERT INTO documents (author, title, content) + VALUES ("Jackie Paper", "Things I'm Afraid Of", "Talking to my parents, the sea, giant pirates, heights."); + +SELECT * FROM documents; +UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; +SELECT * FROM documents; +DELETE FROM documents WHERE title = "Things I'm Afraid Of"; +SELECT * FROM documents + +## Challenge: Clothing alterations +### Step 1 +[x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +### Step 2 +[x] update cloths pricing + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +UPDATE clothes SET price = 10 WHERE id = 1; +UPDATE clothes SET price = 20 WHERE id = 2; +UPDATE clothes SET price = 30 WHERE id = 3; + +SELECT * FROM clothes; + +### Step 3 +[x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. + +CREATE TABLE clothes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type TEXT, + design TEXT); + +INSERT INTO clothes (type, design) + VALUES ("dress", "pink polka dots"); +INSERT INTO clothes (type, design) + VALUES ("pants", "rainbow tie-dye"); +INSERT INTO clothes (type, design) + VALUES ("blazer", "black sequin"); + +ALTER TABLE clothes ADD price INTEGER; + +SELECT * FROM clothes; + +UPDATE clothes SET price = 10 WHERE id = 1; +UPDATE clothes SET price = 20 WHERE id = 2; +UPDATE clothes SET price = 30 WHERE id = 3; + +SELECT * FROM clothes; + +INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); + +SELECT * FROM clothes; \ No newline at end of file diff --git a/README.md b/README.md index eaa225b..f89da32 100644 --- a/README.md +++ b/README.md @@ -1,80 +1,57 @@ -# SQL Exercises - -Exercises to help exercise the SQL muscles. - -Base repository for the [core-sql](http://jsdev.learnersguild.org/goals/178) goal. - -## Getting Started - -Create a Postgres database called `sql_exercises`. Use this database for all of the exercises. - -## Exercises - -Solutions to these exercises can be found in the [`solutions`](https://github.com/GuildCrafts/sql-exercises/tree/solutions) branch. These are here to assist you when you're really stuck, don't overuse them. Remember that there are many ways to solve each of these problems and the [`solutions`](https://github.com/GuildCrafts/sql-exercises/tree/solutions) represents only one option. - -### Build the SQL Schema - -**NOTE:** by schema we mean a set of table definitions **NOT** a [postgresql schema](https://www.postgresql.org/docs/8.2/static/ddl-schemas.html) - -Create the schema for the following tables. - -**01:** Table name: `student`, columns: `id`, `name`, `grade` -- `id` is the primary key -- `name` is only their first name -- `grade` is an integer -- write the SQL in the file `sql/01-create-table-student.sql` - -**02:** Table name: `friend`, columns: `id1`, `id2` -- `id1` is a foreign key reference to a student -- `id2` is a foreign key reference to a student -- write the SQL in the file `sql/02-create-table-friend.sql` - -**03:** Table name: `student_like`, columns: `liker_id`, `likee_id` -- `liker_id` is a foreign key reference to a student -- `likee_id` is a foreign key reference to a student -- write the SQL in the file `sql/03-create-table-like.sql` - -Run the SQL for the schema against the `sql-exercises` database to create the tables. - -### Load the Data - -Load the data into the tables (make sure you have created the tables above). - -**04:** SQL query to load the CSV file `data/students.csv` for the `student` table -
Write the SQL in the file `sql/04-load-table-student.sql` - -**05:** SQL query to load the CSV file `data/friends.csv` for the `friend` table -
Write the query in the file `sql/05-load-table-friend.sql` - -**06:** SQL query to load the CSV file `data/likes.csv` for the `student_like` table -
Write the SQL in the file `sql/06-load-table-like.sql` - -Run the queries to load the data into the tables. - -### Query the Data - -Make sure each question is copied and pasted in the file which contains the SQL, so that it is easy for the reviewer to know what the SQL is supposed to do. - -**07:** Find the names of all students who are friends with someone named Gabriel. -
Write the SQL in the file `sql/07-query-friends-gabriel.sql` - -**08:** For every student who likes someone 2 or more grades younger than themselves, return that student's name and grade, and the name and grade of the student they like. -
Write the SQL in the file `sql/08-query-likes-grade-two-or-more.sql` - -**09:** For every pair of students who both like each other, return the name and grade of both students. Include each pair only once, with the two names in alphabetical order. -
Write the SQL in the file `sql/09-mutual-likes.sql` - -**10:** Find all students who do not appear in the like table (as a student who likes or is liked) and return their names and grades. Sort by grade, then by name within each grade. -
Write the SQL in the file `sql/10-not-liked.sql` - -**11:** For every situation where student A likes student B, but we have no information about whom B likes (that is, B's id does not appear in the `liker_id` column of the like table), return A and B's names and grades. -
Write the SQL in the file `sql/11-liked-but-does-not-like.sql` - -Stretch: **12:** For each student A who likes a student B where the two are not friends, find if they have a friend C in common (who can introduce them!). For all such trios, return the name and grade of A, B, and C. -
Write the SQL in the file `sql/12-find-friends-in-common.sql` - -Stretch: **13:** Find the name and grade of all students who are liked by more than one other student. -
Write the SQL in the file `sql/13-popular-students.sql` - -## Useful Resources -- http://stackoverflow.com/questions/448023/what-is-the-difference-between-left-right-outer-and-inner-joins +# core-sql +- **Name:** Roel Robert Cabrera +- **Github handle:** CabreraRR +- **Team name:** #bulky-moorhen + +### Day 1: SQL Basics & Advanced SQL Queries +- [X] Complete the [SQL Basics course](https://www.khanacademy.org/computing/computer-programming/sql#sql-basics) +- [X] Complete the [Advanced SQL queries course](https://www.khanacademy.org/computing/computer-programming/sql#more-advanced-sql-queries) + +### Day 2: Relational Queries +- [X] Complete the [Relational Queries course](https://www.khanacademy.org/computing/computer-programming/sql#relational-queries-in-sql) +- [X] Complete the [Modifying databases with SQL course](https://www.khanacademy.org/computing/computer-programming/sql#modifying-databases-with-sql) + +### Day 3: Install Postgres and Complete Tutorials with psql +- [X] Install Homebrew by following instructions listed [here](https://gist.github.com/punitrathore/ca32542fddd0d8b625aab610c35e4545) +- [X] Install Postgres by following instructions listed [here](https://gist.github.com/punitrathore/ca32542fddd0d8b625aab610c35e4545#install-postgres) +- [] Learn the `psql` command line tool by working through the following tutorials + - [] complete the tutorial for `createdb` [here](https://www.tutorialspoint.com/postgresql/postgresql_create_database.htm) + - [] complete the tutorial for selecting the database [here](https://www.tutorialspoint.com/postgresql/postgresql_select_database.htm) + - [] complete the tutorial for dropping the database [here](https://www.tutorialspoint.com/postgresql/postgresql_drop_database.htm) + - [] complete the tutorial for `create table` [here](https://www.tutorialspoint.com/postgresql/postgresql_create_table.htm) + - [] complete the tutorial for `drop table` [here](https://www.tutorialspoint.com/postgresql/postgresql_drop_table.htm) + - [] complete the tutorial for `schema` [here](https://www.tutorialspoint.com/postgresql/postgresql_schema.htm) + - [] complete the tutorial for `insert` [here](https://www.tutorialspoint.com/postgresql/postgresql_insert_query.htm) + - [] complete the tutorial for `select` [here](https://www.tutorialspoint.com/postgresql/postgresql_select_query.htm) + - [] complete the tutorial for expressions [here](https://www.tutorialspoint.com/postgresql/postgresql_expressions.htm) + - [] complete the tutorial for `where` clause [here](https://www.tutorialspoint.com/postgresql/postgresql_where_clause.htm) + - [] complete the tutorial for `and` and `or` operators [here](https://www.tutorialspoint.com/postgresql/postgresql_and_or_clauses.htm) + - [] complete the tutorial for update queries [here](https://www.tutorialspoint.com/postgresql/postgresql_update_query.htm) + - [] complete the tutorial for delete queries [here](https://www.tutorialspoint.com/postgresql/postgresql_delete_query.htm) + - [] complete the tutorial for the `like` clause [here](https://www.tutorialspoint.com/postgresql/postgresql_like_clause.htm) + - [] complete the tutorial for the `limit` clause [here](https://www.tutorialspoint.com/postgresql/postgresql_limit_clause.htm) + - [] complete the tutorial for the `order by` clause [here](https://www.tutorialspoint.com/postgresql/postgresql_order_by.htm) + - [] complete the tutorial for the `group by` clause [here](https://www.tutorialspoint.com/postgresql/postgresql_group_by.htm) + +### Day 4: Mini Project & Exercises +- [ ] Exercises 1-13 in the [sql-exercises][sql-exercises] repo are complete and written to the appropriate file: + - [ ] `sql/01-create-table-student.sql` + - [ ] `sql/02-create-table-friend.sql` + - [ ] `sql/03-create-table-like.sql` + - [ ] `sql/04-load-table-learner.sql` + - [ ] `sql/05-load-table-friend.sql` + - [ ] `sql/06-load-table-like.sql` + - [ ] `sql/07-query-friends-gabriel.sql` + - [ ] `sql/08-query-likes-grade-two-or-more.sql` + - [ ] `sql/09-mutual-likes.sql` + - [ ] `sql/10-not-liked.sql` + - [ ] `sql/11-liked-but-does-not-like.sql` + - [ ] `sql/12-find-friends-in-common.sql` + - [ ] `sql/13-popular-students.sql` + +### Day 5: Exercises on SQL Bolt +- [ ] Complete the [SQL Bolt tutorial](https://sqlbolt.com/) + +### Stretch +- [ ] Complete the [Codeacademy course on SQL](https://www.codecademy.com/learn/learn-sql) +- [ ] Complete the [SQL Zoo quizzes](http://sqlzoo.net/wiki/Tutorial_Quizzes) \ No newline at end of file From 4f9b89780ef11f6424cbf4f89980a560a4ee19a0 Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Wed, 17 May 2017 12:20:54 -0700 Subject: [PATCH 4/7] updated markdown files for first 2 days --- Day 1/{1 SQL Basics.txt => 1 SQL Basics.md} | 33 ++++++------ ... queries.txt => 2 Advanced SQL queries.md} | 50 +++++++++++-------- ...al Queries.txt => 3 Relational Queries.md} | 36 +++++++------ ....txt => 4 Modifying databases with SQL.md} | 22 ++++---- 4 files changed, 79 insertions(+), 62 deletions(-) rename Day 1/{1 SQL Basics.txt => 1 SQL Basics.md} (98%) rename Day 1/{2 Advanced SQL queries.txt => 2 Advanced SQL queries.md} (99%) rename Day 2/{3 Relational Queries.txt => 3 Relational Queries.md} (99%) rename Day 2/{4 Modifying databases with SQL.txt => 4 Modifying databases with SQL.md} (98%) diff --git a/Day 1/1 SQL Basics.txt b/Day 1/1 SQL Basics.md similarity index 98% rename from Day 1/1 SQL Basics.txt rename to Day 1/1 SQL Basics.md index 1a0e81c..c90a320 100644 --- a/Day 1/1 SQL Basics.txt +++ b/Day 1/1 SQL Basics.md @@ -1,24 +1,24 @@ # SQL BASICS - +=== ## Challenge: Book list database [x] What are your favorite books? You can make a database table to store them in! In this first step, create a table to store your list of books. It should have columns for id, name, and rating. - +``` CREATE TABLE favorite_books (id INTEGER PRIMARY KEY, name TEXT, rating INTEGER); - +``` [x] Now, add three of your favorite books into the table. - +``` CREATE TABLE favorite_books (id INTEGER PRIMARY KEY, name TEXT, rating INTEGER); INSERT INTO favorite_books VALUES ( 1, "Revelation Space", 10 ); INSERT INTO favorite_books VALUES ( 2, "Harry Potter", 8); INSERT INTO favorite_books VALUES ( 3, "The Godfather", 7); - - +``` +=== ## Challenge: Box office hits database ### Select them all [x] This database contains an incomplete list of box office hits and their release year. In this challenge, you're going to get the results back out of the database in different ways! In this first step, just select all the movies. - +``` CREATE TABLE movies (id INTEGER PRIMARY KEY, name TEXT, release_year INTEGER); INSERT INTO movies VALUES (1, "Avatar", 2009); INSERT INTO movies VALUES (2, "Titanic", 1997); @@ -27,10 +27,10 @@ INSERT INTO movies VALUES (4, "Shrek 2", 2004); INSERT INTO movies VALUES (5, "The Lion King", 1994); INSERT INTO movies VALUES (6, "Disney's Up", 2009); SELECT * FROM movies; - +``` ### Filter recent movies [x] Now, add a second query after the first, that retrieves only the movies that were released in the year 2000 or later, not before. Sort the results so that the earlier movies are - +``` CREATE TABLE movies (id INTEGER PRIMARY KEY, name TEXT, release_year INTEGER); INSERT INTO movies VALUES (1, "Avatar", 2009); INSERT INTO movies VALUES (2, "Titanic", 1997); @@ -40,32 +40,32 @@ INSERT INTO movies VALUES (5, "The Lion King", 1994); INSERT INTO movies VALUES (6, "Disney's Up", 2009); SELECT * FROM movies; SELECT * FROM movies WHERE release_year >= 2000 ORDER BY release_year; - - +``` +=== ## Challenge: TODO list database stats ### Step 1 [x] Here's a table containing a TODO list with the number of minutes it will take to complete each item. Insert another item to your todo list with the estimated minutes it will take - +``` CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); INSERT INTO todo_list VALUES (2, "vacuuming", 20); INSERT INTO todo_list VALUES (3, "Learn some stuff on KA", 30); INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); - +``` ### Step 2 [x] Select the SUM of minutes it will take to do all of the items on your TODO list. You should only have one SELECT statement. - +``` CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); INSERT INTO todo_list VALUES (2, "vacuuming", 20); INSERT INTO todo_list VALUES (3, "Learn some stuff on KA", 30); INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); SELECT SUM(minutes) FROM todo_list; - +``` ## Project: Design a store database [x] Create your own store! Your store should sell one type of things, like clothing or bikes, whatever you want your store to specialize in. You should have a table for all the items in your store, and at least 5 columns for the kind of data you think you'd need to store. You should sell at least 15 items, and use select statements to order your items by price and show at least one statistic about the items. - +``` CREATE TABLE wow_chars(id INTEGER, class TEXT, spec TEXT, race TEXT, cost INTEGER); INSERT INTO wow_chars VALUES(1, "Paladin", "Protection", "Tauren", 500); INSERT INTO wow_chars VALUES(1, "Paladin", "Holy", "Blood-Elf", 350); @@ -83,3 +83,4 @@ INSERT INTO wow_chars VALUES(1, "Druid", "Feral", "Orc", 200); INSERT INTO wow_chars VALUES(1, "Warrior", "Arms", "Blood-Elf", 200); INSERT INTO wow_chars VALUES(1, "Deathknight", "Frost", "Goblin", 200); SELECT class, cost FROM wow_chars ORDER BY cost; +``` \ No newline at end of file diff --git a/Day 1/2 Advanced SQL queries.txt b/Day 1/2 Advanced SQL queries.md similarity index 99% rename from Day 1/2 Advanced SQL queries.txt rename to Day 1/2 Advanced SQL queries.md index 7b82f0c..cb80ec6 100644 --- a/Day 1/2 Advanced SQL queries.txt +++ b/Day 1/2 Advanced SQL queries.md @@ -3,7 +3,7 @@ ## Challenge: Karaoke song selector ### Step 1 [x] Ever sung karaoke? It's a place where you sing songs with your friends, and it's a lot of fun. We've created a table with songs, and in this challenge, you'll use queries to decide what songs to sing. For the first step, select all the song titles. - +``` CREATE TABLE songs ( id INTEGER PRIMARY KEY, title TEXT, @@ -30,10 +30,11 @@ INSERT INTO songs (title, artist, mood, duration, released) VALUES ("Call me maybe", "Carly Rae Jepsen", "happy", 193, 2011); SELECT title FROM songs; - +``` +=== ### Step 2 [x]epic song released after 1990 - +``` CREATE TABLE songs ( id INTEGER PRIMARY KEY, title TEXT, @@ -61,11 +62,12 @@ INSERT INTO songs (title, artist, mood, duration, released) SELECT title FROM songs; SELECT title FROM songs WHERE mood = "epic" OR released > 1989; - +``` +=== ### Step 3 [x]People get picky at the end of the night. Add another SELECT that uses AND to show the titles of songs that are 'epic', and released after 1990, and less than 4 minutes long. Note that the duration column is measured in seconds. - +``` CREATE TABLE songs ( id INTEGER PRIMARY KEY, title TEXT, @@ -94,11 +96,12 @@ INSERT INTO songs (title, artist, mood, duration, released) SELECT title FROM songs; SELECT title FROM songs WHERE mood = "epic" OR released > 1989; SELECT title From songs WHERE mood = "epic" AND released > 1989 AND duration < 240; - +``` +=== ## Challenge: Playlist maker ### Step 1 [x] We've created a database of songs and artists, and you'll make playlists from them in this challenge. In this first step, select the title of all the songs by the artist named 'Queen'. - +``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -159,10 +162,10 @@ INSERT INTO songs (artist, title) VALUES ("Guns N' Roses", "Don't cry"); SELECT title FROM songs WHERE artist="Queen"; - +``` ### Step 2 [x] pop genre - +``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -224,10 +227,10 @@ INSERT INTO songs (artist, title) SELECT title FROM songs WHERE artist="Queen"; SELECT name FROM artists WHERE genre ="Pop"; - +``` ### Step 3 [x] To finish creating the 'Pop' playlist, add another query that will select the title of all the songs from the 'Pop' artists. It should use IN on a nested subquery that's based on your previous query. - +``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -290,11 +293,12 @@ INSERT INTO songs (artist, title) SELECT title FROM songs WHERE artist="Queen"; SELECT name FROM artists WHERE genre ="Pop"; SELECT title FROM songs WHERE artist IN (SELECT name From artists WHERE genre = "Pop"); - +``` +=== ## Challenge: The wordiest author ### Step 1 [x] We've created a database of a few popular authors and their books, with word counts for each book. In this first step, select all the authors who have written more than 1 million words, using GROUP BY and HAVING. Your results table should include the 'author' and their total word count as a 'total_words' column. - +``` CREATE TABLE books ( id INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT, @@ -338,10 +342,10 @@ SELECT author, SUM(words) AS total_words FROM books GROUP BY author HAVING total_words > 1000000 ; - +``` ### Step 2 [x] Now select all the authors that write more than an average of 150,000 words per book. Your results table should include the 'author' and average words as an 'avg_words' column. - +``` CREATE TABLE books ( id INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT, @@ -389,10 +393,12 @@ SELECT author, AVG(words) AS avg_words FROM books GROUP BY author HAVING avg_words > 150000 ; +``` +=== ## Challenge: Gradebook ### Step 1 [x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. - +``` CREATE TABLE student_grades ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -413,10 +419,10 @@ INSERT INTO student_grades (name, number_grade, fraction_completed) VALUES ("Winstonia", 82, 0.9045); SELECT name, number_grade, ROUND(fraction_completed*100) AS percent_completed FROM student_grades; - +``` ### Step 2 [x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. - +``` CREATE TABLE student_grades ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -447,11 +453,12 @@ SELECT COUNT(*), END AS "letter_grade" FROM student_grades GROUP BY letter_grade; - +``` +=== ## Project Data dig [x] We’ve curated a set of interesting data sets for you: Top movies, Top countries by population, Solar system objects by size, Marvel characters, Furniture store sales, Earned KA badges, Winston's donut logs, Card game results, and NFL draft picks. Pick one of those data sets or create a data set like that, and use advanced SELECT queries to discover things about the data. What sort of questions might one have about that data, like if they were using it for an app or a business idea? Here are some ideas: - +``` CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, rating INTEGER); INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("Shawshank Redemption", 1994, "Drama", 9.2); INSERT INTO top_movies (name, year_released, genre, rating) VALUES ("The Godfather", 1972, "Drama", 9.2); @@ -484,4 +491,5 @@ SELECT COUNT(*), END AS "year_group" FROM top_movies GROUP BY year_group; -SELECT genre, AVG(rating) AS avg_rating FROM top_movies GROUP BY genre; \ No newline at end of file +SELECT genre, AVG(rating) AS avg_rating FROM top_movies GROUP BY genre; +``` \ No newline at end of file diff --git a/Day 2/3 Relational Queries.txt b/Day 2/3 Relational Queries.md similarity index 99% rename from Day 2/3 Relational Queries.txt rename to Day 2/3 Relational Queries.md index eb879eb..b375403 100644 --- a/Day 2/3 Relational Queries.txt +++ b/Day 2/3 Relational Queries.md @@ -2,7 +2,7 @@ ## Challenge: Bobby's Hobbies ### Step 1 [x] We've created a database of people and hobbies, and each row in hobbies is related to a row in persons via the person_id column. In this first step, insert one more row in persons and then one more row in hobbies that is related to the newly inserted person. - +``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -31,9 +31,10 @@ INSERT INTO hobbies (person_id, name) VALUES (4, "coding"); INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying"); INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); - +``` ### Step 2 [x] results = persons name next to their hobby +``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -66,9 +67,10 @@ INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); SELECT persons.name, hobbies.name FROM persons JOIN hobbies ON persons.id = hobbies.person_id; - +``` ### Step 3 [x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. +``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -105,11 +107,12 @@ SELECT persons.name, hobbies.name FROM persons JOIN hobbies ON persons.id = hobbies.person_id WHERE persons.name = "Bobby McBobbyFace"; - +``` +=== ## Challenge: Customer's Orders ### Step 1 [x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. - +``` CREATE TABLE customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -136,11 +139,11 @@ SELECT customers.name, customers.email, orders.item, orders.price FROM customers LEFT OUTER JOIN orders ON customers.id = orders.customer_id; - +``` ### Step 2 [x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. (Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) - +``` CREATE TABLE customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, @@ -174,11 +177,12 @@ SELECT customers.name, customers.email, SUM(price) AS orders ON customers.id = orders.customer_id GROUP BY name ORDER BY price DESC; - +``` +=== ## Challenge: Sequels in SQL ### Step 1 [x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). - +``` CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, released INTEGER, @@ -205,11 +209,11 @@ SELECT movies.title, sequel.title as sequel FROM movies LEFT OUTER JOIN movies sequel ON movies.sequel_id = sequel.id; - +``` ## Challenge: FriendBook ### Step 1 [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. - +``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, fullname TEXT, @@ -251,10 +255,10 @@ SELECT persons.fullname, hobbies.name FROM persons JOIN hobbies ON persons.id = hobbies.person_id ; - +``` ### Step 2 [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. - +``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, fullname TEXT, @@ -304,10 +308,11 @@ SELECT a.fullname, b.fullname JOIN persons b ON person2_id = b.id ; - +``` +=== ## Project: Famous people [x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. - +``` CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Shawshank Redemption", 1994, "Drama", "Morgan Freeman", 9.2); @@ -333,3 +338,4 @@ INSERT INTO top_movies (name, year_released, genre, actor, rating) VALUES ("Leon SELECT actor FROM top_movies GROUP BY actor; +``` \ No newline at end of file diff --git a/Day 2/4 Modifying databases with SQL.txt b/Day 2/4 Modifying databases with SQL.md similarity index 98% rename from Day 2/4 Modifying databases with SQL.txt rename to Day 2/4 Modifying databases with SQL.md index 25c3c1a..2d2fe43 100644 --- a/Day 2/4 Modifying databases with SQL.txt +++ b/Day 2/4 Modifying databases with SQL.md @@ -2,7 +2,7 @@ ## Challenge: Dynamic Documents ### Step 1 [x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. - +``` CREATE table documents ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, @@ -23,10 +23,10 @@ INSERT INTO documents (author, title, content) SELECT * FROM documents; UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; SELECT * FROM documents; - +``` ### Step 2 [x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. - +``` CREATE table documents ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, @@ -49,11 +49,12 @@ UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; SELECT * FROM documents; DELETE FROM documents WHERE title = "Things I'm Afraid Of"; SELECT * FROM documents - +``` +=== ## Challenge: Clothing alterations ### Step 1 [x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. - +``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, @@ -69,10 +70,10 @@ INSERT INTO clothes (type, design) ALTER TABLE clothes ADD price INTEGER; SELECT * FROM clothes; - +``` ### Step 2 [x] update cloths pricing - +``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, @@ -94,10 +95,10 @@ UPDATE clothes SET price = 20 WHERE id = 2; UPDATE clothes SET price = 30 WHERE id = 3; SELECT * FROM clothes; - +``` ### Step 3 [x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. - +``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, @@ -122,4 +123,5 @@ SELECT * FROM clothes; INSERT INTO clothes (type, design, price) VALUES ("taco", "carne asada", 1); -SELECT * FROM clothes; \ No newline at end of file +SELECT * FROM clothes; +``` \ No newline at end of file From 1a3dcabea0755b1e8059988568a4ce6097325cde Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Thu, 18 May 2017 08:28:31 -0700 Subject: [PATCH 5/7] updated md files in Day 1 and Day 2 --- .DS_Store | Bin 0 -> 6148 bytes Day 1/1 SQL Basics.md | 1 - Day 2/3 Relational Queries.sublime-workspace | 164 +++++++++++++++++++ sql/01-create-table-student.sql | 5 + sql/02-create-table-friend.sql | 4 + sql/03-create-table-like.sql | 4 + 6 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 .DS_Store create mode 100644 Day 2/3 Relational Queries.sublime-workspace diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..6707c6300d1d5527602aeabf613ef8062803f80d GIT binary patch literal 6148 zcmeHK-A)rh6h6}y*^M#w!UQh&#)J!ET5Q0?m@K8e;DW?hqZdM8*KK5zWe2-kno>&k z#)r^1;8A=69>fRGZ+@(F(Qro$oRiFaXU=?QCiBf^W`~GGdl)r|>O|zAD6F`s{$i?M zm1|b9kwu_TV{9k#W0=SgZ8ad<|F3}ByBb9lP)(SCh-GI_DyTJ>73#&p%2Y-}{(KVP3t9cSrj z^VRmj(fD+7Ha-7p_Cnx8)%MupZ}xL>K72D$yV2 z+B{P%m6$HQp)PG=G%)-7$SzHyVgTFKvAZ6g~3@09DNmotFGc@6m5um$^rTo3xkNj_(wp?z!fWS Hs|x%AarcR2 literal 0 HcmV?d00001 diff --git a/Day 1/1 SQL Basics.md b/Day 1/1 SQL Basics.md index c90a320..a50142b 100644 --- a/Day 1/1 SQL Basics.md +++ b/Day 1/1 SQL Basics.md @@ -1,5 +1,4 @@ # SQL BASICS -=== ## Challenge: Book list database [x] What are your favorite books? You can make a database table to store them in! In this first step, create a table to store your list of books. It should have columns for id, name, and rating. diff --git a/Day 2/3 Relational Queries.sublime-workspace b/Day 2/3 Relational Queries.sublime-workspace new file mode 100644 index 0000000..bf53fbf --- /dev/null +++ b/Day 2/3 Relational Queries.sublime-workspace @@ -0,0 +1,164 @@ +{ + "auto_complete": + { + "selected_items": + [ + ] + }, + "buffers": + [ + ], + "build_system": "", + "build_system_choices": + [ + ], + "build_varint": "", + "command_palette": + { + "height": 359.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 485.0 + }, + "console": + { + "height": 0.0, + "history": + [ + ] + }, + "distraction_free": + { + "menu_visible": true, + "show_minimap": false, + "show_open_files": false, + "show_tabs": false, + "side_bar_visible": false, + "status_bar_visible": false + }, + "file_history": + [ + ], + "find": + { + "height": 0.0 + }, + "find_in_files": + { + "height": 0.0, + "where_history": + [ + ] + }, + "find_state": + { + "case_sensitive": false, + "find_history": + [ + ], + "highlight": true, + "in_selection": false, + "preserve_case": false, + "regex": false, + "replace_history": + [ + ], + "reverse": false, + "show_context": true, + "use_buffer2": true, + "whole_word": false, + "wrap": true + }, + "groups": + [ + { + "sheets": + [ + ] + } + ], + "incremental_find": + { + "height": 0.0 + }, + "input": + { + "height": 0.0 + }, + "layout": + { + "cells": + [ + [ + 0, + 0, + 1, + 1 + ] + ], + "cols": + [ + 0.0, + 1.0 + ], + "rows": + [ + 0.0, + 1.0 + ] + }, + "menu_visible": true, + "output.find_results": + { + "height": 0.0 + }, + "pinned_build_system": "", + "project": "3 Relational Queries.sublime-project", + "replace": + { + "height": 0.0 + }, + "save_all_on_build": true, + "select_file": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 0.0 + }, + "select_project": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 0.0 + }, + "select_symbol": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 0.0 + }, + "selected_group": 0, + "settings": + { + }, + "show_minimap": true, + "show_open_files": false, + "show_tabs": true, + "side_bar_visible": true, + "side_bar_width": 150.0, + "status_bar_visible": true, + "template_settings": + { + } +} diff --git a/sql/01-create-table-student.sql b/sql/01-create-table-student.sql index e69de29..a86bc53 100644 --- a/sql/01-create-table-student.sql +++ b/sql/01-create-table-student.sql @@ -0,0 +1,5 @@ +CREATE TABLE student ( + id INTEGER PRIMARY KEY, + name TEXT, + grade INTEGER) + ; diff --git a/sql/02-create-table-friend.sql b/sql/02-create-table-friend.sql index e69de29..56aaf23 100644 --- a/sql/02-create-table-friend.sql +++ b/sql/02-create-table-friend.sql @@ -0,0 +1,4 @@ +CREATE TABLE friend ( + id1 INTEGER, + id2 INTEGER) + ; diff --git a/sql/03-create-table-like.sql b/sql/03-create-table-like.sql index e69de29..0c91bed 100644 --- a/sql/03-create-table-like.sql +++ b/sql/03-create-table-like.sql @@ -0,0 +1,4 @@ +CREATE TABLE student_like ( + liker_id INTEGER, + likee_id INTEGER) + ; From 17f029332cf0557391c8992f7ff5d3f5521e7aae Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Thu, 18 May 2017 12:26:30 -0700 Subject: [PATCH 6/7] updated file location and documentation --- .DS_Store | Bin 6148 -> 6148 bytes Day 2/3 Relational Queries.sublime-workspace | 164 ----- README.md | 69 +- {Day 1 => khan-academy}/1 SQL Basics.md | 18 +- .../2 Advanced SQL queries.md | 26 +- .../3 Relational Queries.md | 18 +- .../4 Modifying databases with SQL.md | 10 +- psql/psql.md | 601 ++++++++++++++++++ sql/01-create-table-student.sql | 10 + sql/02-create-table-friend.sql | 9 + sql/03-create-table-like.sql | 8 + sql/04-load-table-student.sql | 7 + sql/05-load-table-friend.sql | 6 + sql/06-load-table-like.sql | 6 + sql/07-query-friends-gabriel.sql | 12 + sql/08-query-likes-grade-two-or-more.sql | 11 + sql/09-mutual-likes.sql | 22 + sql/10-not-liked.sql | 8 + sql/11-liked-but-does-not-like.sql | 12 + sql/12-find-friends-in-common.sql | 4 + sql/13-popular-students.sql | 4 + 21 files changed, 791 insertions(+), 234 deletions(-) delete mode 100644 Day 2/3 Relational Queries.sublime-workspace rename {Day 1 => khan-academy}/1 SQL Basics.md (70%) rename {Day 1 => khan-academy}/2 Advanced SQL queries.md (89%) rename {Day 2 => khan-academy}/3 Relational Queries.md (88%) rename {Day 2 => khan-academy}/4 Modifying databases with SQL.md (80%) create mode 100644 psql/psql.md diff --git a/.DS_Store b/.DS_Store index 6707c6300d1d5527602aeabf613ef8062803f80d..57b12d646c2a306a0925fa9a77346c272ad721ce 100644 GIT binary patch delta 269 zcmZoMXfc=|#>B!ku~2NHo+2af#(>?7i$5?kG4gKaVbWt1HTKNOPfp6oPhwzT5CCFp zAf7SVpINltxGcCRFDE}Q9Vo&G#4HR248;tE3^_UJhQZ1CxdlKm7=X*==DWD0l$Inj zFkE$BS__s&l1srUSCD~jrWnFPWQR;{WR4bQhByRSeDg!*1&o{7Iruq%o&|EgGf(Ch RapV9xoC)NL%@HDNm;uYnJ(K_d delta 127 zcmZoMXfc=|#>B)qu~2NHo+2ar#(>?7jO?3vSo9c04Lx)6laq4tlNcBn1b}!Y5Nk~K zXBCw-LX}|@2g&>g0|ti4KUt$Ui*X3DOl*+a%+A5j0W^NIAjfy+$^0UY96*%}j0_Ac Kn= 2000 ORDER BY release_year; ``` -=== + ## Challenge: TODO list database stats ### Step 1 -[x] Here's a table containing a TODO list with the number of minutes it will take to complete each item. Insert another item to your todo list with the estimated minutes it will take + [x] Here's a table containing a TODO list with the number of minutes it will take to complete each item. Insert another item to your todo list with the estimated minutes it will take ``` CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); @@ -53,7 +53,7 @@ INSERT INTO todo_list VALUES (3, "Learn some stuff on KA", 30); INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); ``` ### Step 2 -[x] Select the SUM of minutes it will take to do all of the items on your TODO list. You should only have one SELECT statement. + [x] Select the SUM of minutes it will take to do all of the items on your TODO list. You should only have one SELECT statement. ``` CREATE TABLE todo_list (id INTEGER PRIMARY KEY, item TEXT, minutes INTEGER); INSERT INTO todo_list VALUES (1, "Wash the dishes", 15); @@ -63,7 +63,7 @@ INSERT INTO todo_list VALUES(4, "Get jiggy with it", 10); SELECT SUM(minutes) FROM todo_list; ``` ## Project: Design a store database -[x] Create your own store! Your store should sell one type of things, like clothing or bikes, whatever you want your store to specialize in. You should have a table for all the items in your store, and at least 5 columns for the kind of data you think you'd need to store. You should sell at least 15 items, and use select statements to order your items by price and show at least one statistic about the items. + [x] Create your own store! Your store should sell one type of things, like clothing or bikes, whatever you want your store to specialize in. You should have a table for all the items in your store, and at least 5 columns for the kind of data you think you'd need to store. You should sell at least 15 items, and use select statements to order your items by price and show at least one statistic about the items. ``` CREATE TABLE wow_chars(id INTEGER, class TEXT, spec TEXT, race TEXT, cost INTEGER); INSERT INTO wow_chars VALUES(1, "Paladin", "Protection", "Tauren", 500); diff --git a/Day 1/2 Advanced SQL queries.md b/khan-academy/2 Advanced SQL queries.md similarity index 89% rename from Day 1/2 Advanced SQL queries.md rename to khan-academy/2 Advanced SQL queries.md index cb80ec6..defb9cb 100644 --- a/Day 1/2 Advanced SQL queries.md +++ b/khan-academy/2 Advanced SQL queries.md @@ -2,7 +2,7 @@ ## Challenge: Karaoke song selector ### Step 1 -[x] Ever sung karaoke? It's a place where you sing songs with your friends, and it's a lot of fun. We've created a table with songs, and in this challenge, you'll use queries to decide what songs to sing. For the first step, select all the song titles. + [x] Ever sung karaoke? It's a place where you sing songs with your friends, and it's a lot of fun. We've created a table with songs, and in this challenge, you'll use queries to decide what songs to sing. For the first step, select all the song titles. ``` CREATE TABLE songs ( id INTEGER PRIMARY KEY, @@ -31,9 +31,9 @@ INSERT INTO songs (title, artist, mood, duration, released) SELECT title FROM songs; ``` -=== + ### Step 2 -[x]epic song released after 1990 + [x]epic song released after 1990 ``` CREATE TABLE songs ( id INTEGER PRIMARY KEY, @@ -63,9 +63,9 @@ INSERT INTO songs (title, artist, mood, duration, released) SELECT title FROM songs; SELECT title FROM songs WHERE mood = "epic" OR released > 1989; ``` -=== + ### Step 3 -[x]People get picky at the end of the night. Add another SELECT that uses AND to show the titles of songs that are 'epic', and released after 1990, and less than 4 minutes long. + [x]People get picky at the end of the night. Add another SELECT that uses AND to show the titles of songs that are 'epic', and released after 1990, and less than 4 minutes long. Note that the duration column is measured in seconds. ``` CREATE TABLE songs ( @@ -100,7 +100,7 @@ SELECT title From songs WHERE mood = "epic" AND released > 1989 AND duration < 2 === ## Challenge: Playlist maker ### Step 1 -[x] We've created a database of songs and artists, and you'll make playlists from them in this challenge. In this first step, select the title of all the songs by the artist named 'Queen'. + [x] We've created a database of songs and artists, and you'll make playlists from them in this challenge. In this first step, select the title of all the songs by the artist named 'Queen'. ``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -164,7 +164,7 @@ INSERT INTO songs (artist, title) SELECT title FROM songs WHERE artist="Queen"; ``` ### Step 2 -[x] pop genre + [x] pop genre ``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -229,7 +229,7 @@ SELECT title FROM songs WHERE artist="Queen"; SELECT name FROM artists WHERE genre ="Pop"; ``` ### Step 3 -[x] To finish creating the 'Pop' playlist, add another query that will select the title of all the songs from the 'Pop' artists. It should use IN on a nested subquery that's based on your previous query. + [x] To finish creating the 'Pop' playlist, add another query that will select the title of all the songs from the 'Pop' artists. It should use IN on a nested subquery that's based on your previous query. ``` CREATE TABLE artists ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -297,7 +297,7 @@ SELECT title FROM songs WHERE artist IN (SELECT name From artists WHERE genre = === ## Challenge: The wordiest author ### Step 1 -[x] We've created a database of a few popular authors and their books, with word counts for each book. In this first step, select all the authors who have written more than 1 million words, using GROUP BY and HAVING. Your results table should include the 'author' and their total word count as a 'total_words' column. + [x] We've created a database of a few popular authors and their books, with word counts for each book. In this first step, select all the authors who have written more than 1 million words, using GROUP BY and HAVING. Your results table should include the 'author' and their total word count as a 'total_words' column. ``` CREATE TABLE books ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -344,7 +344,7 @@ HAVING total_words > 1000000 ; ``` ### Step 2 -[x] Now select all the authors that write more than an average of 150,000 words per book. Your results table should include the 'author' and average words as an 'avg_words' column. + [x] Now select all the authors that write more than an average of 150,000 words per book. Your results table should include the 'author' and average words as an 'avg_words' column. ``` CREATE TABLE books ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -397,7 +397,7 @@ HAVING avg_words > 150000 === ## Challenge: Gradebook ### Step 1 -[x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. + [x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. ``` CREATE TABLE student_grades ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -421,7 +421,7 @@ INSERT INTO student_grades (name, number_grade, fraction_completed) SELECT name, number_grade, ROUND(fraction_completed*100) AS percent_completed FROM student_grades; ``` ### Step 2 -[x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. + [x] We've created a database to track student grades, with their name, number grade, and what percent of activities they've completed. In this first step, select all of the rows, and display the name, number_grade, and percent_completed, which you can compute by multiplying and rounding the fraction_completed column. ``` CREATE TABLE student_grades ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -456,7 +456,7 @@ GROUP BY letter_grade; ``` === ## Project Data dig -[x] We’ve curated a set of interesting data sets for you: Top movies, Top countries by population, Solar system objects by size, Marvel characters, Furniture store sales, Earned KA badges, Winston's donut logs, Card game results, and NFL draft picks. + [x] We’ve curated a set of interesting data sets for you: Top movies, Top countries by population, Solar system objects by size, Marvel characters, Furniture store sales, Earned KA badges, Winston's donut logs, Card game results, and NFL draft picks. Pick one of those data sets or create a data set like that, and use advanced SELECT queries to discover things about the data. What sort of questions might one have about that data, like if they were using it for an app or a business idea? Here are some ideas: ``` CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, rating INTEGER); diff --git a/Day 2/3 Relational Queries.md b/khan-academy/3 Relational Queries.md similarity index 88% rename from Day 2/3 Relational Queries.md rename to khan-academy/3 Relational Queries.md index b375403..1b5626b 100644 --- a/Day 2/3 Relational Queries.md +++ b/khan-academy/3 Relational Queries.md @@ -33,7 +33,7 @@ INSERT INTO hobbies (person_id, name) VALUES (4, "meowing"); INSERT INTO hobbies (person_id, name) VALUES (6, "WoW"); ``` ### Step 2 -[x] results = persons name next to their hobby + [x] results = persons name next to their hobby ``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -69,7 +69,7 @@ SELECT persons.name, hobbies.name FROM persons ON persons.id = hobbies.person_id; ``` ### Step 3 -[x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. + [x] Now, add an additional query that shows only the name and hobbies of 'Bobby McBobbyFace', using JOIN combined with WHERE. ``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -111,7 +111,7 @@ SELECT persons.name, hobbies.name FROM persons === ## Challenge: Customer's Orders ### Step 1 -[x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. + [x] We've created a database for customers and their orders. Not all of the customers have made orders, however. Come up with a query that lists the name and email of every customer followed by the item and price of orders they've made. Use a LEFT OUTER JOIN so that a customer is listed even if they've made no orders, and don't add any ORDER BY. ``` CREATE TABLE customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -141,7 +141,7 @@ SELECT customers.name, customers.email, orders.item, orders.price ON customers.id = orders.customer_id; ``` ### Step 2 -[x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. + [x] Now, create another query that will result in one row per each customer, with their name, email, and total amount of money they've spent on orders. Sort the rows according to the total money spent, from the most spent to the least spent. (Tip: You should always GROUP BY on the column that is most likely to be unique in a row.) ``` CREATE TABLE customers ( @@ -181,7 +181,7 @@ SELECT customers.name, customers.email, SUM(price) AS orders === ## Challenge: Sequels in SQL ### Step 1 -[x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). + [x] We've created a table with all the 'Harry Potter' movies, with a sequel_id column that matches the id of the sequel for each movie. Issue a SELECT that will show the title of each movie next to its sequel's title (or NULL if it doesn't have a sequel). ``` CREATE TABLE movies (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, @@ -212,7 +212,7 @@ SELECT movies.title, sequel.title as sequel ``` ## Challenge: FriendBook ### Step 1 -[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. ``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -257,7 +257,7 @@ SELECT persons.fullname, hobbies.name FROM persons ; ``` ### Step 2 -[x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. + [x] We've created a database for a friend networking site, with a table storing data on each person, a table on each person's hobbies, and a table of friend connections between the people. In this first step, use a JOIN to display a table showing people's names with their hobbies. ``` CREATE TABLE persons ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -309,9 +309,9 @@ SELECT a.fullname, b.fullname ON person2_id = b.id ; ``` -=== + ## Project: Famous people -[x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. + [x] In this project, you’re going to make your own table with some small set of “famous people”, then make more tables about things they do and join those to create nice human readable lists. ``` CREATE TABLE top_movies (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, year_released INTEGER, genre TEXT, actor TEXT, rating INTEGER); diff --git a/Day 2/4 Modifying databases with SQL.md b/khan-academy/4 Modifying databases with SQL.md similarity index 80% rename from Day 2/4 Modifying databases with SQL.md rename to khan-academy/4 Modifying databases with SQL.md index 2d2fe43..024b7f4 100644 --- a/Day 2/4 Modifying databases with SQL.md +++ b/khan-academy/4 Modifying databases with SQL.md @@ -1,7 +1,7 @@ # Modifying databases with SQL ## Challenge: Dynamic Documents ### Step 1 -[x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. + [x] We've created a database for a documents app, with rows for each document with it's title, content, and author. In this first step, use UPDATE to change the author to 'Jackie Draper' for all rows where it's currently 'Jackie Paper'. Then re-select all the rows to make sure the table changed like you expected. ``` CREATE table documents ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -25,7 +25,7 @@ UPDATE documents SET content = "Jackie Draper" WHERE author = "Jackie Paper"; SELECT * FROM documents; ``` ### Step 2 -[x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. + [x] Now you'll delete a row, being very careful not to delete all the rows. Only delete the row where the title is 'Things I'm Afraid Of'. Then re-select all the rows to make sure the table changed like you expected. ``` CREATE table documents ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -53,7 +53,7 @@ SELECT * FROM documents === ## Challenge: Clothing alterations ### Step 1 -[x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. + [x] We've created a database of clothes, and decided we need a price column. Use ALTER to add a 'price' column to the table. Then select all the columns in each row to see what your table looks like now. ``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -72,7 +72,7 @@ ALTER TABLE clothes ADD price INTEGER; SELECT * FROM clothes; ``` ### Step 2 -[x] update cloths pricing + [x] update cloths pricing ``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -97,7 +97,7 @@ UPDATE clothes SET price = 30 WHERE id = 3; SELECT * FROM clothes; ``` ### Step 3 -[x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. + [x] Now insert a new item into the table that has all three attributes filled in, including 'price'. Do one final SELECT of all the rows to check it worked. ``` CREATE TABLE clothes ( id INTEGER PRIMARY KEY AUTOINCREMENT, diff --git a/psql/psql.md b/psql/psql.md new file mode 100644 index 0000000..1f25574 --- /dev/null +++ b/psql/psql.md @@ -0,0 +1,601 @@ +# postgrs.sql +## Create Database +SQL Command +``` +psql +CREATE DATABASE testdb; +``` + Results + ``` +hellaboredguy=# CREATE DATABASE testdb; +CREATE DATABASE +hellaboredguy=# \l + List of databases + Name | Owner | Encoding | Collate | Ctype | Access privileges +---------------+---------------+----------+-------------+-------------+--------------------------------- + dbname | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + hellaboredguy | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + postgres | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + template0 | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/hellaboredguy + + | | | | | hellaboredguy=CTc/hellaboredguy + template1 | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/hellaboredguy + + | | | | | hellaboredguy=CTc/hellaboredguy + testdb | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | +(6 rows) + + ``` + +## Selecting the Database +SQL Command +``` +\c testdb +``` + +Results +``` +hellaboredguy=# \c testdb +You are now connected to database "testdb" as user "hellaboredguy". +``` + +## Dropping the Database +SQL Command +``` +dropdb -h localhost -p 5432 -U postgress testdb +``` + +Results +``` +hellaboredguy=# DROP DATABASE testdb; +DROP DATABASE +hellaboredguy=# \l + List of databases + Name | Owner | Encoding | Collate | Ctype | Access privileges +---------------+---------------+----------+-------------+-------------+--------------------------------- + dbname | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + hellaboredguy | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + postgres | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | + template0 | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/hellaboredguy + + | | | | | hellaboredguy=CTc/hellaboredguy + template1 | hellaboredguy | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/hellaboredguy + + | | | | | hellaboredguy=CTc/hellaboredguy +(5 rows) + +hellaboredguy=# +``` + +## Create Table +SQL Command +``` +hellaboredguy=# CREATE TABLE COMPANY( +hellaboredguy(# ID INT PRIMARY KEY NOT NULL, +hellaboredguy(# NAME TEXT NOT NULL, +hellaboredguy(# AGE INT NOT NULL, +hellaboredguy(# ADDRESS CHAR(50), +hellaboredguy(# SALARY REAL +hellaboredguy(# ); +CREATE TABLE + +hellaboredguy=# CREATE TABLE DEPARTMENT( +hellaboredguy(# ID INT PRIMARY KEY NOT NULL, +hellaboredguy(# DEPT CHAR(50) NOT NULL, +hellaboredguy(# EMP_ID INT NOT NULL +hellaboredguy(# ); +CREATE TABLE + +hellaboredguy=# \d + +hellaboredguy-# \d company + +hellaboredguy-# \d department +``` +Results +``` +hellaboredguy=# CREATE TABLE COMPANY( +hellaboredguy(# ID INT PRIMARY KEY NOT NULL, +hellaboredguy(# NAME TEXT NOT NULL, +hellaboredguy(# AGE INT NOT NULL, +hellaboredguy(# ADDRESS CHAR(50), +hellaboredguy(# SALARY REAL +hellaboredguy(# ); +CREATE TABLE +hellaboredguy=# CREATE TABLE DEPARTMENT( +hellaboredguy(# ID INT PRIMARY KEY NOT NULL, +hellaboredguy(# DEPT CHAR(50) NOT NULL, +hellaboredguy(# EMP_ID INT NOT NULL +hellaboredguy(# ); +CREATE TABLE +hellaboredguy=# \d + List of relations + Schema | Name | Type | Owner +--------+------------+-------+--------------- + public | company | table | hellaboredguy + public | department | table | hellaboredguy +(2 rows) + +hellaboredguy-# \d company + Table "public.company" + Column | Type | Modifiers +---------+---------------+----------- + id | integer | not null + name | text | not null + age | integer | not null + address | character(50) | + salary | real | +Indexes: + "company_pkey" PRIMARY KEY, btree (id) + +hellaboredguy-# \d department + Table "public.department" + Column | Type | Modifiers +--------+---------------+----------- + id | integer | not null + dept | character(50) | not null + emp_id | integer | not null +Indexes: + "department_pkey" PRIMARY KEY, btree (id) + +``` + +## Drop Table +SQL Command +``` +drop table department, company; +``` +Results +``` +hellaboredguy=# drop table department, company; +DROP TABLE +``` + +## Schema +SQL Command +``` +hellaboredguy=# create table myschema.company( +hellaboredguy(# ID INT NOT NULL, +hellaboredguy(# NAME VARCHAR (20) NOT NULL, +hellaboredguy(# AGE INT NOT NULL, +hellaboredguy(# ADDRESS CHAR (25), +hellaboredguy(# SALARY DECIMAL (18, 2), +hellaboredguy(# PRIMARY KEY (ID) +hellaboredguy(# ); + +select * from myschema.company; + +DROP SCHEMA myschema CASCADE; +``` + +Results +``` +hellaboredguy=# create table myschema.company( +hellaboredguy(# ID INT NOT NULL, +hellaboredguy(# NAME VARCHAR (20) NOT NULL, +hellaboredguy(# AGE INT NOT NULL, +hellaboredguy(# ADDRESS CHAR (25), +hellaboredguy(# SALARY DECIMAL (18, 2), +hellaboredguy(# PRIMARY KEY (ID) +hellaboredguy(# ); +CREATE TABLE + +hellaboredguy=# select * from myschema.company; + id | name | age | address | salary +----+------+-----+---------+-------- +(0 rows) + +hellaboredguy=# DROP SCHEMA myschema CASCADE; +NOTICE: drop cascades to table myschema.company +DROP SCHEMA + +``` + +## Insert +SQL Command +``` +CREATE TABLE COMPANY( +ID INT PRIMARY KEY NOT NULL, +NAME TEXT NOT NULL, +AGE INT NOT NULL, +ADDRESS CHAR(50), +SALARY REAL, +JOIN_DATE DATE +); + +\d + +\d company + +``` + +Results +``` +hellaboredguy=# CREATE TABLE COMPANY( +hellaboredguy(# ID INT PRIMARY KEY NOT NULL, +hellaboredguy(# NAME TEXT NOT NULL, +hellaboredguy(# AGE INT NOT NULL, +hellaboredguy(# ADDRESS CHAR(50), +hellaboredguy(# SALARY REAL, +hellaboredguy(# JOIN_DATE DATE +hellaboredguy(# ); +CREATE TABLE + +hellaboredguy=# \d + List of relations + Schema | Name | Type | Owner +--------+---------+-------+--------------- + public | company | table | hellaboredguy +(1 row) + +hellaboredguy=# \d company + Table "public.company" + Column | Type | Modifiers +-----------+---------------+----------- + id | integer | not null + name | text | not null + age | integer | not null + address | character(50) | + salary | real | + join_date | date | +Indexes: + "company_pkey" PRIMARY KEY, btree (id) + +ID NAME AGE ADDRESS SALARY JOIN_DATE +---- ---------- ----- ---------- ------- -------- +1 Paul 32 California 20000.0 2001-07-13 +2 Allen 25 Texas 2007-12-13 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 2007-12-13 +5 David 27 Texas 85000.0 2007-12-13 +``` + +## Select +SQL Command +``` +SELECT * FROM COMPANY; +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 2 | Allen | 25 | Texas | | 2007-12-13 + 3 | Teddy | 23 | Norway | 20000 | + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(5 rows) + +``` + +## Expressions +SQL Command +``` +SELECT * FROM COMPANY WHERE SALARY = 10000; + +SELECT (15 + 6) AS ADDITION ; + +SELECT COUNT(*) AS "RECORDS" FROM COMPANY; + +SELECT CURRENT_TIMESTAMP; +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY WHERE SALARY = 10000; + id | name | age | address | salary | join_date +----+------+-----+---------+--------+----------- +(0 rows) + +hellaboredguy=# SELECT (15 + 6) AS ADDITION ; + addition +---------- + 21 +(1 row) + +hellaboredguy=# SELECT COUNT(*) AS "RECORDS" FROM COMPANY; + RECORDS +--------- + 5 +(1 row) + +hellaboredguy=# SELECT CURRENT_TIMESTAMP; + now +------------------------------- + 2017-05-18 12:01:24.263437-07 +(1 row) +``` + +## Where clause +SQL Command +``` +select * from COMPANY; + +SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; + +SELECT * FROM COMPANY WHERE AGE IS NOT NULL; + +SELECT * FROM COMPANY WHERE NAME LIKE 'Pa%'; + +SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 ); + +SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27; +``` + +Results +``` +hellaboredguy=# select * from COMPANY; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 2 | Allen | 25 | Texas | | 2007-12-13 + 3 | Teddy | 23 | Norway | 20000 | + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(5 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(2 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE IS NOT NULL; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 2 | Allen | 25 | Texas | | 2007-12-13 + 3 | Teddy | 23 | Norway | 20000 | + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(5 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE NAME LIKE 'Pa%'; + id | name | age | address | salary | join_date +----+------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 +(1 row) + +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 ); + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 3 | Teddy | 23 | Norway | 20000 | +(2 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 2 | Allen | 25 | Texas | | 2007-12-13 + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(3 rows) + +``` + +## and / or operators +SQL Command +``` +SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; + +SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(2 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 2 | Allen | 25 | Texas | | 2007-12-13 + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 +(4 rows) +``` + +## Update Queries +SQL Command +``` +UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3; + +UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000; +``` + +Results +``` +hellaboredguy=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3; +UPDATE 1 + +hellaboredguy=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000; +UPDATE 5 + +hellaboredguy=# SELECT * FROM COMPANY; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | Texas | 20000 | 2001-07-13 + 2 | Allen | 25 | Texas | 20000 | 2007-12-13 + 4 | Mark | 25 | Texas | 20000 | 2007-12-13 + 5 | David | 27 | Texas | 20000 | 2007-12-13 + 3 | Teddy | 23 | Texas | 15000 | +(5 rows) +``` + +## Delete Queries +SQL Command +``` +DELETE FROM COMPANY WHERE ID = 2; + +DELETE FROM COMPANY; +``` + +Results +``` +hellaboredguy=# DELETE FROM COMPANY WHERE ID = 2; +DELETE 1 +hellaboredguy=# SELECT * FROM COMPANY; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 1 | Paul | 32 | Texas | 20000 | 2001-07-13 + 4 | Mark | 25 | Texas | 20000 | 2007-12-13 + 5 | David | 27 | Texas | 20000 | 2007-12-13 + 3 | Teddy | 23 | Texas | 15000 | +(4 rows) + +hellaboredguy=# DELETE FROM COMPANY; +DELETE 4 +hellaboredguy=# SELECT * FROM COMPANY; + id | name | age | address | salary | join_date +----+------+-----+---------+--------+----------- +(0 rows) +``` + +## like clause +SQL Command +``` +SELECT * FROM COMPANY WHERE AGE::text LIKE '2%'; + +SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%'; +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY WHERE AGE::text LIKE '2%'; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 + 3 | Teddy | 23 | Norway | 20000 | + 2 | Allen | 25 | Texas | | 2007-12-13 +(4 rows) + +hellaboredguy=# SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%'; + id | name | age | address | salary | join_date +----+------+-----+----------------------------------------------------+--------+------------ + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 +(1 row) +``` + +## limit clause +SQL Command +``` +SELECT * FROM COMPANY LIMIT 4; + +SELECT * FROM COMPANY LIMIT 3 OFFSET 2; +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY LIMIT 4; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 + 3 | Teddy | 23 | Norway | 20000 | + 2 | Allen | 25 | Texas | | 2007-12-13 +(4 rows) + +hellaboredguy=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 3 | Teddy | 23 | Norway | 20000 | + 2 | Allen | 25 | Texas | | 2007-12-13 + 1 | Paul | 32 | California | 20000 | 2001-07-13 +(3 rows) +``` + +## order by clause +SQL Command +``` +SELECT * FROM COMPANY ORDER BY AGE ASC; + +SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC; + +SELECT * FROM COMPANY ORDER BY NAME DESC; + +``` + +Results +``` +hellaboredguy=# SELECT * FROM COMPANY ORDER BY AGE ASC; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 3 | Teddy | 23 | Norway | 20000 | + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 2 | Allen | 25 | Texas | | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 + 1 | Paul | 32 | California | 20000 | 2001-07-13 +(5 rows) + +hellaboredguy=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 2 | Allen | 25 | Texas | | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 3 | Teddy | 23 | Norway | 20000 | +(5 rows) + +hellaboredguy=# SELECT * FROM COMPANY ORDER BY NAME DESC; + id | name | age | address | salary | join_date +----+-------+-----+----------------------------------------------------+--------+------------ + 3 | Teddy | 23 | Norway | 20000 | + 1 | Paul | 32 | California | 20000 | 2001-07-13 + 4 | Mark | 25 | Rich-Mond | 65000 | 2007-12-13 + 5 | David | 27 | Texas | 85000 | 2007-12-13 + 2 | Allen | 25 | Texas | | 2007-12-13 +(5 rows) +``` + +## group by clause +SQL Command +``` +SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME; + +SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME; + +SELECT NAME, SUM(SALARY) +FROM COMPANY GROUP BY NAME ORDER BY NAME DESC; +``` + +Results +``` +hellaboredguy=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME; + name | sum +-------+------- + Teddy | 20000 + Paul | 20000 + Mark | 65000 + David | 85000 + Allen | +(5 rows) + +hellaboredguy=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME; + name | sum +-------+------- + Allen | + David | 85000 + James | 10000 + Mark | 65000 + Paul | 40000 + Teddy | 20000 +(6 rows) + +hellaboredguy=# SELECT NAME, SUM(SALARY) +hellaboredguy-# FROM COMPANY GROUP BY NAME ORDER BY NAME DESC; + name | sum +-------+------- + Teddy | 20000 + Paul | 40000 + Mark | 65000 + James | 10000 + David | 85000 + Allen | +(6 rows) +``` diff --git a/sql/01-create-table-student.sql b/sql/01-create-table-student.sql index a86bc53..b3dd727 100644 --- a/sql/01-create-table-student.sql +++ b/sql/01-create-table-student.sql @@ -1,3 +1,13 @@ +/* +01: Table name: student, columns: id, name, grade + + - id is the primary key + - name is only their first name + - grade is an integer + - write the SQL in the file sql/01-create-table-student.sql +*/ + + CREATE TABLE student ( id INTEGER PRIMARY KEY, name TEXT, diff --git a/sql/02-create-table-friend.sql b/sql/02-create-table-friend.sql index 56aaf23..7c15289 100644 --- a/sql/02-create-table-friend.sql +++ b/sql/02-create-table-friend.sql @@ -1,3 +1,12 @@ +/* +02: Table name: friend, columns: id1, id2 + + - id1 is a foreign key reference to a student + - id2 is a foreign key reference to a student + - write the SQL in the file sql/02-create-table-friend.sql +*/ + + CREATE TABLE friend ( id1 INTEGER, id2 INTEGER) diff --git a/sql/03-create-table-like.sql b/sql/03-create-table-like.sql index 0c91bed..01c2dbb 100644 --- a/sql/03-create-table-like.sql +++ b/sql/03-create-table-like.sql @@ -1,3 +1,11 @@ +/* +03: Table name: student_like, columns: liker_id, likee_id + + - liker_id is a foreign key reference to a student + - likee_id is a foreign key reference to a student + - write the SQL in the file sql/03-create-table-like.sql +*/ + CREATE TABLE student_like ( liker_id INTEGER, likee_id INTEGER) diff --git a/sql/04-load-table-student.sql b/sql/04-load-table-student.sql index e69de29..0466384 100644 --- a/sql/04-load-table-student.sql +++ b/sql/04-load-table-student.sql @@ -0,0 +1,7 @@ +/* +04: SQL query to load the CSV file data/students.csv for the student table +Write the SQL in the file sql/04-load-table-student.sql +*/ + +COPY exercises.students FROM '/Users/hellaboredguy/Documents/Projects/CoreSQL/sql-exercises/data/students.csv' DELIMITER ',' CSV HEADER; + diff --git a/sql/05-load-table-friend.sql b/sql/05-load-table-friend.sql index e69de29..64feef7 100644 --- a/sql/05-load-table-friend.sql +++ b/sql/05-load-table-friend.sql @@ -0,0 +1,6 @@ +/* +05: SQL query to load the CSV file data/friends.csv for the friend table +Write the query in the file sql/05-load-table-friend.sql +*/ + +COPY exercises.students FROM '/Users/hellaboredguy/Documents/Projects/CoreSQL/sql-exercises/data/friends.csv' DELIMITER ',' CSV HEADER; diff --git a/sql/06-load-table-like.sql b/sql/06-load-table-like.sql index e69de29..07d8ead 100644 --- a/sql/06-load-table-like.sql +++ b/sql/06-load-table-like.sql @@ -0,0 +1,6 @@ +/* +06: SQL query to load the CSV file data/likes.csv for the student_like table +Write the SQL in the file sql/06-load-table-like.sql +*/ + +COPY exercises.students FROM '/Users/hellaboredguy/Documents/Projects/CoreSQL/sql-exercises/data/likes.csv' DELIMITER ',' CSV HEADER; diff --git a/sql/07-query-friends-gabriel.sql b/sql/07-query-friends-gabriel.sql index e69de29..ef91178 100644 --- a/sql/07-query-friends-gabriel.sql +++ b/sql/07-query-friends-gabriel.sql @@ -0,0 +1,12 @@ +/* +07: Find the names of all students who are friends with someone named Gabriel. +Write the SQL in the file sql/07-query-friends-gabriel.sql +*/ + +SELECT a.name, b.name FROM friend +JOIN students a +ON a.id = friend.id1 +JOIN students b +ON b.id = friend.id2 +WHERE a.name = 'Gabriel' OR b.name = 'Gabriel'; + diff --git a/sql/08-query-likes-grade-two-or-more.sql b/sql/08-query-likes-grade-two-or-more.sql index e69de29..726a7b0 100644 --- a/sql/08-query-likes-grade-two-or-more.sql +++ b/sql/08-query-likes-grade-two-or-more.sql @@ -0,0 +1,11 @@ +/* +08: For every student who likes someone 2 or more grades younger than themselves, return that student's name and grade, and the name and grade of the student they like. +Write the SQL in the file sql/08-query-likes-grade-two-or-more.sql +*/ + +SELECT a.name AS liker_name, a.grade AS liker_grade,b.name AS likee_name, b.grade AS likee_grade FROM student_like +JOIN students a +ON liker_id = a.id +JOIN students b +ON likee_id = b.id +WHERE a.grade -2 >= b.grade; diff --git a/sql/09-mutual-likes.sql b/sql/09-mutual-likes.sql index e69de29..88966ba 100644 --- a/sql/09-mutual-likes.sql +++ b/sql/09-mutual-likes.sql @@ -0,0 +1,22 @@ +/* +09: For every pair of students who both like each other, return the name and grade of both students. Include each pair only once, with the two names in alphabetical order. +Write the SQL in the file sql/09-mutual-likes.sql +*/ +SELECT name, id_result FROM students +JOIN +(SELECT liker_id AS id_result FROM ( +SELECT a.liker_id FROM students +JOIN student_like a +ON id = a.liker_id +JOIN student_like b +ON students.id = b.likee_id +) AS test1 +INTERSECT +SELECT likee_id AS id_result FROM ( +SELECT a.likee_id FROM exercises.students +JOIN student_like a +ON students.id = a.liker_id +JOIN student_like b +ON students.id = b.likee_id +) AS test1) test98 +ON students.id = test98.id_result; diff --git a/sql/10-not-liked.sql b/sql/10-not-liked.sql index e69de29..81e650e 100644 --- a/sql/10-not-liked.sql +++ b/sql/10-not-liked.sql @@ -0,0 +1,8 @@ +/* +10: Find all students who do not appear in the like table (as a student who likes or is liked) and return their names and grades. Sort by grade, then by name within each grade. +Write the SQL in the file sql/10-not-liked.sql +*/ +SELECT * FROM exercises.students + WHERE id NOT IN (SELECT liker_id From exercises.student_like) + AND id NOT IN (SELECT likee_id From exercises.student_like) + ORDER BY grade, name; diff --git a/sql/11-liked-but-does-not-like.sql b/sql/11-liked-but-does-not-like.sql index e69de29..daee39e 100644 --- a/sql/11-liked-but-does-not-like.sql +++ b/sql/11-liked-but-does-not-like.sql @@ -0,0 +1,12 @@ +/* +11: For every situation where student A likes student B, but we have no information about whom B likes (that is, B's id does not appear in the liker_id column of the like table), return A and B's names and grades. +Write the SQL in the file sql/11-liked-but-does-not-like.sql +*/ + +SELECT a.name AS liker_name, a.grade AS liker_grade, b.name AS likee_name, b.grade AS likee_grade +FROM exercises.student_like +JOIN exercises.students a +ON student_like.liker_id =a.id +JOIN exercises.students b +ON student_like.likee_id =b.id +WHERE b.id NOT IN (SELECT liker_id FROM exercises.student_like); diff --git a/sql/12-find-friends-in-common.sql b/sql/12-find-friends-in-common.sql index e69de29..28c845a 100644 --- a/sql/12-find-friends-in-common.sql +++ b/sql/12-find-friends-in-common.sql @@ -0,0 +1,4 @@ +/* +Stretch: 12: For each student A who likes a student B where the two are not friends, find if they have a friend C in common (who can introduce them!). For all such trios, return the name and grade of A, B, and C. +Write the SQL in the file sql/12-find-friends-in-common.sql +*/ diff --git a/sql/13-popular-students.sql b/sql/13-popular-students.sql index e69de29..d06cacf 100644 --- a/sql/13-popular-students.sql +++ b/sql/13-popular-students.sql @@ -0,0 +1,4 @@ +/* +Stretch: 13: Find the name and grade of all students who are liked by more than one other student. +Write the SQL in the file sql/13-popular-students.sql +*/ From 63a79f3c46a34f111ccf32b5f37ef68b8c8d60ef Mon Sep 17 00:00:00 2001 From: Roel Cabrera Date: Fri, 19 May 2017 08:12:27 -0700 Subject: [PATCH 7/7] updated md files, added SQLBolt file --- .DS_Store | Bin 6148 -> 6148 bytes SQLBolt/SQLBolt.md | 353 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+) create mode 100644 SQLBolt/SQLBolt.md diff --git a/.DS_Store b/.DS_Store index 57b12d646c2a306a0925fa9a77346c272ad721ce..85c6c677799edeb092d535264a1d2aed40d19a3c 100644 GIT binary patch delta 321 zcmZoMXfc@J&&acq3GcYhP0x=6i0YfoE rAwy11x?yl~er^F!3= 2000 +; +``` + - [x] Find the movies not released in the years between 2000 and 2010 +``` +SELECT * FROM movies +WHERE year > 2010 OR year < 2000 +; +``` + - [x] Find the first 5 Pixar movies and their release year +``` +SELECT * FROM movies +WHERE id BETWEEN 1 AND 5 +; +``` + +## SQL Lesson 3: Queries with constraints (Pt. 2) + - [x] Find all the Toy Story movies +``` +SELECT * FROM movies +WHERE Title LIKE "Toy Story%" +; +``` + - [x] Find all the moviesdirected by John Lasseter +``` +SELECT * FROM movies +WHERE Director = "John Lasseter" +; +``` + - [x] Find all the movies (and director)not direct by John Lasseter +``` +SELECT * FROM movies +WHERE Director != "John Lasseter" +; +``` + - [x] Find all the Wall-* movies +``` +SELECT * FROM movies +WHERE Title Like "WALL-_" +; +``` + +## SQL Lesson 4: Filtering and sorting Query results + - [x] List all directors of Pixar movies (alphabetically), without duplicates +``` +SELECT DISTINCT Director FROM movies +ORDER BY Director DESC +; +``` + - [x] List the last four Pixar movies released (ordered from most recent to least) +``` +SELECT * FROM movies +ORDER BY Year DESC +LIMIT 4 +; +``` + - [x] List the first five Pixar movies sorted alphabetically +``` +SELECT * FROM movies +ORDER BY Title ASC +LIMIT 5 +; +``` + - [x] List the next five Pixar movies sorted alphabetically +``` +SELECT * FROM movies +ORDER BY Title ASC +LIMIT 5 OFFSET 5 +; +``` + +## SQL Review: Simple SELECT Queries +- [x] List all the Canadian cities and their populations +``` +SELECT * FROM north_american_cities +WHERE Country = "Canada" +; +``` +- [x] Order all the cities in the United States by their latitude from north to south +``` +SELECT * FROM north_american_cities +WHERE Country = "United States" +ORDER BY Latitude DESC +; +``` +- [x] List all the cities west of Chicago, ordered from west to east +``` +SELECT FROM north_american_cities +WHERE longitude < -87.629798 +ORDER BY longitude ASC +; +``` +- [x] List the two largest cities in Mexico (by population) +``` +SELECT * FROM North_american_cities +WHERE Country = "Mexico" +ORDER BY Population DESC +LIMIT 2 +; +``` +- [x] List the third and fourth largest cities (by population) in the United States and their population +``` +SELECT * FROM North_american_cities +WHERE Country = "United States" +ORDER BY Population DESC +LIMIT 2 OFFSET 2 +; +``` + +## SQL Lesson 6: Multi-table queries with JOINs + - [x] Find the domestic and international sales for each movie +``` +SELECT movies.title, boxoffice.domestic_sales, boxoffice.international_sales FROM movies +JOIN Boxoffice +ON movies.id = boxoffice.movie_id +; +``` + - [x] Show the sales numbers for each movie that did better internationally rather than domestically +``` +SELECT movies.title, boxoffice.domestic_sales, boxoffice.international_sales FROM movies +JOIN Boxoffice +ON movies.id = boxoffice.movie_id +WHERE boxoffice.International_sales > boxoffice.domestic_sales +; +``` + - [x] List all the movies by their ratings in descending order +``` +SELECT movies.title, boxoffice.rating FROM movies +JOIN Boxoffice +ON movies.id = boxoffice.movie_id +ORDER BY rating DESC +; +``` + +## SQL Lesson 7: OUTER JOINs + - [x] Find the list of all buildings that have employees +``` +SELECT DISTINCT building FROM employees +; +``` +note: seriously.... + - [x] Find the list of all buildings and their capacity +``` +SELECT * FROM buildings +; +``` +note: bruh.... + - [x] List all buildings and the distinct employee roles in each building (including empty buildings) + +``` +SELECT DISTINCT building_name, role FROM buildings +LEFT JOIN employees +ON building_name = building +; +``` + +## SQL Lesson 8: AShort note on NULLs +-[x] Find the name and role of all employees who have not been assigned to a building +``` +SELECT name, role FROM employees +WHERE building IS NULL +; +``` +-[x] Find the names of the buildings that hold no employees +``` +SELECT DISTINCT building_name FROM buildings +LEFT JOIN employees +ON building_name = building +WHERE role IS NULL +; +``` + +## SQL Lesson 9: Queries with expressions +-[x] List all movies and their combined sales in millions of dollars +``` +SELECT title, (domestic_sales + international_sales) / 1000000 AS +gross_sales_millionsFROM movies +JOIN boxoffice +ON movies.id = boxoffice.movie_id +; +``` +-[x] List all movies and their ratings in percent +``` +SELECT title, rating * 10 AS rating_percent +FROM movies +JOIN boxoffice +ON movies.id = boxoffice.movie_id +; +``` +-[x] List all movies that were released on even number years +``` +SELECT title, year +FROM movies +WHERE year % 2 = 0 +; +``` +## SQL Lesson 10: Queries with aggregates (Pt. 1) +-[x] Find the longest time that an employee has been at the studio +``` +SELECT * FROM employees +ORDER BY years_employed DESC +LIMIT 1 +; +``` +-[x] For each role, find the average number of years employed by employees in that role +``` +SELECT role, AVG(years_employed) as Average_years_employed +FROM employees +GROUP BY role +; +``` +-[x] Find the total number of employee years worked in each building +``` +SELECT building, SUM(years_employed) as Average_years_employed +FROM employees +GROUP BY building +; +``` + +## SQL Lesson 11: Queries with aggregates (Pt. 2) +-[x] Find the number of Artists in the studio (without a HAVING clause) +``` +SELECT role, COUNT(*) as artist_count +FROM employees +WHERE role = "Artist"; +``` +-[x] Find the number of Employees of each role in the studio +``` +SELECT role, COUNT(*) +FROM employees +GROUP BY role +; +``` +-[x] Find the total number of years employed by all Engineers +``` +SELECT role, SUM(years_employed) +FROM employees +WHERE role = "Engineer" +``` + +## SQL Lesson 12: Order of execution of a Query +-[x] Find the number of movies each director has directed +``` +SELECT director, COUNT(Director) FROM movies +GROUP BY DIRECTOR +; +``` +-[x] Find the total domestic and international sales that can be attributed to each director + +``` +SELECT director, SUM(domestic_sales + international_sales) as sum_all_movies +FROM movies +INNER JOIN boxoffice +ON movies.id = boxoffice.movie_id +GROUP BY director +; +``` + +## SQL Lesson 13: Inserting rows +-[x] Add the studio's new production, Toy Story 4 to the list of movies (you can use any director) +``` +INSERT INTO boxoffice VALUES (4, "Toy Story 4", "John Lasseter", 2008, 10000000); +``` +-[x] Toy Story 4 has been released to critical acclaim! It had a rating of 8.7, and made 340 million domestically and 270 million internationally. Add the record to the BoxOffice table. +``` +INSERT INTO boxoffice VALUES (4, 8.7, 340000000, 27000000); +``` + +## SQL Lesson 14: Updating rows +-[x] The director for A Bug's Life is incorrect, it was actually directed by John Lasseter +``` +UPDATE movies +SET Director = "John Lasseter" +WHERE id = 2 +; +``` +-[x] The year that Toy Story 2 was released is incorrect, it was actually released in 1999 +``` +UPDATE movies +SET Year = 1999 +WHERE id = 3 +; +``` +-[x] Both the title and directory for Toy Story 8 is incorrect! The title should be "Toy Story 3" and it was directed by Lee Unkrich +``` +UPDATE movies +SET title = "Toy Story 3" +director = "Lee Unkrich" +WHERE id = 11 +; +``` + +## SQL Lesson 15: Deleting rows +-[x] This database is getting too big, lets remove all movies that were released before 2005. +``` +DELETE FROM movies +WHERE Year < 2005 +; +``` +-[x] Andrew Stanton has also left the studio, so please remove all movies directed by him. +``` +DELETE FROM movies +WHERE director = "Andrew Stanton" +; +``` + +## SQL Lesson 16: Creating tables +-[x] Create a new table named Database with the following columns: + – Name A string (text) describing the name of the database + – Version A number (floating point) of the latest version of this database + – Download_count An integer count of the number of times this database was downloaded +This table has no constraints. +``` +CREATE TABLE Database ( + name TEXT, + version INTEGER, + download_count INTEGER +); +```