Solution Practice Set 1
Explore practical SQL exercises that cover sorting results, self joins to compare data within the same table, and aggregation functions to count shared attributes. Learn to write queries that find top entries, identify shared last names among actors, and distinguish actors with or without movie roles. This practice set helps reinforce key relational database query skills.
We'll cover the following...
Solution Practice Set 1
The database relationship model is reprinted below for reference.
Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy and paste the command ./DataJek/Lessons/quiz.sh and wait for the MySQL prompt to start-up.
Question # 1
Write a query that prints the top three movies by box office collection?
This asks for us to print the top three movies and should hint towards sorting. The sort key should be the column CollectionInMillions. However, remember that by default, ORDER BY sorts in ascending order so we’ll need to sort in descending order. The last piece to the puzzle is to apply the LIMIT clause so that we only retrieve the top three rows.
SELECT Name
FROM Movies
ORDER BY CollectionInMillions DESC
LIMIT 3;
Question # 2
Can you write a query to determine if any two actors share the same second name?
The information we want to extract is contained within the Actors table. However, we need a way to compare the second name of the first actor with all the other actors in the table except with itself. How can you make the comparison? The answer is using a self join.
Whenever you hear yourself thinking in terms of picking up a row from a table and comparing it to another row from the same table or another table, you are looking for a join. Without further ado, we’ll perform an inner join of the ...