diff --git a/DataSet_project.zip b/DataSet_project.zip new file mode 100644 index 000000000..541b682cd Binary files /dev/null and b/DataSet_project.zip differ diff --git a/SQL-part-1-Studio.sql b/SQL-part-1-Studio.sql new file mode 100644 index 000000000..8f1f2159f --- /dev/null +++ b/SQL-part-1-Studio.sql @@ -0,0 +1,83 @@ + +--Question 1: Write a query of the `books` table that returns the top 100 results and includes `book_id`, `authors`, `title`, and `average_rating`. Use an alias for at least one column and sort the result set in descending order of rating. What is the number one book? +SELECT TOP 100 + book_id, + authors, + title AS book_title, -- alias for title + average_rating +FROM [BooksDB].[dbo].[books] +ORDER BY average_rating DESC; + + +--Question 2: Write a query to find the least popular book. + +SELECT TOP 1 book_id, title, authors, average_rating +FROM [BooksDB].[dbo].[books] +ORDER BY average_rating ASC; + +--Question 3: Which tag is the most popular? + +SELECT TOP 1 + tag_id, "count" +FROM [BooksDB].[dbo].[book_tags] +ORDER BY "count" DESC; + +--Question 4: What is the name of the most popular tag? + +SELECT * +FROM BooksDB.dbo.tags +WHERE tag_id = ( + +SELECT TOP (1) tag_id + +FROM BooksDB.dbo.book_tags + + ORDER BY "count" DESC) + + +--Question 5: How many books where released in the first decade of 2000? + +SELECT COUNT(*) AS books_2000s +FROM [BooksDB].[dbo].[books] +WHERE original_publication_year BETWEEN 2000 AND 2009; + +--Question 6: How many book titles contain the word, "happy"? + +SELECT COUNT(*) AS happy_books +FROM [BooksDB].[dbo].[books] +WHERE title LIKE '%happy%'; + +--Question 7: List the books from the top 3 authors from Question 1. +-- If there is more than one author just use the first one. Sort the title alphabetically by `author` and then by `average_rating`, best rated to lowest. Does this order matter in sorting? + + SELECT authors, title, average_rating +FROM BooksDB.dbo.books +WHERE authors = 'j.k. rowling' OR authors = 'bill watterson' OR authors = 'brandon sanderson' +ORDER BY title ASC, average_rating DESC + +--Question 8: Write a query that returns the number of authors whose first name is between rock and roll. +SELECT COUNT(*) AS authors_between_rock_roll +FROM [BooksDB].[dbo].[books] +WHERE authors BETWEEN 'rock' AND 'roll'; + +-- Question: Click here to add a questions that you want to answer and write a query to find +the answer! + +--Question-Returns the top 100 books sorted by average_rating (highest first). +SELECT TOP 100 + book_id, + authors, + title AS book_title, + average_rating +FROM [BooksDB].[dbo].[books] +ORDER BY average_rating DESC; + +--question-Books containing the word "happy" + +SELECT COUNT(*) AS happy_books +FROM [BooksDB].[dbo].[books] +WHERE title LIKE '%happy%'; + + + + diff --git a/SQL-part-1-exercises.sql b/SQL-part-1-exercises.sql new file mode 100644 index 000000000..271af5f2c --- /dev/null +++ b/SQL-part-1-exercises.sql @@ -0,0 +1,120 @@ + +--A. The books table + +--Question 1 Select the top 1000 rows from the books table.make sure to use the correct syntax for your SQL database. +SELECT Top 1000 * +FROM [BooksDB].[dbo].[books] + +--Question 2 count the number of Titles .Are there 1000 titles as promised by the dataset? + +SELECT COUNT(Title) AS Number_of_Titles +FROM [BooksDB].[dbo].[books] + +--Question 3 Count the number of books where the original_publication_year is earlier than 1800? + +SELECT COUNT(Title) AS Books_Before_1800 +FROM [BooksDB].[dbo].[books] +WHERE original_publication_year < 1800 + +--Question 4 Create the query that display distinct authors from the table? + +SELECT DISTINCT authors +FROM [BooksDB].[dbo].[books] +ORDER BY authors + +--Question 5 Create the query that display acount of all the books that contains a language_code for english.this could be represented in a table as "en" or "eng". + +SELECT COUNT(Title) AS english +FROM [BooksDB].[dbo].[books] +WHERE language_code IN ('en', 'eng') + +--Question 6 Create the query that checks how many original titles where written during world war 1 era (1914-1921)? + +SELECT COUNT(Title) AS WW1_Era +FROM [BooksDB].[dbo].[books] +WHERE original_publication_year BETWEEN 1914 AND 1921 + + +--B.The Books tags table +--Question 1 Select the top 1000 table items ordered by the tag_id? + +SELECT TOP 1000 * +FROM [BooksDB].[dbo].[book_tags] +ORDER BY tag_id + +--Question 2 create a query that counts the number of good_books_id grouped by tag_id ? + +select COUNT(goodreads_book_id) as good_reads +FROM [BooksDB].[dbo].[book_tags] +GROUP BY tag_id + +--Question 3 In the last query ,we created new,unnamed column .use As to create Alias to provide a name of your choice to this column? + +select COUNT(goodreads_book_id) as Goodreads_books +FROM [BooksDB].[dbo].[book_tags] +GROUP BY tag_id + +--C. The rating table +--Question 1 create a query that selects the top 1000 rows from the ratings table in a descnding order? + +SELECT TOP 1000 * +FROM [BooksDB].[dbo].[ratings] +ORDER BY rating DESC + +--question 2 Create a query that returns the total number of user that has given a rating less than 2? + +select COUNT(rating) as total_ratings +from [BooksDB].[dbo].[ratings] +where rating < 2 + +--Question 3 Create a query that returns the sum of books that have rating 4 or higher? + +select COUNT(rating) as total_ratings +from [BooksDB].[dbo].[ratings] +where rating >= 4 + + +--D. The Tags Table +--Question 1 Create a query that return table items where the tag_name describes book as a mystery? + +SELECT * +from [BooksDB].[dbo].[tags] +WHERE tag_name LIKE '%mystery%' + +--Questtion 2 run the query below. in your worlds what is returning? + +SELECT * +FROM BooksDB.dbo.tags +WHERE tag_name < 'd' AND tag_name >= 'c'; + +--The to Read table +--Question 1: Create a query that uses the `user_id` to count the total number of books that each user wants to read. Print the results in ascending order by `user_id` under the alias 'Total Books To Read'. + +--Hint: You can use both `GROUP BY` and `ORDER BY` to complete this query. + +SELECT user_id, COUNT(book_id) AS 'Total Books To Read' +FROM [BooksDB].[dbo].[to_read] +GROUP BY user_id +ORDER BY user_id ASC + +--Question 2: Create a query that uses `user_id` to count the total number of books each user wants to read. Have the results sort the table by the total number of `book_ids` in descending order and under the alias 'Total Books To Read'. + +--Hint: You can use both `GROUP BY` and `ORDER BY` to complete this query. + +SELECT user_id, COUNT(book_id) AS 'Total Books To Read' +FROM [BooksDB].[dbo].[to_read] +GROUP BY user_id +ORDER BY COUNT(book_id) DESC + + + + + + + + + + + + + diff --git a/SQL-part-4-demos.sql b/SQL-part-4-demos.sql new file mode 100644 index 000000000..1a48c0c1f --- /dev/null +++ b/SQL-part-4-demos.sql @@ -0,0 +1,169 @@ +--1which driver have ever finished first? + +SELECT forename, surname +FROM formula_one.dbo.drivers +WHERE driverId IN +( + SELECT DISTINCT driverId + FROM formula_one.dbo.results + WHERE position = '1' +) + +--2 How many races has each driver entered? + +SELECT d.forename, d.surname, +( + SELECT COUNT(*) + FROM formula_one.dbo.results AS r + WHERE r.driverId = d.driverId + ) AS race_count +FROM formula_one.dbo.drivers AS d + +--Which driver have entered at least 50 competitions? + +SELECT + d.forename, d.surname +FROM formula_one.dbo.drivers AS d +WHERE +( + SELECT COUNT(*) + FROM formula_one.dbo.results AS r + WHERE r.driverId = d.driverId +) >= 50 + +--which driver have finished first at least once? CTE version +WITH Winning_driverIDs AS( + SELECT DISTINCT driverId + FROM formula_one.dbo.results + WHERE position = '1' + +) +SELECT d.forename, d.surname +FROM formula_one.dbo.drivers AS d +WHERE d.driverId IN (SELECT driverId FROM Winning_driverIDs); + +-- for each circuit,in how many years has it hosted at least one race? +--count of distinct year values for each circuit id, from race table +--information about each circuit itself,like the circuit name,which comes from the circuit table + +WITH circuit_years AS +( +Select circuitId,COUNT(DISTINCT year) AS num_years_hosted +from formula_one.dbo.races +GROUP BY circuitId +) +SELECT cir.name AS circuit_name, +cy.num_years_hosted +FROM formula_one.dbo.circuits AS cir +INNER JOIN circuit_years AS cy +ON cir.circuitId = cy.circuitId +ORDER BY cy.num_years_hosted DESC; + +-- which drivers have scored points in more than 5 different races? +--need: driver table, results + +WITH driver_points AS ( SELECT + driverId, + COUNT(resultId) AS races_with_points +FROM formula_one.dbo.results +WHERE points > 0 +GROUP BY driverId +) +SELECT d.forename ,d.surname, +driver_points.races_with_points AS races_with_points +FROM formula_one.dbo.drivers AS d +INNER JOIN driver_points +ON d.driverId = driver_points.driverId +WHERE driver_points.races_with_points > 5 +ORDER BY races_with_points; + +-- A list of all driver who are either from the UK or from Italy +SELECT forename,surname,nationality +From formula_one.dbo.drivers +WHERE +nationality = 'British' + +UNION + +SELECT forename,surname,nationality +From formula_one.dbo.drivers +WHERE +nationality = 'Italian' + +--list of drivers who have either won a race ,or recorded the fastet lap in a race +--"rank "column in results table is the "rank "of the fastest lap.i.e a rank of 1 means they had the first fastet lap in that race +-- table that pulls drivers who won a race + +SELECT + d.forename, d.surname, + 'Race Winner' AS achievement_type +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS r +ON d.driverId = r.driverId +WHERE r.position = '1' +UNION +--table that pulls driver who have recorded the fastet lap in a race +SELECT + d.forename, d.surname, + 'Fastest Lap' AS achievement_type +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS r +ON d.driverId = r.driverId +WHERE r.rank = '1'; + +-- create a list of drivers who races in both 2021 and 2022 + +--create a table of drivers whoc raced in 2021 + +SELECT DISTINCT d.driverId, +d.forename, +d.surname +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS res +ON d.driverID = res.driverId +INNER JOIN formula_one.dbo.races +ON res.raceId = races.raceId +WHERE races.year=2021 + +INTERSECT +--table of drivers who races in 2022 + +SELECT DISTINCT d.driverId, +d.forename, +d.surname +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS res +ON d.driverID = res.driverId +INNER JOIN formula_one.dbo.races +ON res.raceId = races.raceId +WHERE races.year=2022 + +--which driver raced in 2021 but not 2022 + +SELECT DISTINCT d.driverId, +d.forename, +d.surname +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS res +ON d.driverID = res.driverId +INNER JOIN formula_one.dbo.races +ON res.raceId = races.raceId +WHERE races.year=2021 + +EXCEPT +--table of drivers who races in 2022 + +SELECT DISTINCT d.driverId, +d.forename, +d.surname +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS res +ON d.driverID = res.driverId +INNER JOIN formula_one.dbo.races +ON res.raceId = races.raceId +WHERE races.year=2022 + + + + + diff --git a/SQLPart2_Studio.txt b/SQLPart2_Studio.txt new file mode 100644 index 000000000..43a131c44 --- /dev/null +++ b/SQLPart2_Studio.txt @@ -0,0 +1,107 @@ +--Highlight popular women writers based on ratings from `BooksDB` by writing a query that +-- returns `tag_id`, the number of times each `tag_id` is used and the `tag_name`. Use the `GROUP BY` and `HAVING` clause to narrow your +--focus and try multiple keywords, such as "woman" and "female" + +SELECT * +FROM BooksDB.dbo.tags +WHERE tag_name LIKE '%woman%' OR tag_name LIKE '%female%' +ORDER BY tag_name; + + + +SELECT + t.tag_id, + t.tag_name, + COUNT(bt.tag_id) AS tag_count +FROM BooksDB.dbo.book_tags AS bt +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%woman%' OR t.tag_name LIKE '%female%' +GROUP BY + t.tag_id, + t.tag_name +ORDER BY + tag_count DESC; + + + --### Event 2: Choose another event from March/Spring + +--Write a query to return authors, titles, + --ratings, and `tag_id` that you would want to promote during your chosen event. + + SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%Christmas%' -- filter by your event theme +ORDER BY b.average_rating DESC; + +--# Part 2: Choose Another Month + +--Choose another month and plan at least 2 events / promotions and answer the following questions: +1. Which month did you choose? September +1. What 2 events / promotions are you highlighting? Back to School and Autumn + +--# Part 3: Summarize your Work + +For each event write at least one query that joins any two tables in `BooksDB` to +support your choice and record you thoughts as to why you used the paticlular query. + At least one of your queries needs to include a `HAVING` clause. + + --Query joins books and book_tags to find books tagged with School + + +SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + --t.tag_id, + --t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%School%' -- filter by your event theme + +ORDER BY b.average_rating DESC; + + + +--Event 2: Autumn or Fall + +--Query joins books and book_tags to find books tagged with Autumn or Fall +SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%Autumn%' +GROUP BY + b.authors, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +HAVING b.average_rating > 4.0 +ORDER BY b.average_rating DESC; + + + + + + + diff --git a/SQL_Part2-demo.sql b/SQL_Part2-demo.sql new file mode 100644 index 000000000..277f6268e --- /dev/null +++ b/SQL_Part2-demo.sql @@ -0,0 +1,40 @@ +select UPPER(LEFT(surname,3)) AS surname_first_3 ,nationality, driverId +FROM formula_one.dbo.drivers; + +--Which month have the most races occured in? + +select MONTH(date) AS race_month, + DATENAME(MONTH,date) AS month_name, + count(*) AS number_of_races +from formula_one.dbo.races +where YEAR(date) > 2014 +GROUP BY MONTH(date), DATENAME(MONTH,date) +ORDER BY number_of_races DESC; + +--Race review occur 4 days after each race.calculate the day of the race review for every race in the races + +SELECT name AS race_name, +date as race_date, +DATEADD(DAY, 4, date) AS review_date +from formula_one.dbo.races + +-- how can we display each race date as a formateed string like "Sunday, March 11"? + +SELECT name as race_name, +FORMAT(date, 'dddd, MMMM dd,yyyy') AS Formatted_date +from formula_one.dbo.races +ORDER BY [date] + +-- +SELECT * +FROM BooksDB.dbo.books +where original_title is NULL + +--create a column that has original title, if it exist, or title if original title is null + +SELECT authors, book_id, COALESCE(original_title,title) original_title_refined +FROM BooksDB.dbo.books + + + + diff --git a/SQLpart1.txt b/SQLpart1.txt new file mode 100644 index 000000000..57a4e52f1 --- /dev/null +++ b/SQLpart1.txt @@ -0,0 +1,123 @@ + + +Paper View + +--A. The books table + +--Question 1 Select the top 1000 rows from the books table.make sure to use the correct syntax for your SQL database. +SELECT Top 1000 * +FROM [BooksDB].[dbo].[books] + +--Question 2 count the number of Titles .Are there 1000 titles as promised by the dataset? + +SELECT COUNT(Title) AS Number_of_Titles +FROM [BooksDB].[dbo].[books] + +--Question 3 Count the number of books where the original_publication_year is earlier than 1800? + +SELECT COUNT(Title) AS Books_Before_1800 +FROM [BooksDB].[dbo].[books] +WHERE original_publication_year < 1800 + +--Question 4 Create the query that display distinct authors from the table? + +SELECT DISTINCT authors +FROM [BooksDB].[dbo].[books] +ORDER BY authors + +--Question 5 Create the query that display acount of all the books that contains a language_code for english.this could be represented in a table as "en" or "eng". + +SELECT COUNT(Title) AS english +FROM [BooksDB].[dbo].[books] +WHERE language_code IN ('en', 'eng') + +--Question 6 Create the query that checks how many original titles where written during world war 1 era (1914-1921)? + +SELECT COUNT(Title) AS WW1_Era +FROM [BooksDB].[dbo].[books] +WHERE original_publication_year BETWEEN 1914 AND 1921 + + +--B.The Books tags table +--Question 1 Select the top 1000 table items ordered by the tag_id? + +SELECT TOP 1000 * +FROM [BooksDB].[dbo].[book_tags] +ORDER BY tag_id + +--Question 2 create a query that counts the number of good_books_id grouped by tag_id ? + +select COUNT(goodreads_book_id) as good_reads +FROM [BooksDB].[dbo].[book_tags] +GROUP BY tag_id + +--Question 3 In the last query ,we created new,unnamed column .use As to create Alias to provide a name of your choice to this column? + +select COUNT(goodreads_book_id) as Goodreads_books +FROM [BooksDB].[dbo].[book_tags] +GROUP BY tag_id + +--C. The rating table +--Question 1 create a query that selects the top 1000 rows from the ratings table in a descnding order? + +SELECT TOP 1000 * +FROM [BooksDB].[dbo].[ratings] +ORDER BY rating DESC + +--question 2 Create a query that returns the total number of user that has given a rating less than 2? + +select COUNT(rating) as total_ratings +from [BooksDB].[dbo].[ratings] +where rating < 2 + +--Question 3 Create a query that returns the sum of books that have rating 4 or higher? + +select COUNT(rating) as total_ratings +from [BooksDB].[dbo].[ratings] +where rating >= 4 + + +--D. The Tags Table +--Question 1 Create a query that return table items where the tag_name describes book as a mystery? + +SELECT * +from [BooksDB].[dbo].[tags] +WHERE tag_name LIKE '%mystery%' + +--Questtion 2 run the query below. in your worlds what is returning? + +SELECT * +FROM BooksDB.dbo.tags +WHERE tag_name < 'd' AND tag_name >= 'c'; + +--The to Read table +--Question 1: Create a query that uses the `user_id` to count the total number of books that each user wants to read. Print the results in ascending order by `user_id` under the alias 'Total Books To Read'. + +--Hint: You can use both `GROUP BY` and `ORDER BY` to complete this query. + +SELECT user_id, COUNT(book_id) AS 'Total Books To Read' +FROM [BooksDB].[dbo].[to_read] +GROUP BY user_id +ORDER BY user_id ASC + +--Question 2: Create a query that uses `user_id` to count the total number of books each user wants to read. Have the results sort the table by the total number of `book_ids` in descending order and under the alias 'Total Books To Read'. + +--Hint: You can use both `GROUP BY` and `ORDER BY` to complete this query. + +SELECT user_id, COUNT(book_id) AS 'Total Books To Read' +FROM [BooksDB].[dbo].[to_read] +GROUP BY user_id +ORDER BY COUNT(book_id) DESC + + + + + + + + + + + + + diff --git a/sql-part-1/exercises/SQL-Demo-1.sql b/sql-part-1/exercises/SQL-Demo-1.sql new file mode 100644 index 000000000..ff9b31f93 --- /dev/null +++ b/sql-part-1/exercises/SQL-Demo-1.sql @@ -0,0 +1,25 @@ +select * + From formula_one.INFORMATION_SCHEMA.columns + Where Table_name='drivers' + + Select count(*) + From formula_one.dbo.drivers + where nationality ='british' + + select COUNT(DISTINCT driverId) + FROM formula_one.dbo.lap_times + where time < '0:57.0' + + #This is the additional comment + + USE formula_one + SELECT Top 100 * + From pit_stops + order by raceId, driverId + +--How many pit stops each driver take in each race they complte + Use formula_one + select MAX("stop") AS total_pit_stops + from pit_stops + GROUP BY raceId, driverId + ORDER BY raceId diff --git a/sql-part-2/exercises/SQL-Part-2-Exercises.ipynb b/sql-part-2/exercises/SQL-Part-2-Exercises.ipynb index 0ce26bb6e..160e2b09f 100644 --- a/sql-part-2/exercises/SQL-Part-2-Exercises.ipynb +++ b/sql-part-2/exercises/SQL-Part-2-Exercises.ipynb @@ -1,20 +1,11 @@ { - "metadata": { - "kernelspec": { - "name": "SQL", - "display_name": "SQL", - "language": "sql" - }, - "language_info": { - "name": "sql", - "version": "" - } - }, - "nbformat_minor": 2, - "nbformat": 4, "cells": [ { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "2b5a5976-8b51-4e24-a08d-234ef97f379a" + }, "source": [ "# Exercises\n", "\n", @@ -23,267 +14,310 @@ "## String Functions\n", "\n", "Write a query that returns the last 3 characters of the base name in other_FHV_services_jan_aug_2015. Do you see anything that is a common abbreviation at the end of business names?" - ], - "metadata": { - "azdata_cell_guid": "2b5a5976-8b51-4e24-a08d-234ef97f379a" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "392f7b72-9acf-44a4-bb53-6c29090c5d75", + "language": "sql", "tags": [], - "language": "sql" + "vscode": { + "languageId": "sql" + } }, "outputs": [ { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} + "ename": "SyntaxError", + "evalue": "invalid syntax (2162263096.py, line 3)", + "output_type": "error", + "traceback": [ + " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[8]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[31m \u001b[39m\u001b[31mRIGHT(base_name, 3) AS Last_3_Chars\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" + ] }, { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} + "ename": "", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n", + "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n", + "\u001b[1;31mClick here for more info. \n", + "\u001b[1;31mView Jupyter log for further details." + ] } ], - "execution_count": 8 + "source": [ + "SELECT \n", + "base_name,\n", + "RIGHT(base_name, 3) AS Last_3_Chars\n", + "FROM [dbo].[other_FHV_services_jan_aug_2015]" + ] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "The number of trips and the number of pickups are both stored as strings in other_FHV_services_jan_aug_2015. This is because the data provided included spaces in some of the numbers. Write a query that returns the location of spaces in both of these columns." - ], "metadata": { - "azdata_cell_guid": "6c206898-77f4-4357-8d17-33192980f45d" + "azdata_cell_guid": "6c206898-77f4-4357-8d17-33192980f45d", + "vscode": { + "languageId": "raw" + } }, - "attachments": {} + "source": [ + "The number of trips and the number of pickups are both stored as strings in other_FHV_services_jan_aug_2015. This is because the data provided included spaces in some of the numbers. Write a query that returns the location of spaces in both of these columns." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "3c810c3d-4e66-447b-8326-19e59d8a1b88", "language": "sql" }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 9 + "source": [] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "b138ac53-9fff-4320-9ff1-08717873f2ee" + }, "source": [ "## Date Functions\n", "\n", "For other_FHV_services_jan_aug_2015, display the name of month of the pickup date and order in descending order. Is the result of this query what you expected?" - ], - "metadata": { - "azdata_cell_guid": "b138ac53-9fff-4320-9ff1-08717873f2ee" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "8abd404c-a360-4b10-8d6b-8b34ef763bc7", - "tags": [], - "language": "sql" + "language": "sql", + "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 10 + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "Using other_FHV_services_jan_aug_2015, write a query that returns the day number of the pickup date and month name and orders it in ascending order by day number." - ], "metadata": { "azdata_cell_guid": "aa6bf15c-b847-45f0-ba0d-79c7636c4578" }, - "attachments": {} + "source": [ + "Using other_FHV_services_jan_aug_2015, write a query that returns the day number of the pickup date and month name and orders it in ascending order by day number." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "46dcd617-8dcf-4c15-b5fa-c0ec04f2bf29", "language": "sql" }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 11 + "source": [] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "348342a2-6039-43b1-8461-841288deee94" + }, "source": [ "## Aggregate Functions\n", "\n", "Write a query that returns the most easterly Lyft pickup." - ], - "metadata": { - "azdata_cell_guid": "348342a2-6039-43b1-8461-841288deee94" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "f2cb1b41-c92a-47ea-bd77-7bafd78af1d4", - "tags": [], - "language": "sql" + "language": "sql", + "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 12 + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "Write a query the returns the most northerly Lyft pickup." - ], "metadata": { "azdata_cell_guid": "bd589862-044d-4909-8565-8aa4771d9c00" }, - "attachments": {} + "source": [ + "Write a query the returns the most northerly Lyft pickup." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "189b7c25-0dfa-4ca0-a683-d402b3875abd", "language": "sql" }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 13 + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "Using other_FHV_services_jan_aug_2015, write a query that connects the the base number and the base name in a string that uses the following format: base_number: base_name." - ], "metadata": { "azdata_cell_guid": "674f8758-14bf-4712-b029-0ad0447617fb" }, - "attachments": {} + "source": [ + "Using other_FHV_services_jan_aug_2015, write a query that connects the the base number and the base name in a string that uses the following format: base_number: base_name." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "f6f4b247-63c0-4997-8769-204e37a55c08", "language": "sql" }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00" + "text/html": [ + "Total execution time: 00:00:00" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 14 + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.0" } - ] -} \ No newline at end of file + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/sql-part-2/exercises/SQL-Part-2-Exercises.sql b/sql-part-2/exercises/SQL-Part-2-Exercises.sql new file mode 100644 index 000000000..f5c983a6e --- /dev/null +++ b/sql-part-2/exercises/SQL-Part-2-Exercises.sql @@ -0,0 +1,37 @@ +SELECT +base_name, +RIGHT(base_name, 3) AS Last_3_Chars +FROM [dbo].[other_FHV_services_jan_aug_2015] + +SELECT +CHARINDEX(' ', Number_of_Trips) AS trip_space_position, +CHARINDEX(' ', Number_of_Vehicles) AS pickup_space_position +FROM [dbo].[other_FHV_services_jan_aug_2015] + + +SELECT +DATENAME(MONTH,Pick_Up_Date ) AS month_name +FROM [dbo].[other_FHV_services_jan_aug_2015] +ORDER BY MONTH(Pick_Up_Date) DESC; + + +SELECT +DATEPART(MONTH, Pick_Up_Date) AS month_number +FROM [dbo].[other_FHV_services_jan_aug_2015] +ORDER BY month_number ASC; + +SELECT MAX(start_lng) AS most_easterly_longitude +FROM [dbo].[lyft] + +SELECT TOP 1 * +FROM [dbo].[lyft] +ORDER BY start_lat DESC; + + +SELECT +CONCAT(Base_Number,':', Base_Name) AS base_info +FROM [dbo].[other_FHV_services_jan_aug_2015] + + + + diff --git a/sql-part-2/studio/SQL_Part-2-Studio.sql b/sql-part-2/studio/SQL_Part-2-Studio.sql new file mode 100644 index 000000000..85e579204 --- /dev/null +++ b/sql-part-2/studio/SQL_Part-2-Studio.sql @@ -0,0 +1,143 @@ +--1.  Create a query that returns the longest title in the dataset.  We can do this in two steps. +--A. Create a query that returns the length of the longest title. +-- B. Create a query that uses the length you found in step A to find the longest title. +-- Replace 'title' with the correct column name if it's different, e.g., 'book_title' + +SELECT MAX(LEN(title)) AS LongestTitleLength +FROM BooksDB.dbo.books + +-- Answer 186 Characters + + +--Part B + +SELECT title +FROM BooksDB.dbo.books +WHERE LEN(title) = ( + SELECT MAX(LEN(title)) + FROM BooksDB.dbo.books +); + + +--2.  Use what you learned in question 1 to find the shortest author name.   + +--A. Create a query that returns the length of the shortest author. + +--B. Create a query that returns the shortest author's name. + +Select MIN(LEN(authors)) AS ShortestAuthorLength +FROM BooksDB.dbo.books + +SELECT authors +FROM BooksDB.dbo.books +WHERE LEN(authors) = ( + SELECT MIN(LEN(authors)) + FROM BooksDB.dbo.books +); + +--3. How many titles contain the word "The"?   + +-- A. Is there a difference between the number of titles that use "The" or "the"? + +SELECT COUNT(*) AS TitlesWithThe +FROM BooksDB.dbo.books +WHERE title LIKE '%The%'; + +--OR +Select count(title) +FROM BooksDB.dbo.books +where CHARINDEX('The',title) >0 + +SELECT COUNT(*) AS TitlesWiththe +FROM BooksDB.dbo.books +WHERE title LIKE '%the%'; + +--both have same count of 4702 + + --4.How many authors' names _start_ with 'Z'? + +SELECT COUNT(*) AS AuthorsStartingWithZ +FROM BooksDB.dbo.books +WHERE authors LIKE 'Z%'; + +--or +SELECT COUNT(*) AS AuthorsStartingWithZ +FROM BooksDB.dbo.books +WHERE LEFT(authors, 1) = 'Z'; + + + +--5\. How many books have been identified as printed in a language other than English?  There are four language codes for English: 'en', 'eng', 'en-US', and 'en-UK'.  Use LEFT to answer the question.  +--(Do not use the wildcard) + +SELECT COUNT(*) AS NonEnglishBooks +FROM BooksDB.dbo.books +WHERE LEFT(language_code, 5) NOT IN ('en-US', 'en-UK') + AND LEFT(language_code, 3) NOT IN ('eng') + AND LEFT(language_code, 2) NOT IN ('en'); + + + --6\. Retry question 5 using SUBSTRING. + + SELECT COUNT(*) AS NonEnglishBooks +FROM BooksDB.dbo.books +WHERE SUBSTRING(language_code, 1, 5) NOT IN ('en-US', 'en-UK') + AND SUBSTRING(language_code, 1, 3) NOT IN ('eng') + AND SUBSTRING(language_code, 1, 2) NOT IN ('en'); + + --7.  Create a column that returns the title, authors, and language codes.  Concatenate these elements so that they return in the following way: title by authors in language\_code language. + +--A.  Check each selected column to see where any values are NULL.  Did any of the columns contain NULL values?  If so, which one? + +SELECT title, authors, language_code +FROM BooksDB.dbo.books +WHERE title IS NULL OR authors IS NULL OR language_code IS NULL; + + + +SELECT + title, + authors, + language_code, + CONCAT(title, ' by ', authors, ' in ', language_code, ' language') AS BookInfo +FROM BooksDB.dbo.books +WHERE title IS NOT NULL AND authors IS NOT NULL AND language_code IS NOT NULL; + + + +--8.  Update the query in question 7 using COALESCE to change the language code values from NULL to 'unknown'. + +-- A.  Has this changed the language\_code  where the values are NULL? + +SELECT + title, + authors, + COALESCE(language_code, 'unknown') AS language_code, + CONCAT(title, ' by ', authors, ' in ', COALESCE(language_code, 'unknown'), ' language') AS BookInfo +FROM BooksDB.dbo.books + +WHERE language_code IS NOT NULL; + + +--9 Revisit question 7 using ISNULL instead of COALESCE. + + +SELECT + title, + authors, + ISNULL(language_code, 'unknown') AS language_code, + CONCAT(title, ' by ', authors, ' in ', ISNULL(language_code, 'unknown'), ' language') AS BookInfo +FROM BooksDB.dbo.books + +-- A.  Has this changed the language\_code  where the values are NULL? + +WHERE language_code IS NOT NULL; + + + + + + + + + diff --git a/sql-part-3/exercises/SQL-Part-3-Exercises.ipynb b/sql-part-3/exercises/SQL-Part-3-Exercises.ipynb index 3b63aec8a..1870ce0b8 100644 --- a/sql-part-3/exercises/SQL-Part-3-Exercises.ipynb +++ b/sql-part-3/exercises/SQL-Part-3-Exercises.ipynb @@ -1,20 +1,10 @@ { - "metadata": { - "kernelspec": { - "name": "SQL", - "display_name": "SQL", - "language": "sql" - }, - "language_info": { - "name": "sql", - "version": "" - } - }, - "nbformat_minor": 2, - "nbformat": 4, "cells": [ { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "c739e118-2a3a-45f9-bd51-090c836e7a7e" + }, "source": [ "# SQL Part 3 Exercises: Joins\n", "\n", @@ -27,13 +17,13 @@ "In **questions 5-8**, you will be asked to join tables to find results about titles, tags, and the books users want to read.\n", "\n", "As you go through the questions, you will see 'Minimum Desired Output'. This will provide you with the bare minimum columns needed to answer the questions. When you write the queries, add as many additional columns as you need to best find your answers." - ], - "metadata": { - "azdata_cell_guid": "c739e118-2a3a-45f9-bd51-090c836e7a7e" - } + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "cdfaf133-068f-496d-8ecb-ecfde5c8d9f5" + }, "source": [ "## QUESTION 1: Exploring a `LEFT JOIN` using the `books` and `to_read` tables\n", "\n", @@ -42,18 +32,27 @@ "**Part A:** Look at Query 1, which table is the 'Left' table and which is the 'Right'?\n", "\n", "> Your Answer:\n", + "The left table is BooksDB.dbo.books and the right table is BooksDB.dbo.to_read.\n", "\n", "**Part B:** Using table 2, answer the following questions: \n", "- When we added a `WHERE tr.user_id IS NOT NULL` clause (line 14), how did the table change? Why?\n", "\n", - "> Your Answer:" - ], - "metadata": { - "azdata_cell_guid": "cdfaf133-068f-496d-8ecb-ecfde5c8d9f5" - } + "> Your Answer:filtered out all the rows where tr.user_id was NULL.\n", + "\n", + "This means any book that did not have a matching record in to_read got removed from the results." + ] }, { "cell_type": "code", + "execution_count": null, + "metadata": { + "azdata_cell_guid": "a2038d22-5f42-4539-af89-d1fd36c66d47", + "language": "sql", + "vscode": { + "languageId": "sql" + } + }, + "outputs": [], "source": [ "/*\n", "-- Query 1: LEFT JOIN\n", @@ -71,19 +70,13 @@ "WHERE tr.user_id IS NOT NULL\n", "ORDER BY b.average_rating;\n", "*/" - ], - "metadata": { - "vscode": { - "languageId": "sql" - }, - "azdata_cell_guid": "a2038d22-5f42-4539-af89-d1fd36c66d47", - "language": "sql" - }, - "outputs": [], - "execution_count": null + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "e5b293e1-3c99-4696-93db-71e77df50757" + }, "source": [ "## **QUESTION 2:** Exploring `RIGHT` joins with the `books` and `to_read` tables\n", "\n", @@ -91,18 +84,28 @@ "\n", "**Part A:** Looking at the query, which table is the 'Left' and which is the 'Right'?\n", "\n", - "> Your Answer:\n", + "> Your Answer:Left table: BooksDB.dbo.books (aliased as b) \n", + "\n", + "Right table: BooksDB.dbo.to_read (aliased as tr) — it appears after the RIGHT JOIN keyword.\n", "\n", "**Part B:** How do the RIGHT-joined tables differ from the LEFT-joined tables in Question 1?\n", "\n", - "> Your Answer:" - ], - "metadata": { - "azdata_cell_guid": "e5b293e1-3c99-4696-93db-71e77df50757" - } + "> Your Answer:Right joined table -Returns all rows from the to_read table, even if there’s no matching book in the books table.\n", + "LEFT JOIN keeps all books,\n", + "RIGHT JOIN keeps all to-read entries." + ] }, { "cell_type": "code", + "execution_count": null, + "metadata": { + "azdata_cell_guid": "3916ff86-e45b-47d3-ae94-c1ee7903c7b9", + "language": "sql", + "vscode": { + "languageId": "sql" + } + }, + "outputs": [], "source": [ "/*\n", "-- Query 1: RIGHT JOIN\n", @@ -111,19 +114,13 @@ "RIGHT JOIN BooksDB.dbo.to_read AS tr\n", "ON b.best_book_id = tr.book_id;\n", "*/" - ], - "metadata": { - "vscode": { - "languageId": "sql" - }, - "azdata_cell_guid": "3916ff86-e45b-47d3-ae94-c1ee7903c7b9", - "language": "sql" - }, - "outputs": [], - "execution_count": null + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "db92a0de-8cbe-47b2-a989-c77138c427fd" + }, "source": [ "## **QUESTION 3:** Exploring FULL JOINS with the `books` and `to_read` tables\n", "\n", @@ -132,34 +129,42 @@ "**Part A:** Look at the table and explore how it was populated. Try manipulating the query to better understand how this table works. Try adding a WHERE clause, or ORDER BY a column on the `books` table. Based on your exploration, can you think of when you might want a FULL join rather than a LEFT, RIGHT, or INNER?\n", "\n", "> Your Answer:" - ], - "metadata": { - "azdata_cell_guid": "db92a0de-8cbe-47b2-a989-c77138c427fd" - } + ] }, { "cell_type": "code", + "execution_count": null, + "metadata": { + "azdata_cell_guid": "421beb17-491d-4d0b-9a83-4383e9a878f6", + "language": "sql", + "vscode": { + "languageId": "sql" + } + }, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (30008201.py, line 1)", + "output_type": "error", + "traceback": [ + " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m \u001b[39m\u001b[31m-- FULL JOIN\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" + ] + } + ], "source": [ - "/*\n", + "\n", "-- FULL JOIN\n", "SELECT TOP 30 b.title, b.average_rating, b.books_count,tr.user_id, tr.book_id\n", "FROM BooksDB.dbo.books AS b\n", "FULL JOIN BooksDB.dbo.to_read AS tr\n", - "ON b.book_id = tr.book_id;\n", - "*/" - ], - "metadata": { - "vscode": { - "languageId": "sql" - }, - "azdata_cell_guid": "421beb17-491d-4d0b-9a83-4383e9a878f6", - "language": "sql" - }, - "outputs": [], - "execution_count": null + "ON b.book_id = tr.book_id;\n" + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "c9219b58-ba70-4f18-b40d-5a959f50ec10" + }, "source": [ "## **QUESTION 4:** Exploring INNER Joins with the `books` and `to_read` tables\n", "\n", @@ -167,22 +172,43 @@ "\n", "**Part A:** What does an inner join do?\n", "\n", - "> Your Answer: \n", + "> Your Answer: An INNER JOIN returns only the rows that have matching values in both tables \n", + "based on the join condition.\n", "\n", "**Part B:** Currently this table has an `'IS NOT NULL'` in the `WHERE` clause. Is this necessary for this table? Why or Why not?\n", "\n", - "> Your Answer:\n", + "> Your Answer:the WHERE b.title IS NOT NULL might not be necessary\n", + "INNER JOIN between books and to_read on book_id.\n", + "\n", + "For a row to appear in an INNER JOIN, there must be a matching book_id in the books table.\n", + "\n", + "Usually, a book with a valid book_id will also have a title.\n", "\n", "**Part C:** When using SQL, you are usually returning much larger tables so every line of code will add to the compilation and return time. Rewrite this inner join query so that it contains no redundant code.\n", "\n", - "> Your Answer: Update the query in the code box below." - ], - "metadata": { - "azdata_cell_guid": "c9219b58-ba70-4f18-b40d-5a959f50ec10" - } + "> Your Answer: SELECT TOP 30 \n", + " b.title, \n", + " b.average_rating, \n", + " b.books_count, \n", + " tr.user_id, \n", + " tr.book_id\n", + "FROM BooksDB.dbo.books AS b\n", + "INNER JOIN BooksDB.dbo.to_read AS tr\n", + " ON b.book_id = tr.book_id\n", + "ORDER BY tr.book_id;" + ] }, { "cell_type": "code", + "execution_count": null, + "metadata": { + "azdata_cell_guid": "6ee6b18f-d81b-46b8-857b-95e2e88bd1fd", + "language": "sql", + "vscode": { + "languageId": "sql" + } + }, + "outputs": [], "source": [ "/*\n", "-- INNER JOIN\n", @@ -193,19 +219,13 @@ "WHERE b.title IS NOT NULL\n", "ORDER BY tr.book_id;\n", "*/" - ], - "metadata": { - "vscode": { - "languageId": "sql" - }, - "azdata_cell_guid": "6ee6b18f-d81b-46b8-857b-95e2e88bd1fd", - "language": "sql" - }, - "outputs": [], - "execution_count": null + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "6c20039d-2496-42c6-b5fc-db8f1ded0ce4" + }, "source": [ "## **QUESTION 5:** Using joins to find the most tagged book and the most popular tag\n", "\n", @@ -227,35 +247,58 @@ "\n", "**Tag Id:**\n", "\n", + "SELECT TOP 1 \n", + " bt.tag_id,\n", + " COUNT(bt.tag_id) AS tag_usage_count\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.book_tags AS bt\n", + " ON b.best_book_id = bt.goodreads_book_id\n", + "WHERE b.title = 'Selected Poems'\n", + "GROUP BY \n", + " bt.tag_id\n", + "ORDER BY \n", + " tag_usage_count DESC;\n", + "\n", "**Part C:** What is this particular tag?\n", "\n", "You may return this answer with a simple query.\n", "\n", "*Minimum Desired Output:* The tag name for the most popular tag used for the most tagged book.\n", "\n", - "**Tag Name:**" - ], - "metadata": { - "azdata_cell_guid": "6c20039d-2496-42c6-b5fc-db8f1ded0ce4" - } + "**Tag Name:** SELECT tag_name\n", + "FROM BooksDB.dbo.tags\n", + "WHERE tag_id = 5207;" + ] }, { "cell_type": "code", - "source": [ - "-- Code Here" - ], + "execution_count": null, "metadata": { + "azdata_cell_guid": "c1d7f859-cf56-424e-bd90-0203ab5a1cdd", + "language": "sql", "vscode": { "languageId": "sql" - }, - "azdata_cell_guid": "c1d7f859-cf56-424e-bd90-0203ab5a1cdd", - "language": "sql" + } }, "outputs": [], - "execution_count": null + "source": [ + "SELECT TOP 1\n", + " b.title,\n", + " COUNT(bt.tag_id) AS tag_count\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.book_tags AS bt\n", + " ON b.best_book_id = bt.goodreads_book_id\n", + "GROUP BY \n", + " b.title\n", + "ORDER BY \n", + " tag_count DESC;" + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "0afe0108-c632-4cde-b7e0-5e699c066e03" + }, "source": [ "## QUESTION 6: Find a book based on a tag of your choice using joins.\n", "\n", @@ -265,9 +308,16 @@ "\n", "Here is an example. Alyce wanted to search for Halloween books. She used the wildcard, `%halloween%` and 8 different combinations were found. Alyce selected `halloween-storytime`, with a tag id of 13877.\n", "\n", - "*Minimum Desired Output:* tag name and tag id\n", + "*Minimum Desired Output:* tag name and tag id SELECT tag_name\n", + "FROM BooksDB.dbo.tags\n", + "WHERE tag_name LIKE '%Christmas%'\n", + "**Tag Name:** Christmas\n", + "\n", + "SELECT tag_id, tag_name\n", + "FROM BooksDB.dbo.tags\n", + "WHERE tag_name = 'christmas-winter';\n", "\n", - "**Your Tag and Tag Id:**\n", + "**Your Tag and Tag Id:** 7248\tchristmas-winter\n", "\n", "**Part B:** Now that you have the tag id, find the title that was tagged the most with this tag by joining the `books` and `books_tags` tables.\n", "\n", @@ -275,63 +325,103 @@ "\n", "*Minimum Desired Output:* title and tag count\n", "\n", - "**Your Title and Number of times the tag was used:**" - ], - "metadata": { - "azdata_cell_guid": "0afe0108-c632-4cde-b7e0-5e699c066e03" - } + "**Your Title and Number of times the tag was used:**\n", + "Snowmen at Night\t1" + ] }, { "cell_type": "code", - "source": [ - "-- Code Here:" - ], + "execution_count": null, "metadata": { + "azdata_cell_guid": "761b4d46-2218-486e-8336-cda901bc8551", + "language": "sql", "vscode": { "languageId": "sql" - }, - "azdata_cell_guid": "761b4d46-2218-486e-8336-cda901bc8551", - "language": "sql" + } }, "outputs": [], - "execution_count": null + "source": [ + "SELECT TOP 1 \n", + " b.title, \n", + " COUNT(bt.tag_id) AS tag_count\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.book_tags AS bt\n", + " ON b.best_book_id = bt.goodreads_book_id\n", + "WHERE bt.tag_id = 7248\n", + "GROUP BY b.title\n", + "ORDER BY tag_count DESC;-- Code Here:" + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "d684cef6-783d-43d1-a017-f5e5d83c46da" + }, "source": [ "## **QUESTION 7:** What are the top 10 most popular book titles on the 'to read' list?\n", "\n", "**Part A:** Explore how the `to_read` and `books` tables are organized, and then join them. What will you use as a key?\n", "\n", - "Your Answer:\n", + "Your Answer:SELECT TOP 10 \n", + " b.title,\n", + " COUNT(tr.book_id) AS times_on_list\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.to_read AS tr\n", + " ON b.book_id = tr.book_id\n", + "GROUP BY b.title\n", + "ORDER BY times_on_list DESC;\n", "\n", "**Part B:** Organize your newly joined table in a way that groups popularity based on the title based on users.\n", "\n", "*Hint:* Suggest using an alias for the aggregation you will need to run on the `user_id`\n", "\n", - "*Minimum Desired Output:* title and aliased column" - ], - "metadata": { - "azdata_cell_guid": "d684cef6-783d-43d1-a017-f5e5d83c46da" - } + "*Minimum Desired Output:* title and aliased column\n", + "SELECT \n", + " b.title,\n", + " COUNT(tr.user_id) AS user_count -- aliased column\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.to_read AS tr\n", + " ON b.book_id = tr.book_id\n", + "GROUP BY b.title\n", + "ORDER BY user_count DESC;" + ] }, { "cell_type": "code", - "source": [ - "-- Code Here:" - ], + "execution_count": null, "metadata": { + "azdata_cell_guid": "3247ef18-3603-47b0-b2a1-0b6a70e8de33", + "language": "sql", "vscode": { "languageId": "sql" - }, - "azdata_cell_guid": "3247ef18-3603-47b0-b2a1-0b6a70e8de33", - "language": "sql" + } }, - "outputs": [], - "execution_count": null + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (3649151683.py, line 1)", + "output_type": "error", + "traceback": [ + " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m \u001b[39m\u001b[31m-- Code Here:\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" + ] + } + ], + "source": [ + "-- Code Here:SELECT \n", + " b.title,\n", + " COUNT(tr.user_id) AS user_count -- aliased column\n", + "FROM BooksDB.dbo.books AS b\n", + "JOIN BooksDB.dbo.to_read AS tr\n", + " ON b.book_id = tr.book_id\n", + "GROUP BY b.title\n", + "ORDER BY user_count DESC;" + ] }, { "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "d7f2f6a3-ecc3-4629-aacd-312723da07af" + }, "source": [ "## **QUESTION 8:** Largest 'To Read' Lists\n", "\n", @@ -341,26 +431,55 @@ "\n", "_Minimum Desired Output:_ `user_id` and your aliased column of titles.\n", "\n", - "**Part B:** The longest list length is 15 titles total, and is shared by 4 different users. Select one of the uses and print out their entire 'to read' list." - ], - "metadata": { - "azdata_cell_guid": "d7f2f6a3-ecc3-4629-aacd-312723da07af" - } + "**Part B:** The longest list length is 15 titles total, and is shared by 4 different users. Select one of the uses and print out their entire 'to read' list.\n", + "SELECT TOP 10\n", + " tr.user_id,\n", + " COUNT(tr.book_id) AS titles_count -- aliased column\n", + "FROM BooksDB.dbo.to_read AS tr\n", + "GROUP BY tr.user_id\n", + "ORDER BY titles_count DESC;" + ] }, { "cell_type": "code", - "source": [ - "-- Code Here:" - ], + "execution_count": null, "metadata": { + "azdata_cell_guid": "a7ae1df0-4d43-4e27-b635-eed926d2311f", + "language": "sql", "vscode": { "languageId": "sql" - }, - "azdata_cell_guid": "a7ae1df0-4d43-4e27-b635-eed926d2311f", - "language": "sql" + } }, "outputs": [], - "execution_count": null + "source": [ + "-- Code Here:SELECT TOP 10\n", + " tr.user_id,\n", + " COUNT(tr.book_id) AS titles_count -- aliased column\n", + "FROM BooksDB.dbo.to_read AS tr\n", + "GROUP BY tr.user_id\n", + "ORDER BY titles_count DESC;" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.0" } - ] -} \ No newline at end of file + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/sql-part-3/exercises/SQL-Part-3-Exercises.sql b/sql-part-3/exercises/SQL-Part-3-Exercises.sql new file mode 100644 index 000000000..c957710bf --- /dev/null +++ b/sql-part-3/exercises/SQL-Part-3-Exercises.sql @@ -0,0 +1,263 @@ +# SQL Part 3 Exercises: Joins + +This notebook works with `BooksDB`. + +**Questions 1-4** focus on how joins work in a more general sense. If you are not sure how to best answer the questions, try manipulating the queries by changing the order of joins, the length of the TOP, or how they are ordered. + +Note: If some of the queries are not returning quickly, you can try closing and restarting Visual Studio Code after a few minutes. + +In **questions 5-8**, you will be asked to join tables to find results about titles, tags, and the books users want to read. + +As you go through the questions, you will see 'Minimum Desired Output'. This will provide you with the bare minimum columns needed to answer the questions. When you write the queries, add as many additional columns as you need to best find your answers. + +## QUESTION 1: Exploring a `LEFT JOIN` using the `books` and `to_read` tables + +The code block below has been commented out. To answer this question, you will need to uncomment it by removing the `/*` (line 1) and `*/` (line 16). + +**Part A:** Look at Query 1, which table is the 'Left' table and which is the 'Right'? + +> Your Answer: +The left table is BooksDB.dbo.books and the right table is BooksDB.dbo.to_read. + +**Part B:** Using table 2, answer the following questions: +- When we added a `WHERE tr.user_id IS NOT NULL` clause (line 14), how did the table change? Why? + +> Your Answer:filtered out all the rows where tr.user_id was NULL. + +This means any book that did not have a matching record in to_read got removed from the results. + +-- Query 1: LEFT JOIN + +SELECT TOP 50 b.title, b.average_rating, b.books_count,tr.user_id, tr.book_id +FROM BooksDB.dbo.books AS b +LEFT JOIN BooksDB.dbo.to_read AS tr +ON b.best_book_id = tr.book_id +ORDER BY b.average_rating; + +-- Query 2: LEFT JOIN USING 'IS NOT NULL' +SELECT TOP 50 b.title, b.average_rating, b.books_count,tr.user_id, tr.book_id +FROM BooksDB.dbo.books AS b +LEFT JOIN BooksDB.dbo.to_read AS tr +ON b.best_book_id = tr.book_id +WHERE tr.user_id IS NOT NULL +ORDER BY b.average_rating; + +## **QUESTION 2:** Exploring `RIGHT` joins with the `books` and `to_read` tables + +You will need to uncomment the query to answer the question. + +**Part A:** Looking at the query, which table is the 'Left' and which is the 'Right'? + +> Your Answer:Left table: BooksDB.dbo.books (aliased as b) + +Right table: BooksDB.dbo.to_read (aliased as tr) — it appears after the RIGHT JOIN keyword. + +**Part B:** How do the RIGHT-joined tables differ from the LEFT-joined tables in Question 1? + +> Your Answer:Right joined table -Returns all rows from the to_read table, even if there’s no matching book in the books table. +LEFT JOIN keeps all books, +RIGHT JOIN keeps all to-read entries. + +-- Query 1: RIGHT JOIN +SELECT TOP 300 b.title, b.average_rating, b.books_count, tr.user_id, tr.book_id +FROM BooksDB.dbo.books AS b +RIGHT JOIN BooksDB.dbo.to_read AS tr +ON b.best_book_id = tr.book_id; + +## **QUESTION 3:** Exploring FULL JOINS with the `books` and `to_read` tables + +You will need to uncomment the Query to answer the question. + +**Part A:** Look at the table and explore how it was populated. Try manipulating the query to better understand how this table works. Try adding a WHERE clause, or ORDER BY a column on the `books` table. Based on your exploration, can you think of when you might want a FULL join rather than a LEFT, RIGHT, or INNER? + +> Your Answer: + +-- FULL JOIN +SELECT TOP 30 b.title, b.average_rating, b.books_count,tr.user_id, tr.book_id +FROM BooksDB.dbo.books AS b +FULL JOIN BooksDB.dbo.to_read AS tr +ON b.book_id = tr.book_id; + +## **QUESTION 4:** Exploring INNER Joins with the `books` and `to_read` tables + +You will need to uncomment the Query to answer the question. + +**Part A:** What does an inner join do? + +> Your Answer: An INNER JOIN returns only the rows that have matching values in both tables +based on the join condition. + +**Part B:** Currently this table has an `'IS NOT NULL'` in the `WHERE` clause. Is this necessary for this table? Why or Why not? + +> Your Answer:the WHERE b.title IS NOT NULL might not be necessary +INNER JOIN between books and to_read on book_id. + +For a row to appear in an INNER JOIN, there must be a matching book_id in the books table. + +Usually, a book with a valid book_id will also have a title. + +**Part C:** When using SQL, you are usually returning much larger tables so every line of code will add to the compilation and return time. Rewrite this inner join query so that it contains no redundant code. + +> Your Answer: SELECT TOP 30 + b.title, + b.average_rating, + b.books_count, + tr.user_id, + tr.book_id +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.to_read AS tr + ON b.book_id = tr.book_id +ORDER BY tr.book_id; + +-- INNER JOIN +SELECT TOP 30 b.title, b.average_rating, b.books_count,tr.user_id, tr.book_id +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.to_read AS tr +ON b.book_id = tr.book_id +WHERE b.title IS NOT NULL +ORDER BY tr.book_id; + +## **QUESTION 5:** Using joins to find the most tagged book and the most popular tag + +We will be writing 3 queries to find both the most tagged book and that book's most popular tag. + +**Part A:** What is the most tagged book? + +Start by joining the `books` and `book_tags` tables ON the `books.best_book_id` and `book_tags.goodreads_book_id`. We want the *most popular* book, so think about ordering the table in a way that will display both the book title and the number of times a book tag has been used. + +Minimum Desired output:_ The title of the most tagged book, and the number of times the book has been tagged. + +**Title:** + +**Part B:** How many different tags have been used for the most tagged book? + +Start by joining the `books` and `book_tags` tables ON the `books.best_book_id` and `book_tags.goodreads_book_id`. We want to find the *most popular* tag id, so think about ordering in a way that will display the most popular tag id. + +*Minimum Desired Output:* The tag id for the most popular tag used for the most tagged book. + +**Tag Id:** + +SELECT TOP 1 + bt.tag_id, + COUNT(bt.tag_id) AS tag_usage_count +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +WHERE b.title = 'Selected Poems' +GROUP BY + bt.tag_id +ORDER BY + tag_usage_count DESC; + +**Part C:** What is this particular tag? + +You may return this answer with a simple query. + +*Minimum Desired Output:* The tag name for the most popular tag used for the most tagged book. + +**Tag Name:** SELECT tag_name +FROM BooksDB.dbo.tags +WHERE tag_id = 5207; +SELECT TOP 1 + b.title, + COUNT(bt.tag_id) AS tag_count +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +GROUP BY + b.title +ORDER BY + tag_count DESC; +## QUESTION 6: Find a book based on a tag of your choice using joins. + +Some suggestions: any hobbies you like? baking, drawing, etc. how about favorite holidays, subjects, animals, etc? + +**Part A:** Explore the tags table for a tag of your choice. Suggested ideas, try searching for one of your hobbies, a favorite time of year, favorite animal, etc. Start by querying the tag table for your chosen tag. (_Hint:_ in order to make sure you find all combinations of your tags, use the wildcard). If your query returns more than one result, pick your favorite. + +Here is an example. Alyce wanted to search for Halloween books. She used the wildcard, `%halloween%` and 8 different combinations were found. Alyce selected `halloween-storytime`, with a tag id of 13877. + +*Minimum Desired Output:* tag name and tag id SELECT tag_name +FROM BooksDB.dbo.tags +WHERE tag_name LIKE '%Christmas%' +**Tag Name:** Christmas + +SELECT tag_id, tag_name +FROM BooksDB.dbo.tags +WHERE tag_name = 'christmas-winter'; + +**Your Tag and Tag Id:** 7248 christmas-winter + +**Part B:** Now that you have the tag id, find the title that was tagged the most with this tag by joining the `books` and `books_tags` tables. + +Alyce joined the book table with the tags table and discovered that "The Little Old Lady Who Was Not Afraid of Anything" was tagged as `halloween-storytime` the most. + +*Minimum Desired Output:* title and tag count + +**Your Title and Number of times the tag was used:** +Snowmen at Night 1 +SELECT TOP 1 + b.title, + COUNT(bt.tag_id) AS tag_count +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +WHERE bt.tag_id = 7248 +GROUP BY b.title +ORDER BY tag_count DESC;-- Code Here: +## **QUESTION 7:** What are the top 10 most popular book titles on the 'to read' list? + +**Part A:** Explore how the `to_read` and `books` tables are organized, and then join them. What will you use as a key? + +Your Answer:SELECT TOP 10 + b.title, + COUNT(tr.book_id) AS times_on_list +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.to_read AS tr + ON b.book_id = tr.book_id +GROUP BY b.title +ORDER BY times_on_list DESC; + +**Part B:** Organize your newly joined table in a way that groups popularity based on the title based on users. + +*Hint:* Suggest using an alias for the aggregation you will need to run on the `user_id` + +*Minimum Desired Output:* title and aliased column +SELECT + b.title, + COUNT(tr.user_id) AS user_count -- aliased column +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.to_read AS tr + ON b.book_id = tr.book_id +GROUP BY b.title +ORDER BY user_count DESC; +-- Code Here:SELECT + b.title, + COUNT(tr.user_id) AS user_count -- aliased column +FROM BooksDB.dbo.books AS b +JOIN BooksDB.dbo.to_read AS tr + ON b.book_id = tr.book_id +GROUP BY b.title +ORDER BY user_count DESC; +## **QUESTION 8:** Largest 'To Read' Lists + +**Part A:** Create a query that returns a table that contains the top 10 users with the most number of titles on their 'to read' list. Group all the entries by `user_id`. + +_Hint:_ You might want an alias for the titles. + +_Minimum Desired Output:_ `user_id` and your aliased column of titles. + +**Part B:** The longest list length is 15 titles total, and is shared by 4 different users. Select one of the uses and print out their entire 'to read' list. +SELECT TOP 10 + tr.user_id, + COUNT(tr.book_id) AS titles_count -- aliased column +FROM BooksDB.dbo.to_read AS tr +GROUP BY tr.user_id +ORDER BY titles_count DESC; + +-- Code Here: +SELECT TOP 10 + tr.user_id, + COUNT(tr.book_id) AS titles_count -- aliased column +FROM BooksDB.dbo.to_read AS tr +GROUP BY tr.user_id +ORDER BY titles_count DESC; diff --git a/sql-part-3/exercises/sql-Part-3-demos.sql b/sql-part-3/exercises/sql-Part-3-demos.sql new file mode 100644 index 000000000..dd806ddff --- /dev/null +++ b/sql-part-3/exercises/sql-Part-3-demos.sql @@ -0,0 +1,102 @@ +--Which circuit did each race take place at(across all years)? +--circuit table : circuitId,name +--races:years,name,circuitId,date +SELECT + races.name AS race_name, + races.year AS race_year, + races.date AS race_date, + cir.name AS circuit_name +FROM formula_one.dbo.races AS races +INNER JOIN formula_one.dbo.circuits AS cir + ON races.circuitId = cir.circuitId; +-- If you intended to enable READ_COMMITTED_SNAPSHOT, run: +-- ALTER DATABASE [YourDatabaseName] SET READ_COMMITTED_SNAPSHOT ON; + +--I want the pitstop data, but with race name instead of race_id +--pitstop: raceId,driverId,stop,lap,time,duration,milliseconds +--races: raceId,name,year + +SELECT races.year,races.name,pit.driverId,pit.stop,pit.lap,pit.time,pit.duration,pit.milliseconds +FROM formula_one.dbo.races AS races +LEFT JOIN formula_one.dbo.pit_stops AS pit +ON races.raceId=pit.raceId +WHERE pit.raceId IS NULL + +--Which circuits hosted races in 2021? +--year,name of race,name of circuit + +SELECT r.YEAR,r.name AS race_name,cir.name AS circuit_name +FROM formula_one.dbo.races AS r +INNER JOIN formula_one.dbo.circuits AS cir +ON r.circuitId=cir.circuitId +WHERE r.year=2021 +ORDER BY cir.name + +--who won each race in 2021? +--I want a table with first and last name of the winners,and the name of the race that they won +--names are in drivers table,race name is in races table and position (where 1 =winner)is in result table) + +SELECT r.name AS race_name, +d.forename + ' ' + d.surname AS winner_name +FROM formula_one.dbo.results AS res +INNER JOIN formula_one.dbo.races AS r +ON res.raceId=r.raceId +INNER JOIN formula_one.dbo.drivers AS d +ON res.driverId=d.driverId +WHERE r.year=2021 AND res.position=1 AND res.position <> '\N' + +--how many races has each circuit held? +--circuit table(name),and races table (raceID) + +SELECT cir.name AS circuit_name, +COUNT(r.raceId) AS total_races +FROM formula_one.dbo.circuits AS cir +LEFT JOIN formula_one.dbo.races AS r +ON cir.circuitId=r.circuitId +GROUP BY cir.name +ORDER BY total_races DESC + +--How many races did each driver participate in 2021? +--drivers(name),results(driverId),races(raceId) + +SELECT +d.forename + ' ' + d.surname AS driver_name, +COUNT(res.resultId) AS races_entered +FROM formula_one.dbo.drivers AS d +INNER JOIN formula_one.dbo.results AS res ON d.driverId=res.driverId +INNER JOIN formula_one.dbo.races AS r ON res.raceId = r.raceId +WHERE r.year = 2021 +GROUP BY d.forename,d.surname +ORDER BY races_entered DESC + +--How many races have been at each circuit? + +SELECT cir.name AS circuit_name, +COUNT(r.raceId) AS total_races +FROM formula_one.dbo.circuits AS cir +LEFT JOIN formula_one.dbo.races AS r + ON cir.circuitId = r.circuitId AND r.year >= 2000 +GROUP BY cir.name +HAVING COUNT(r.raceId) > 5 + +--How many races been won by drivers of each nationality? + +SELECT +--d.forename + ' ' + d.surname AS winner_name, +d.nationality ,COUNT(nationality) as number_of_wins +FROM formula_one.dbo.results AS res +INNER JOIN formula_one.dbo.races AS r +ON res.raceId=r.raceId +INNER JOIN formula_one.dbo.drivers AS d +ON res.driverId=d.driverId +WHERE res.position=1 AND res.position <> '\N' +GROUP BY d.nationality +HAVING d.nationality IN ('British','Canadian','Australian','American') +ORDER BY number_of_wins DESC + + + + + + + diff --git a/sql-part-3/studio/SQL-Part-3-Studio.ipynb b/sql-part-3/studio/SQL-Part-3-Studio.ipynb index eea5af39a..69fab7a6d 100644 --- a/sql-part-3/studio/SQL-Part-3-Studio.ipynb +++ b/sql-part-3/studio/SQL-Part-3-Studio.ipynb @@ -50,7 +50,7 @@ }, "outputs": [], "source": [ - "-- Solution" + "--solution" ] }, { diff --git a/sql-part-3/studio/SQL-Part-3-Studio.sql b/sql-part-3/studio/SQL-Part-3-Studio.sql new file mode 100644 index 000000000..43a131c44 --- /dev/null +++ b/sql-part-3/studio/SQL-Part-3-Studio.sql @@ -0,0 +1,107 @@ +--Highlight popular women writers based on ratings from `BooksDB` by writing a query that +-- returns `tag_id`, the number of times each `tag_id` is used and the `tag_name`. Use the `GROUP BY` and `HAVING` clause to narrow your +--focus and try multiple keywords, such as "woman" and "female" + +SELECT * +FROM BooksDB.dbo.tags +WHERE tag_name LIKE '%woman%' OR tag_name LIKE '%female%' +ORDER BY tag_name; + + + +SELECT + t.tag_id, + t.tag_name, + COUNT(bt.tag_id) AS tag_count +FROM BooksDB.dbo.book_tags AS bt +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%woman%' OR t.tag_name LIKE '%female%' +GROUP BY + t.tag_id, + t.tag_name +ORDER BY + tag_count DESC; + + + --### Event 2: Choose another event from March/Spring + +--Write a query to return authors, titles, + --ratings, and `tag_id` that you would want to promote during your chosen event. + + SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%Christmas%' -- filter by your event theme +ORDER BY b.average_rating DESC; + +--# Part 2: Choose Another Month + +--Choose another month and plan at least 2 events / promotions and answer the following questions: +1. Which month did you choose? September +1. What 2 events / promotions are you highlighting? Back to School and Autumn + +--# Part 3: Summarize your Work + +For each event write at least one query that joins any two tables in `BooksDB` to +support your choice and record you thoughts as to why you used the paticlular query. + At least one of your queries needs to include a `HAVING` clause. + + --Query joins books and book_tags to find books tagged with School + + +SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + --t.tag_id, + --t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%School%' -- filter by your event theme + +ORDER BY b.average_rating DESC; + + + +--Event 2: Autumn or Fall + +--Query joins books and book_tags to find books tagged with Autumn or Fall +SELECT DISTINCT + b.authors AS author, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +FROM BooksDB.dbo.books AS b +INNER JOIN BooksDB.dbo.book_tags AS bt + ON b.best_book_id = bt.goodreads_book_id +INNER JOIN BooksDB.dbo.tags AS t + ON bt.tag_id = t.tag_id +WHERE t.tag_name LIKE '%Autumn%' +GROUP BY + b.authors, + b.title, + b.average_rating, + t.tag_id, + t.tag_name +HAVING b.average_rating > 4.0 +ORDER BY b.average_rating DESC; + + + + + + + diff --git a/sql-part-4/exercises/SQL-Part-4-Exercises.ipynb b/sql-part-4/exercises/SQL-Part-4-Exercises.ipynb index 5e3c18ec6..a20bb64e2 100644 --- a/sql-part-4/exercises/SQL-Part-4-Exercises.ipynb +++ b/sql-part-4/exercises/SQL-Part-4-Exercises.ipynb @@ -1,203 +1,126 @@ { - "metadata": { - "kernelspec": { - "name": "SQL", - "display_name": "SQL", - "language": "sql" - }, - "language_info": { - "name": "sql", - "version": "" - } - }, - "nbformat_minor": 2, - "nbformat": 4, "cells": [ { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "10006a10-882f-4f55-8d42-f36044fdb6c7" + }, "source": [ "# Exercises: Complex queries\n", "\n", "For the exercises, you are tasked with writing five queries that will help you delve deeper into BooksDB. You can choose whether you want to use a correlated subquery, a nested subquery, the UNION operator, the INTERSECT operator, or the EXCEPT operator for each one. You may not use joins or add multiple statements to the WHERE clause.\n", "\n", "1. Write a query that will return the number of users who rated a book above it's average rating." - ], - "metadata": { - "azdata_cell_guid": "10006a10-882f-4f55-8d42-f36044fdb6c7" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "203eb95e-6585-435f-8a8e-bfa0dfe6f7c0", "tags": [] }, - "outputs": [ - { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} - }, - { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} - } - ], - "execution_count": 1 + "outputs": [], + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "2. Write a query that returns the book ids of all books that have over 1000 ratings of 1 star or over 1000 ratings of 5 stars." - ], "metadata": { "azdata_cell_guid": "7f849931-6c9c-4cd9-b3ba-66871052673d" }, - "attachments": {} + "source": [ + "2. Write a query that returns the book ids of all books that have over 1000 ratings of 1 star or over 1000 ratings of 5 stars." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "bce732e3-1590-457b-b1f9-5319345ff790" }, - "outputs": [ - { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} - }, - { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} - } - ], - "execution_count": 2 + "outputs": [], + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "3. Write a query that returns the book ids of all books that have over 1000 ratings of 1 star and over 1000 ratings of 5 stars." - ], "metadata": { "azdata_cell_guid": "9c53b866-c8e8-465e-b089-7702b191a15e" }, - "attachments": {} + "source": [ + "3. Write a query that returns the book ids of all books that have over 1000 ratings of 1 star and over 1000 ratings of 5 stars." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "43e39973-5a29-45ff-b2a9-9c658a19c296" }, - "outputs": [ - { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} - }, - { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} - } - ], - "execution_count": 3 + "outputs": [], + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "4. Write a query that returns the book ids of books that have a language code of \"en-US\" and not a langugae code of \"en-GB\"." - ], "metadata": { "azdata_cell_guid": "2bd4844b-83af-490f-97cd-fdc1fa2944ec" }, - "attachments": {} + "source": [ + "4. Write a query that returns the book ids of books that have a language code of \"en-US\" and not a langugae code of \"en-GB\"." + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "ba5a1b61-19c0-4d70-ae8d-2daae6ae1e21" }, - "outputs": [ - { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} - }, - { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} - } - ], - "execution_count": 4 + "outputs": [], + "source": [] }, { + "attachments": {}, "cell_type": "markdown", - "source": [ - "5. Write a query that returns the names of the tags and the tag ids for tags that were used over 100,000 times for a book. " - ], "metadata": { "azdata_cell_guid": "6ddd588f-a84c-4c77-93ac-e8c8bd21d0f5" }, - "attachments": {} + "source": [ + "5. Write a query that returns the names of the tags and the tag ids for tags that were used over 100,000 times for a book. " + ] }, { "cell_type": "code", - "source": [ - "" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "90f61ad7-65cb-4ea8-85a3-d8c815cfe347", "tags": [] }, - "outputs": [ - { - "output_type": "display_data", - "data": { - "text/html": "Commands completed successfully." - }, - "metadata": {} - }, - { - "output_type": "display_data", - "data": { - "text/html": "Total execution time: 00:00:00" - }, - "metadata": {} - } - ], - "execution_count": 5 + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.0" } - ] -} \ No newline at end of file + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/sql-part-4/exercises/SQL-Part-4-Exercises.sql b/sql-part-4/exercises/SQL-Part-4-Exercises.sql new file mode 100644 index 000000000..b8e9674c1 --- /dev/null +++ b/sql-part-4/exercises/SQL-Part-4-Exercises.sql @@ -0,0 +1,81 @@ +# Exercises: Complex queries + +For the exercises, you are tasked with writing five queries that will help you delve deeper into BooksDB. You can choose whether you want to use a correlated subquery, a nested subquery, the UNION operator, the INTERSECT operator, or the EXCEPT operator for each one. You may not use joins or add multiple statements to the WHERE clause. + +1. Write a query that will return the number of users who rated a book above its average rating. + + +-- Count distinct users who gave a rating higher than that book's average rating + + +SELECT COUNT(DISTINCT r.user_id) AS users_above_avg +FROM BooksDB.dbo.ratings AS r +WHERE r.rating > ( + SELECT AVG(r2.rating) + FROM BooksDB.dbo.ratings AS r2 + WHERE r2.book_id = r.book_id +); +--Answer- 49382 + +2. Write a query that returns the book ids of all books that have over 1000 ratings of 1 star +or over 1000 ratings of 5 stars. + +SELECT book_id +FROM BooksDB.dbo.ratings +WHERE rating = 1 +GROUP BY book_id +HAVING COUNT(*) > 1000 + +UNION + +SELECT book_id +FROM BooksDB.dbo.ratings +WHERE rating = 5 +GROUP BY book_id +HAVING COUNT(*) > 1000; + +3. Write a query that returns the book ids of all books that have over +1000 ratings of 1 star and over 1000 ratings of 5 stars. + +SELECT book_id +FROM BooksDB.dbo.ratings +WHERE rating = 1 +GROUP BY book_id +HAVING COUNT(*) > 1000 +INTERSECT +SELECT book_id +FROM BooksDB.dbo.ratings +WHERE rating = 5 +GROUP BY book_id +HAVING COUNT(*) > 1000; + +4.Write a query that returns the book ids of books that have a language code of "en-US" +and not a langugae code of "en-GB". + +SELECT book_id +FROM BooksDB.dbo.books +WHERE language_code = 'en-US' +EXCEPT +SELECT book_id +FROM BooksDB.dbo.books +WHERE language_code = 'en-GB'; + +--Answers- 2070 rows + + +5. Write a query that returns the names of the tags and the tag ids for tags that were +used over 100,000 times for a book. + +SELECT tag_id, tag_name +FROM BooksDB.dbo.tags AS t +WHERE ( + SELECT COUNT(*) + FROM BooksDB.dbo.book_tags AS bt + WHERE bt.tag_id = t.tag_id +) > 1000 +--Answers-186 rows + + + + + diff --git a/sql-part-4/studio/SQL-Part-4-Studio.ipynb b/sql-part-4/studio/SQL-Part-4-Studio.ipynb index 1a394fcbd..c870344d5 100644 --- a/sql-part-4/studio/SQL-Part-4-Studio.ipynb +++ b/sql-part-4/studio/SQL-Part-4-Studio.ipynb @@ -1,157 +1,155 @@ { - "metadata": { - "kernelspec": { - "name": "SQL", - "display_name": "SQL", - "language": "sql" - }, - "language_info": { - "name": "sql", - "version": "" - }, - "extensions": { - "vscode": { - "version": 1, - "views": [] - } - } - }, - "nbformat_minor": 2, - "nbformat": 4, "cells": [ { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "3ea3f8a2-b444-4354-be8b-eebc139b3c13" + }, "source": [ "# SQL Part 4 Studio\n", "\n", "For this studio, you will be working in small groups and using the BooksDB.  One group member should screen share while fellow group members code along in their own notebooks.  Each group member will submit a link to their studio notebook.\n", "\n", "You are back at the bookstore helping employees with their inventory of books.   Four employees need your help with finding books to create in-store displays.  Read their requests and decide if you want to use a correlated subquery, nested subquery, UNION operator, EXCEPT operator, or INTERSECT operator.  You may not use any joins or add multiple statements to the WHERE clause unless explicitly asked." - ], - "metadata": { - "azdata_cell_guid": "3ea3f8a2-b444-4354-be8b-eebc139b3c13" - }, - "attachments": {} + ] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "5c8b1c77-0878-4dc6-8e79-7f64e5e1df0d" + }, "source": [ "## QUESTION 1:  Willow\n", "\n", "Willow wants a list of book titles that have multiple authors attributed to them.  Write a query to return her desired results." - ], - "metadata": { - "azdata_cell_guid": "5c8b1c77-0878-4dc6-8e79-7f64e5e1df0d" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "-- Code here:" - ], + "execution_count": null, "metadata": { "azdata_cell_guid": "46c76d2f-acbc-4fd2-9c2a-367044fda616", "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00.080" + "text/html": [ + "Total execution time: 00:00:00.080" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 1 + "source": [ + "-- Code here:\n", + "SELECT top 5 *" + ] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "06f2a08a-a54e-484e-8053-c74594da9db2" + }, "source": [ "## QUESTION 2: Ira\n", "\n", "Ira was asked by a customer for titles that have been tagged \"Meditation\".  As you create a query for Ira, think about how the tables in BooksDB are organized as you write your query." - ], - "metadata": { - "azdata_cell_guid": "06f2a08a-a54e-484e-8053-c74594da9db2" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "-- Code here:" - ], + "execution_count": 2, "metadata": { "azdata_cell_guid": "552924f9-a1cc-4979-8f53-15ba959550c2", "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00.049" + "text/html": [ + "Total execution time: 00:00:00.049" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 2 + "source": [ + "-- Code here:" + ] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "1d758d74-b4f0-4836-bdfe-d7280b5b4592" + }, "source": [ "## QUESTION 3:  Alyce\n", "\n", "Alyce wants to create a display of books with an average rating of 4.2 or higher, but she only wants books that share both title and original title.  Write a query that displays both the original title and title for Alyce, in descending order by rating.  Make sure that none of the original titles contain NULL values either." - ], - "metadata": { - "azdata_cell_guid": "1d758d74-b4f0-4836-bdfe-d7280b5b4592" - }, - "attachments": {} + ] }, { "cell_type": "code", - "source": [ - "-- Code here:" - ], + "execution_count": 3, "metadata": { "azdata_cell_guid": "2c693b4e-6987-4c49-ba55-61094e677608", "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00.048" + "text/html": [ + "Total execution time: 00:00:00.048" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 3 + "source": [ + "-- Code here:" + ] }, { + "attachments": {}, "cell_type": "markdown", + "metadata": { + "azdata_cell_guid": "c3cb4fa8-802c-4130-8740-2adf20ec6a15" + }, "source": [ "## QUESTION 4:  Thisbe\n", "\n", @@ -160,38 +158,67 @@ "**Part A:**   Write a query that compares the publication time with average reader ratings.\n", "\n", "**Part B:**  She wants the list ordered by year, then the book title" - ], - "metadata": { - "azdata_cell_guid": "c3cb4fa8-802c-4130-8740-2adf20ec6a15" - }, - "attachments": {} + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [] }, { "cell_type": "code", - "source": [ - "-- Code here:" - ], + "execution_count": 4, "metadata": { "azdata_cell_guid": "164e0a22-349f-45ed-afe8-0753d5a8c6fc", "tags": [] }, "outputs": [ { - "output_type": "display_data", "data": { - "text/html": "Commands completed successfully." + "text/html": [ + "Commands completed successfully." + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" }, { - "output_type": "display_data", "data": { - "text/html": "Total execution time: 00:00:00.051" + "text/html": [ + "Total execution time: 00:00:00.051" + ] }, - "metadata": {} + "metadata": {}, + "output_type": "display_data" } ], - "execution_count": 4 + "source": [ + "-- Code here:" + ] } - ] -} \ No newline at end of file + ], + "metadata": { + "extensions": { + "vscode": { + "version": 1, + "views": [] + } + }, + "kernelspec": { + "display_name": "SQL", + "language": "sql", + "name": "SQL" + }, + "language_info": { + "name": "sql", + "version": "" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/sql-part-4/studio/SQL-Part-4-Studio.sql b/sql-part-4/studio/SQL-Part-4-Studio.sql new file mode 100644 index 000000000..c85b68fbd --- /dev/null +++ b/sql-part-4/studio/SQL-Part-4-Studio.sql @@ -0,0 +1,93 @@ +## QUESTION 1:  Willow + +Willow wants a list of book titles that have multiple authors attributed to them.  + Write a query to return her desired results. + +SELECT title,authors + +FROM + BooksDB.dbo.books AS b +where ( + select count(*) + from BooksDB.dbo.books AS b2 + where b2.title =b.title +)>1 +order by title, authors; + +--Answer- 69 rows affected + +## QUESTION 2: Ira + +Ira was asked by a customer for titles that have been tagged "Meditation".  +As you create a query for Ira, think about how the tables +in BooksDB are organized as you write your query. + +SELECT b.title + +FROM BooksDB.dbo.books as b + +WHERE b.book_id IN + + ( + + SELECT b_tags.goodreads_book_id + + FROM BooksDB.dbo.book_tags as b_tags + + WHERE b_tags.tag_id IN + + ( + + SELECT tag.tag_id + + FROM BooksDB.dbo.tags as tag + + WHERE tag.tag_name LIKE '%Meditation%' + + ) + + ) + +--Answer 44 rows + +## QUESTION 3:  Alyce +Alyce wants to create a display of books with an average rating of 4.2 or + higher, but she only wants books that share both title and original title.  Write a query that displays both the original title and title for Alyce, in descending order by rating.  + Make sure that none of the original titles contain NULL values either. + + +SELECT original_title, title, average_rating +FROM BooksDB.dbo.books +WHERE book_id IN ( + SELECT book_id + FROM BooksDB.dbo.book_tags +) +AND original_title IS NOT NULL +ORDER BY average_rating DESC; + +--Answer 9410 rows + +-- QUESTION 4: Thisbe +-- +-- Thisbe is planning to make a long-term display of popular books that she will update monthly, +-- reflecting different time periods. She wants to make it reader-centric by including titles that +-- readers have averagely rated higher than the book's actual average rating. + + +SELECT title, + original_publication_year, + average_rating AS book_avg_rating, + ( + SELECT AVG(rating) + FROM BooksDB.dbo.ratings AS r + WHERE r.book_id = b.book_id + ) AS reader_avg_rating +FROM BooksDB.dbo.books AS b +WHERE average_rating < ( + SELECT AVG(rating) + FROM BooksDB.dbo.ratings AS r + WHERE r.book_id = b.book_id +) +ORDER BY original_publication_year, title; + +Answer- 178 rows \ No newline at end of file diff --git a/sql-part-5/exercises/Sql-part-5-demo.sql b/sql-part-5/exercises/Sql-part-5-demo.sql new file mode 100644 index 000000000..39675190d --- /dev/null +++ b/sql-part-5/exercises/Sql-part-5-demo.sql @@ -0,0 +1,73 @@ +--Create a table +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.Customers( + customer_id INT IDENTITY(1,1) PRIMARY KEY, + first_name VARCHAR(50) NOT NULL, + last_name VARCHAR(50) NOT NULL, + email VARCHAR(100), + subscription VARCHAR(50), + join_date DATE DEFAULT CAST(GETDATE() AS DATE) +) ; + +Select * FROM Sep2025JunkDB.madhuri_chaudhari.Customers + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.Customers(first_name,last_name,email,subscription) +VALUES('Ava','Rodriguez','ava.abcd@email.com','pro'), +('Liam','Patel','liam.patel@email.com','free'), +('Noah','chen','noah.chen@email.com','basic'); + +UPDATE Sep2025JunkDB.madhuri_chaudhari.Customers +SET email = 'noah.chen@newdomain.com' +--WHERE first_name = 'Noah' AND last_name ='Chen' +WHERE customer_id= 3 + +--CTE /temp table + +SELECT * +INTO #payingcutomers +FROM Sep2025JunkDB.madhuri_chaudhari.Customers +WHERE subscription <> 'free' + +SELECT * from #payingcutomers; + +--Temp table from scratch +CREATE TABLE #TempSales( + sales_id INT IDENTITY(1,1) PRIMARY KEY, + product_name VARCHAR(100), + quantity INT, + sale_data DATE DEFAULT GETDATE() +); +--inserting data manually + +INSERT INTO #TempSales (product_name,quantity) +VALUES ('Notebook',5) ,('Pencil',20); + +SELECT * FROM #TempSales + +--Delete +DELETE FROM +Sep2025JunkDB.madhuri_chaudhari.Customers +WHERE email LIKE '%newdomain.com%' + +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.Customers + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.Orders +( + order_id INT PRIMARY KEY IDENTITY (1,1), + customer_id INT FOREIGN KEY REFERENCES Sep2025JunkDB.madhuri_chaudhari.Customers(customer_id), + order_date DATE DEFAULT GETDATE(), + total_amount DECIMAL(10,2) + +); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.Orders(customer_id,total_amount) +VALUES(1,249.99),(2,175.50); + +DELETE FROM Sep2025JunkDB.madhuri_chaudhari.Customers +WHERE customer_id= 2; + +--Dropping table -entire table + +DROP TABLE Sep2025JunkDB.madhuri_chaudhari.Orders + +--SELECT *FROM Sep2025JunkDB.madhuri_chaudhari.Orders + diff --git a/sql-part-5/studio/SQL-Part-5-Studio.sql b/sql-part-5/studio/SQL-Part-5-Studio.sql new file mode 100644 index 000000000..e61815a9f --- /dev/null +++ b/sql-part-5/studio/SQL-Part-5-Studio.sql @@ -0,0 +1,615 @@ +--Part A +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.book +( + book_id INT IDENTITY(1,1) PRIMARY KEY, + author_id INT, + title VARCHAR(255), + isbn INT, + available BIT, + genre_id INT +); + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.book + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (2, 'A Midsummers Night Dream', 978149413, 1, 23) + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (2, 'Romeo and Juliet', 988535196, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (1, 'The Golden Compass', 451664226, 1, 1); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (1, 'The Subtle Knife', 160419390, 1, 1); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (1, 'The Amber Spyglass', 94387895, 1, 1); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (3, 'The Alchemist', 464069772, 1, 2); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (4, 'And Then There Were None', 335973357, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (5, 'The Joy Luck Club', 990050329, 1, 10); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (5, 'The Moon Lady', 91720786, 1, 24); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Sense and Sensibility', 156879860, 1, 2); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Northanger Abbey', 951273178, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Pride and Prejudice', 415886839, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Mansfield Park', 188534067, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Emma', 994896202, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Persuasion', 28150097, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (6, 'Lady Susan', 230962926, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (7, 'Wuthering Heights', 280569946, 1, 3); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (8, 'The Handmaids Tale', 639239663, 1, 5); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (8, 'The Testaments', 826875490, 1, 5); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (9, 'The Parable of the Sower', 283359358, 1, 5); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (10, 'Little Women', 495409887, 1, 23); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'Still Life', 455128657, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'A Fatal Grace', 832517012, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'The Cruelest Month', 419285319, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'The Murder Stone', 656621400, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'The Brutal Telling', 144255852, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'Bury Your Dead', 208180961, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (11, 'A Trick of the Light', 93451531, 1, 6); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (12, 'Midnights Children', 881082293, 1, 10); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (13, 'Dont Let the Pigeon Drive the Bus!', 18409532, 1, 24); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (14, 'Beezus and Ramona', 744412630, 1, 24); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (15, 'Organic Chemistry', 604328803, 1, 25); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (16, 'I Know Why the Caged Bird Sings', 909947112, 1, 12); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (17, 'Beloved', 46736233, 1, 10); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.book(author_id, title, isbn, available, genre_id) +VALUES (18, 'Brassbones and Rainbows', 330608463, 1, 26); + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.book + + + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.author ( + author_id INT IDENTITY(1,1) PRIMARY KEY, + first_name VARCHAR(255), + last_name VARCHAR(255), + birth_year INT, + death_year INT +); + +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.author + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Phillip', 'Pullman', 1946, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('William', 'Shakespeare', 1564, 1616); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Paulo', 'Coelho', 1947, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Agatha', 'Christie', 1890-09-15, 1976-01-12); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Amy', 'Tan', 1952-02-19, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Jane', 'Austin', 1775-12-16, 1817-07-18); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Emily', 'Bronte', 1818-07-30, 1848-12-19); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Margaret', 'Atwood', 1939-11-18, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Octavia', 'Butler', 1947-06-22, 2006-02-24); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Louisa May', 'Alcott', 1832-11-29, 1888-03-06); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Louise', 'Penny', 1958-07-01, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Salman', 'Rushdie', 1947-08-19, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Mo', 'Willems', 1968-02-11, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Beverly', 'Cleary', 1916-04-12, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Peter', 'Vollhardt', 1946-03-07, null); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Maya', 'Angelou', 1928-04-04, 2014-05-28); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Toni', 'Morrison', 1931-02-18, 2019-08-05); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.author(first_name, last_name, birth_year, death_year) +VALUES ('Shirley', 'LeFlore', 1940-03-06, 2019-05-12); + + +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.author + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.patron ( + patron_id INT IDENTITY (1,1) PRIMARY KEY, + first_name VARCHAR(255), + last_name VARCHAR(255), + loan_id INT +); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Jennifer', 'Slayny', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Susan', 'Traviss', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Vincent', 'Ritelli', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Tasia', 'Laybourne', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Wren', 'Gergler', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Tory', 'Lees', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Estelle', 'Di Lorio', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Dorian', 'Betje', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Frank', 'Jelk', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Chris', 'Endon', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Gillie', 'Fritz', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Leisha', 'Defty', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Erika', 'Bompass', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Gabe', 'Moxstead', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Blake', 'Teresse', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Joshua', 'Timmouth', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Tasha', 'Timmouth', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Neil', 'Davie', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Emmeline', 'Pitherick', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Josiah', 'Staner', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('James', 'Greetham', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Isaac', 'Barstowk', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Dean', 'Nelane', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Carolina', 'Cranmere', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Champ', 'Lardiner', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Abbie', 'Quaif', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Camile', 'Milbourne', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Quentin', 'Crose', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Silvano', 'Horlick', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Phyllis', 'Cicchillo', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Jerrie', 'Brownhall', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Ludovika', 'Leist', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Tara', 'Knatt', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Kelsie', 'Parkson', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Jodi', 'Leopard', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Rosanna', 'Cultcheth', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Remy', 'Fairpool', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Megan', 'Blyth', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Rikki', 'McLernon', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Clare', 'Haacker', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Vincent', 'Chettle', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Sybil', 'Costanza', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Jonas', 'Sinclare', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Claire', 'Bendel', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Kathleen', 'Welband', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Kylie', 'Crannage', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Evelyn', 'Tarajo', NULL); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.patron(first_name, last_name, loan_id) +VALUES ('Oliver', 'Caulson', NULL); + +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.patron + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.genre ( + genre_id INT PRIMARY KEY, + genres VARCHAR(100) +); + +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.genre + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (1, 'Fantasy'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (2, 'Adventure'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (3, 'Romance'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (4, 'Contemporary'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (5, 'Dystopian'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (6, 'Mystery'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (7, 'Horror'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (8, 'Thriller'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (9, 'Paranormal'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (10, 'Historical Fiction'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (11, 'Science Fiction'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (12, 'Memoir'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (13, 'Cooking'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (14, 'Art'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (15, 'Self-Help'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (16, 'Development'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (17, 'Motivational'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (18, 'Health'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (19, 'History'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (20, 'Travel'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (21, 'Guide'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (22, 'Families and Relationships'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (23, 'Humor'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (24, 'Childrens'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (25, 'Reference'); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.genre(genre_id, genres) +VALUES (26, 'Poetry'); + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.loan ( + loan_id INT IDENTITY(1,1) PRIMARY KEY, + patron_id INT, + date_out DATE, + date_in DATE, + book_id INT + CONSTRAINT book_id FOREIGN KEY (book_id) REFERENCES Sep2025JunkDB.madhuri_chaudhari.book (book_id) + ON UPDATE SET NULL + ON DELETE SET NULL +); + +--Part B + +--1. Return the mystery book titles and their ISBNs. + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.book + +SELECT + b.Title, + b.ISBN, + g.genres +FROM Sep2025JunkDB.madhuri_chaudhari.book AS b +INNER JOIN Sep2025JunkDB.madhuri_chaudhari.genre g + ON b.genre_id = g.genre_id +WHERE g.genres = 'Mystery'; + + +--Answer- 8 rows + + +--2. Return all of the titles and the author's first +--and last names for books written by authors who are currently living. + + +SELECT + b.Title, + a.first_name, + a.last_name +FROM Sep2025JunkDB.madhuri_chaudhari.book AS b +INNER JOIN Sep2025JunkDB.madhuri_chaudhari.author AS a + ON b.author_id= a.author_id -- FK (book) matches PK (author) +WHERE a.death_year IS NULL; + +--Answer- 19 rows + +--Part C- + +--1. Change **available** to **0** (false) for the appropriate book. +SELECT * from Sep2025JunkDB.madhuri_chaudhari.book + +UPDATE Sep2025JunkDB.madhuri_chaudhari.book +SET available = 0 +WHERE book_id = 1; + + +--2. Add a new row to the **loan** table with today's date as the `date_out` and the +--ids in the row matching the appropriate `patron_id` and `book_id`. +--Add a new loan record with today's date + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.book + + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.loan (book_id, patron_id, date_out) +VALUES (1, 1, CONVERT(date, GETDATE())); +--Answer- 1 row affected + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.loan + +3. Update the appropriate **patron** with the `loan_id` for the new row created in the **loan** table. + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.patron + +UPDATE Sep2025JunkDB.madhuri_chaudhari.patron +SET loan_id = ( + SELECT TOP 1 loan_id + FROM Sep2025JunkDB.madhuri_chaudhari.loan + WHERE patron_id = 1 AND book_id = 1 + ORDER BY date_out DESC +) +WHERE patron_id = 1; + +--Answer- 1 row affected + +SELECT * from Sep2025JunkDB.madhuri_chaudhari.patron +--answer- 48 row affected ,loan id added + + +## **Part D: Check a Book Back In** + +Work with the same patron and book as you create your query to check a book back into the library. + +The check a book back in, your query need to do the following: + +1. Change **available** to **1** (true) for the appropriate book. +SELECT * FROM Sep2025JunkDB.madhuri_chaudhari.book + +UPDATE Sep2025JunkDB.madhuri_chaudhari.book +SET available = 1 +WHERE book_id = 1; + +--2. Update the appropriate row in the **loan** table with today's date as the `date_in`. +SELECT * from Sep2025JunkDB.madhuri_chaudhari.loan + +UPDATE Sep2025JunkDB.madhuri_chaudhari.loan +SET date_in = CONVERT(date, GETDATE()) +WHERE book_id = 1 + AND patron_id = 1 + AND date_in IS NULL; + + --ANSWER- date_in is added -1 row affected + + + +3. Update the appropriate **patron** changing `loan_id` back to `NULL`. + +SELECT *FROM Sep2025JunkDB.madhuri_chaudhari.patron +UPDATE Sep2025JunkDB.madhuri_chaudhari.patron +SET loan_id= NULL +WHERE patron_id = 1; + +--Answer- 1 row affected / Loan_id back to NULL + +## **Part E: Create a temp table** + +Write a query that returns a temporary table for a patron that shows them all of their loans. + +_Question to think about:_ Why might a temp table be a good option for this type of query? + +SELECT + l.loan_id, + l.book_id, + b.title AS book_title, + l.date_out, + l.date_in +INTO #PatronLoans +FROM Sep2025JunkDB.madhuri_chaudhari.loan AS l +JOIN Sep2025JunkDB.madhuri_chaudhari.book AS b + ON l.book_id = b.book_id +WHERE l.patron_id = 1; + +--Answe- 1 row affected + +SELECT * FROM #PatronLoans; + +**Part F: Wrap-up Query** + +Create a query that returns the names of the patrons with the genre of every book they currently + have checked out. + +SELECT + p.patron_id, + p.first_name, + p.last_name, + b.title AS book_title, + g.genres AS genre +FROM + Sep2025JunkDB.madhuri_chaudhari.patron AS p +JOIN + Sep2025JunkDB.madhuri_chaudhari.loan AS l + ON p.patron_id = l.patron_id +JOIN + Sep2025JunkDB.madhuri_chaudhari.book AS b + ON l.book_id = b.book_id +JOIN + Sep2025JunkDB.madhuri_chaudhari.genre AS g + ON b.genre_id = g.genre_id +WHERE + l.date_in IS NULL; + +--Answer- 0 rows affected + +## **Bonus Challenge:** + +CREATE TABLE Sep2025JunkDB.madhuri_chaudhari.reference_books ( + reference_id INT IDENTITY(1,1) PRIMARY KEY, + edition INT, + book_id INT NULL, + CONSTRAINT FK_reference_books_book FOREIGN KEY (book_id) REFERENCES Sep2025JunkDB.madhuri_chaudhari.book(book_id) + ON UPDATE SET NULL + ON DELETE SET NULL +); + +INSERT INTO Sep2025JunkDB.madhuri_chaudhari.reference_books (edition, book_id) +VALUES (5, 32); + +Select * from Sep2025JunkDB.madhuri_chaudhari.reference_books + +--answer- 1 row affected \ No newline at end of file