Basics of Sets and Relations #1 Easy Problem Solving (Basic) Max Score: 5 Success Rate: 87.58%
Basics of sets and relations #2 easy problem solving (basic) max score: 5 success rate: 96.80%, basics of sets and relations #3 easy problem solving (basic) max score: 5 success rate: 97.04%, basics of sets and relations #4 easy problem solving (basic) max score: 5 success rate: 96.49%, basics of sets and relations #5 easy problem solving (basic) max score: 5 success rate: 97.48%, basics of sets and relations #6 easy problem solving (basic) max score: 5 success rate: 97.26%, basics of sets and relations #7 easy problem solving (basic) max score: 5 success rate: 98.24%, relational algebra - 3 multiple choice question max score: 2 success rate: 67.94%, relational algebra - 4 multiple choice question max score: 2 success rate: 64.77%, database query languages multiple choice question max score: 2 success rate: 83.86%, cookie support is required to access hackerrank.
Seems like cookies are disabled on this browser, please enable them to open this website
- SQL Cheat Sheet
- SQL Interview Questions
- MySQL Interview Questions
- PL/SQL Interview Questions
- Learn SQL and Database
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL ( Structured Query Language ) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks.
So, in this free SQL exercises page, we'll cover a series of SQL practice exercises covering a wide range of topics suitable for beginners , intermediate , and advanced SQL learners. These exercises are designed to provide hands-on experience with common SQL tasks, from basic retrieval and filtering to more advanced concepts like joins window functions , and stored procedures.
Table of Content
SQL Exercises for Practice
Sql practice exercises for beginners, sql practice exercises for intermediate, sql practice exercises for advanced, more questions for practice.
Practice SQL questions to enhance our skills in database querying and manipulation. Each question covers a different aspect of SQL , providing a comprehensive learning experience.
We have covered a wide range of topics in the sections beginner , intermediate and advanced .
- Basic Retrieval
- Arithmetic Operations and Comparisons:
- Aggregation Functions
- Group By and Having
- Window Functions
- Conditional Statements
- DateTime Operations
- Creating and Aliasing
- Constraints
- Stored Procedures:
- Transactions
let's create the table schemas and insert some sample data into them.
Create Sales table
Create products table.
This hands-on approach provides a practical environment for beginners to experiment with various SQL commands, gaining confidence through real-world scenarios. By working through these exercises, newcomers can solidify their understanding of fundamental concepts like data retrieval, filtering, and manipulation, laying a strong foundation for their SQL journey.
1. Retrieve all columns from the Sales table.
Explanation:
This SQL query selects all columns from the Sales table, denoted by the asterisk (*) wildcard. It retrieves every row and all associated columns from the Sales table.
2. Retrieve the product_name and unit_price from the Products table.
This SQL query selects the product_name and unit_price columns from the Products table. It retrieves every row but only the specified columns, which are product_name and unit_price.
3. Retrieve the sale_id and sale_date from the Sales table.
This SQL query selects the sale_id and sale_date columns from the Sales table. It retrieves every row but only the specified columns, which are sale_id and sale_date.
4. Filter the Sales table to show only sales with a total_price greater than $100.
This SQL query selects all columns from the Sales table but only returns rows where the total_price column is greater than 100. It filters out sales with a total_price less than or equal to $100.
5. Filter the Products table to show only products in the 'Electronics' category.
This SQL query selects all columns from the Products table but only returns rows where the category column equals 'Electronics'. It filters out products that do not belong to the 'Electronics' category.
6. Retrieve the sale_id and total_price from the Sales table for sales made on January 3, 2024.
This SQL query selects the sale_id and total_price columns from the Sales table but only returns rows where the sale_date is equal to '2024-01-03'. It filters out sales made on any other date.
7. Retrieve the product_id and product_name from the Products table for products with a unit_price greater than $100.
This SQL query selects the product_id and product_name columns from the Products table but only returns rows where the unit_price is greater than $100. It filters out products with a unit_price less than or equal to $100.
8. Calculate the total revenue generated from all sales in the Sales table.
This SQL query calculates the total revenue generated from all sales by summing up the total_price column in the Sales table using the SUM() function.
9. Calculate the average unit_price of products in the Products table.
This SQL query calculates the average unit_price of products by averaging the values in the unit_price column in the Products table using the AVG() function.
10. Calculate the total quantity_sold from the Sales table.
This SQL query calculates the total quantity_sold by summing up the quantity_sold column in the Sales table using the SUM() function.
11. Retrieve the sale_id, product_id, and total_price from the Sales table for sales with a quantity_sold greater than 4.
This SQL query selects the sale_id, product_id, and total_price columns from the Sales table but only returns rows where the quantity_sold is greater than 4.
12. Retrieve the product_name and unit_price from the Products table, ordering the results by unit_price in descending order.
This SQL query selects the product_name and unit_price columns from the Products table and orders the results by unit_price in descending order using the ORDER BY clause with the DESC keyword.
13. Retrieve the total_price of all sales, rounding the values to two decimal places.
This SQL query calculates the total sales revenu by summing up the total_price column in the Sales table and rounds the result to two decimal places using the ROUND() function.
14. Calculate the average total_price of sales in the Sales table.
This SQL query calculates the average total_price of sales by averaging the values in the total_price column in the Sales table using the AVG() function.
15. Retrieve the sale_id and sale_date from the Sales table, formatting the sale_date as 'YYYY-MM-DD'.
This SQL query selects the sale_id and sale_date columns from the Sales table and formats the sale_date using the DATE_FORMAT() function to display it in 'YYYY-MM-DD' format.
16. Calculate the total revenue generated from sales of products in the 'Electronics' category.
This SQL query calculates the total revenue generated from sales of products in the 'Electronics' category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the 'Electronics' category.
17. Retrieve the product_name and unit_price from the Products table, filtering the unit_price to show only values between $20 and $600.
This SQL query selects the product_name and unit_price columns from the Products table but only returns rows where the unit_price falls within the range of $20 and $600 using the BETWEEN operator.
18. Retrieve the product_name and category from the Products table, ordering the results by category in ascending order.
This SQL query selects the product_name and category columns from the Products table and orders the results by category in ascending order using the ORDER BY clause with the ASC keyword.
19. Calculate the total quantity_sold of products in the 'Electronics' category.
This SQL query calculates the total quantity_sold of products in the 'Electronics' category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the 'Electronics' category.
20. Retrieve the product_name and total_price from the Sales table, calculating the total_price as quantity_sold multiplied by unit_price.
This SQL query retrieves the product_name from the Sales table and calculates the total_price by multiplying quantity_sold by unit_price, joining the Sales table with the Products table on the product_id column.
These exercises are designed to challenge you beyond basic queries, delving into more complex data manipulation and analysis. By tackling these problems, you'll solidify your understanding of advanced SQL concepts like joins, subqueries, functions, and window functions, ultimately boosting your ability to work with real-world data scenarios effectively.
1. Calculate the total revenue generated from sales for each product category.
This query joins the Sales and Products tables on the product_id column, groups the results by product category, and calculates the total revenue for each category by summing up the total_price.
2. Find the product category with the highest average unit price.
This query groups products by category, calculates the average unit price for each category, orders the results by the average unit price in descending order, and selects the top category with the highest average unit price using the LIMIT clause.
3. Identify products with total sales exceeding 30.
This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and selects products with total sales exceeding 30 using the HAVING clause.
4. Count the number of sales made in each month.
This query formats the sale_date column to extract the month and year, groups the results by month, and counts the number of sales made in each month.
5. Determine the average quantity sold for products with a unit price greater than $100.
This query joins the Sales and Products tables on the product_id column, filters products with a unit price greater than $100, and calculates the average quantity sold for those products.
6. Retrieve the product name and total sales revenue for each product.
This query joins the Sales and Products tables on the product_id column, groups the results by product name, and calculates the total sales revenue for each product.
7. List all sales along with the corresponding product names.
This query joins the Sales and Products tables on the product_id column and retrieves the sale_id and product_name for each sale.
8. Retrieve the product name and total sales revenue for each product.
This query will give you the top three product categories contributing to the highest percentage of total revenue generated from sales. However, if you only have one category (Electronics) as in the provided sample data, it will be the only result.
9. Rank products based on total sales revenue.
This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and ranks products based on total sales revenue using the RANK () window function.
10. Calculate the running total revenue for each product category.
This query joins the Sales and Products tables on the product_id column, partitions the results by product category, orders the results by sale date, and calculates the running total revenue for each product category using the SUM() window function.
11. Categorize sales as "High", "Medium", or "Low" based on total price (e.g., > $200 is High, $100-$200 is Medium, < $100 is Low).
This query categorizes sales based on total price using a CASE statement. Sales with a total price greater than $200 are categorized as "High", sales with a total price between $100 and $200 are categorized as "Medium", and sales with a total price less than $100 are categorized as "Low".
12. Identify sales where the quantity sold is greater than the average quantity sold.
This query selects all sales where the quantity sold is greater than the average quantity sold across all sales in the Sales table.
13. Extract the month and year from the sale date and count the number of sales for each month.
This query extracts the year and month from the sale_date and counts the number of sales for each month. CONCAT(YEAR(sale_date), '-', LPAD(MONTH(sale_date), 2, '0')): Formats the year and month as YYYY-MM. COUNT(*): Counts the total sales for each month. GROUP BY YEAR(sale_date), MONTH(sale_date): Groups the sales by year and month. This results in the sales count for each month in the format YYYY-MM.
14. Calculate the number of days between the current date and the sale date for each sale.
This query calculates the number of days between the current date and the sale date for each sale using the DATEDIFF function.
15. Identify sales made during weekdays versus weekends.
This query categorizes sales based on the day of the week using the DAYOFWEEK function. Sales made on Sunday (1) or Saturday (7) are categorized as "Weekend", while sales made on other days are categorized as "Weekday".
This section likely dives deeper into complex queries, delving into advanced features like window functions, self-joins, and intricate data manipulation techniques. By tackling these challenging exercises, users can refine their SQL skills and tackle real-world data analysis scenarios with greater confidence and efficiency.
1. Write a query to create a view named Total_Sales that displays the total sales amount for each product along with their names and categories.
This query creates a view named Total_Sales that displays the total sales amount for each product along with their names and categories.
2. Retrieve the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.
This query retrieves the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.
3. Explain the significance of indexing in SQL databases and provide an example scenario where indexing could significantly improve query performance in the given schema.
With an index on the sale_date column, the database can quickly locate the rows that match the specified date without scanning the entire table. The index allows for efficient lookup of rows based on the sale_date value, resulting in improved query performance.
4. Add a foreign key constraint to the Sales table that references the product_id column in the Products table.
This query adds a foreign key constraint to the Sales table that references the product_id column in the Products table, ensuring referential integrity between the two tables.
5. Create a view named Top_Products that lists the top 3 products based on the total quantity sold.
This query creates a view named Top_Products that lists the top 3 products based on the total quantity sold.
6. Implement a transaction that deducts the quantity sold from the Products table when a sale is made in the Sales table, ensuring that both operations are either committed or rolled back together.
The quantity in stock for product with product_id 101 should be updated to 5.The transaction should be committed successfully.
7. Create a query that lists the product names along with their corresponding sales count.
This query selects the product names from the Products table and counts the number of sales (using the COUNT() function) for each product by joining the Sales table on the product_id. The results are grouped by product name using the GROUP BY clause.
8. Write a query to find all sales where the total price is greater than the average total price of all sales.
The subquery (SELECT AVG(total_price) FROM Sales) calculates the average total price of all sales. The main query selects all columns from the Sales table where the total price is greater than the average total price obtained from the subquery.
9. Analyze the performance implications of indexing the sale_date column in the Sales table, considering the types of queries commonly executed against this column.
Query without indexing:, query with indexing:.
This format clearly displays the operations and details of the query execution plan before and after indexing.
Without indexing, the query performs a full table scan, filtering rows based on the sale date, which is less efficient. With indexing, the query uses the index to quickly locate the relevant rows, significantly improving query performance.
10. Add a check constraint to the quantity_sold column in the Sales table to ensure that the quantity sold is always greater than zero.
All rows in the Sales table meet the condition of the check constraint, as each quantity_sold value is greater than zero.
11. Create a view named Product_Sales_Info that displays product details along with the total number of sales made for each product.
This view provides a concise and organized way to view product details alongside their respective sales information, facilitating analysis and reporting tasks.
12. Develop a stored procedure named Update_Unit_Price that updates the unit price of a product in the Products table based on the provided product_id.
The above SQL code creates a stored procedure named Update_Unit_Price. This stored procedure takes two parameters: p_product_id (the product ID for which the unit price needs to be updated) and p_new_price (the new unit price to set).
13. Implement a transaction that inserts a new product into the Products table and then adds a corresponding sale record into the Sales table, ensuring that both operations are either fully completed or fully rolled back.
This will update the unit price of the product with product_id 101 to 550.00 in the Products table.
14. Write a query that calculates the total revenue generated from each category of products for the year 2024.
When you execute this query, you will get the total revenue generated from each category of products for the year 2024.
If you're looking to sharpen your SQL skills and gain more confidence in querying database s, consider delving into these articles. They're packed with query-based SQL questions designed to enhance your understanding and proficiency in SQL .
By practicing with these exercises, you'll not only improve your SQL abilities but also boost your confidence in tackling various database-related tasks. The Questions are as follows:
- How to Insert a Value that Contains an Apostrophe in SQL?
- How to Select Row With Max Value in SQL?
- How to Efficiently Convert Rows to Columns in SQL?
- How To Use Nested Select Queries in SQL
- How to Select Row With Max Value on a Column in SQL?
- How to Specify Condition in Count() in SQL?
- How to Find the Maximum of Multiple Columns in SQL?
- How to Update Top 100 Records in SQL?
- How to Select the Last Records in a One-To-Many Relationship Using SQL Join
- How to Join First Row in SQL?
- How to Insert Row If Not Exists in SQL?
- How to Use GROUP BY to Concatenate Strings in SQL?
- How Inner Join works in LINQ to SQL
- How to Get the Identity of an Inserted Row in SQL
- How to Declare a Variable in SQL?
Mastering SQL requires consistent practice and hands-on experience. By working through these SQL practice exercises , you'll strengthen your skills and gain confidence in querying relational databases.
Whether you're just starting or looking to refine your expertise, these exercises provide valuable opportunities to hone your SQL abilities. Keep practicing , and you'll be well-equipped to tackle real-world data challenges with SQL.
Similar Reads
- SQL Exercises : SQL Practice with Solution for Beginners and Experienced SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confi 15+ min read
- Top 15 Uber SQL Interview Questions with Answers and Explanations Preparing for a SQL interview at Uber involves not only understanding SQL concepts but also being able to work with practical examples. Here, we'll provide 15 unique SQL questions you might encounter during an interview at Uber, along with detailed database setups and explanations. Each question wil 12 min read
- PL/SQL Interview Questions and Answers PL/SQL (Procedural Language for SQL) is one of the most widely used database programming languages in the world, known for its robust performance, flexibility, and tight integration with Oracle databases. It is a preferred choice for many top companies such as Oracle, IBM, Accenture, Infosys, TCS, C 15 min read
- Getting started with Databases : Essential Guide for Beginners Databases and data are the fundamental building blocks of new technology. Data is the building blocks of information, like numbers, words, pictures, and more, that computers use and process. Databases, on the other hand, are like organized libraries, making sure this data is stored, retrieved, and m 12 min read
- 5 Best Practices For Writing SQL JOIN Query The SQL JOIN clause allows users to take records from two or more tables at once and retrieve data based on a common field. It also helps to keep our database normalized. However, poorly written joins can lead to inefficient queries, slow performance, and even incorrect results. Here, we will explor 5 min read
- SQL Quiz : Practice SQL Questions Online This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things intere 3 min read
- Difference between SQL and T-SQL SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifical 4 min read
- Difference Between Nested Subquery, Correlated Subquery and Join Operation Nested subqueries, correlated subqueries, and join operations are common methods for querying data, but they all have different behaviors and serve various purposes. Joins are used to combine two or more different tables based on a common field between them. We can easily retrieve data from multiple 8 min read
- Difference Between JOIN, IN and EXISTS Clause in SQL SEQUEL widely known as SQL, Structured Query Language is the most popular standard language to work on databases. We can perform tons of operations using SQL which includes creating a database, storing data in the form of tables, modify, extract and lot more. There are different versions of SQL like 4 min read
- SQL VS ADO.NET With Stored Procedures Stored Procedures have been used as a solution for so many problems, performance issues and not being able to separate the business Logic and transaction management. Stored Procedure tries to solve this major problem while developing a website. In .NET when we want to create a website or desktop app 6 min read
- Compute a Difference(Delta) Between Two Columns on Different Rows in PL/SQL Calculating the difference between two columns is useful in data analysis. It can help identify trends in various sectors such as finance, healthcare, and inventory management. It can also be used to analyze day-to-day changes in stock prices, and medical diagnoses, and identify bottleneck products. 5 min read
- Pass DataTable to Stored Procedure as Parameter in SQL Server In SQL Server, when we have to pass multiple rows of data to be added or updated in a table the simplest way to send data from the front-end application to the database is by using DataTable as a parameter sent to a stored procedure. Any number of data records can be sent to the database table by th 6 min read
- PL/SQL Query to List the Last 25% Rows in a Result Set We sometimes need to fetch some specific rows from our result set. There are many reasons to do so. When we are working on real-time analytics, focusing on recent data is then our need. This helps us in quicker decision-making as it provides us the quicker insight into the latest data. PL/SQL is a p 5 min read
- Best Practices For SQL Query Optimizations SQL stands for Structured Query Language which is used to interact with a relational database. It is a tool for managing, organizing, manipulating, and retrieving data from databases. SQL offers amazing advantages like faster query processing, highly portable, interactive language, cost-efficient, a 8 min read
- Advanced SQL Interview Questions Mastering advanced SQL is always important if you are preparing for data-centric job roles. SQL (Structured Query Language) is the backbone of database management, and employers look for candidates who can show they understand advanced SQL concepts. This interview preparation guide covers frequently 4 min read
- How to Write a Simple SELECT Stored Procedure in PL/SQL? In PL/SQL, stored procedures are powerful tools for encapsulating logic and executing complex queries. This article will guide you through the process of creating a simple SELECT stored procedure in PL/SQL. In this article, we will learn how to store procedures with the help of various methods and e 6 min read
- How to Implement Relationships While Designing Tables in SQL? In database design, understanding and implementing relationships between entities is crucial. These relationships, such as one-to-one, one-to-many, and many-to-many, establish connections between tables using key constraints. Let's explore each type of relationship with examples and SQL implementati 7 min read
- How to Find Records From One Table Which Don't Exist in Another MySQL MySQL is a free and open-source relational database management system written in C and C++ that is extremely popular among developers. Like other relational database management systems, MySQL provides a variety of rich features to create databases and tables, insert data in them, and further manipul 5 min read
- Top 50 Database Interview Questions and Answers for 2024 Getting ready for a database interview can be challenging, but knowing the types of questions that you can encounter in the interview can help you feel more prepared. In this interview preparation post, we'll go over key database interview questions that cover a wide range of topics, from basic idea 15+ min read
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
SQL for Data Analysis: 15 Practical Exercises with Solutions
- sql practice
- data analysis
Table of Contents
Store Database Overview
Exercise 1: all products, exercise 2: products with the unit price greater than 3.5, exercise 3: products with specific conditions for category and price, exercise 4: products and categories, exercise 5: purchases and products, exercise 6: purchases and categories, exercise 7: sorted categories, exercise 8: employees sorted by birth date, exercise 9: products sorted by the number of units, exercise 10: the average unit price for each category, exercise 11: the number of customers in cities, exercise 12: the number of discontinued products, exercise 13: employees with an unknown hire date, exercise 14: number of employees with unknown birth and hire dates, exercise 15: percentage of money spent by the customer on purchase, ready for more sql exercises.
Are you new to the world of SQL and eager to unlock the power of data analysis?. In this article, we'll improve our SQL skills through 15 practical, hands-on exercises designed specifically for beginners. Because when it comes to SQL, practice truly makes perfect!
We’re going to shine a spotlight on the critical domain of data analysis, where SQL takes center stage. SQL, or Structured Query Language, plays a pivotal role in data analysis. It provides a robust framework for querying, transforming, and extracting invaluable insights from databases. If you're eager to delve deeper into the world of SQL and become a master of data analysis, you can explore additional information and resources in our article Learn SQL for Data Analysis .
What we aren’t going to do is bore you with theory. Instead, we firmly believe in the power of learning through hands-on experience. That's why we've curated a collection of 15 beginner-friendly SQL exercises that immerse you in the art of data analysis – all while utilizing a real-world dataset from a store.
These exercises are drawn from our comprehensive course, Basic SQL Practice: A Store , which offers a total of 169 interactive online exercises. The exercises in the article are grouped into different topics: single table queries, JOIN queries, ORDER BY queries, GROUP BY exercises, and other features. If you enjoy these exercises, you'll undoubtedly want to explore the course for a more extensive learning experience.
Now, get ready to roll up your sleeves and fully immerse yourself in the realm of SQL-powered data analysis!
The store database consists of six tables, each serving a unique purpose and structured for specific functions. These tables are pivotal to the SQL exercises at hand, and gaining a comprehensive understanding of their components is important. Below, we will look at a brief description of each table.
- employee : Contains employee details like ID, name, birth date, address, city, country, and immediate supervisor.
- customer : Stores customer information, including customer ID, name, company, email, address, city, and country.
- purchase : Records order details, including order ID, customer ID (who placed the order), employee (who serviced the order), total price, and purchase and shipment details.
- purchase_item : Connects purchases with products via ID, product, unit price, and quantity.
- category : Provides insights into product categories using category ID, name, description, and parent category ID.
- product : Lists store products and includes product ID, product name, category ID, quantity per unit, unit price, units in stock, and product status.
Now that we have a better understanding of the tables in the store database, let's dive into some SQL exercises to help sharpen your data analysis skills.
Data Analysis SQL Exercises
Since practice is essential for developing and refining your SQL skills, these exercises will serve as valuable tools. We've even created a SQL for Data Analysis Cheat Sheet to make things easier for you! You might want to keep it handy on your journey through the following 15 SQL exercises.
Single Table Queries
In this section, we are going to focus on SQL queries involving a single table. These exercises will help you master the foundational art of retrieving, filtering, and working with data within a single dataset.
Exercise : Display all data present in the product table.
Solution explanation: This simple query retrieves all the data from the product table. The asterisk ( * ) is used to indicate that we want to select all available columns in the table, essentially fetching all the data. After the FROM keyword, we give the name of the table we’re selecting from (here, the table product ).
Exercise: Display product names for products with a unit price greater than or equal to 3.5.
Solution explanation: Using the WHERE clause, we filter for product_names with a unit price greater than or equal to 3.5. The WHERE clause restricts the rows returned by the query to only those meeting the specified criteria.
Exercise: Display data for all products in categories with an ID of 1 (Food) or 5 (Fruits and Vegetables) and with a unit price above 3.5.
Solution explanation: This query uses both the AND and OR operators to create complex conditions that filter products based on category and unit_price .
The OR operator allows products from either category 1 (Food) or category 5 (Fruits and Vegetables), while the AND operator ensures that selected products must have a unit price greater than 3.5. The use of brackets enhances query readability.
JOIN Queries
Joins are a fundamental concept in SQL. They are crucial for data analysis because they allow you to combine and analyze data from different sources, enabling comprehensive insights into your datasets. For more practice exercises involving joins, refer to our article SQL Joins: 12 Practice Questions with Detailed Answers .
Exercise: Select product names along with their categories. Display two columns: product_name and category_name .
Solution explanation: In this exercise, an INNER JOIN combines data from the product and category tables. An INNER JOIN selects only the rows that have matching values in both tables. This ensures that only products with corresponding categories are retrieved, creating a meaningful and accurate result.
The ON part of the query defines the relationship between the two tables. Additionally, the use of aliases ( AS category_name ) allows us to rename the columns as required by the question.
Exercise: For each purchase, display the purchase ID, product name, unit price at the time of purchase, and quantity of each product's items.
Solution explanation: This query combines data from the purchase_item and product tables, allowing us to display relevant purchase information. In SQL, INNER JOIN and JOIN are often used interchangeably, but they serve the same purpose: retrieving matching rows from both tables.
Exercise: For each purchase, display all product categories bought in this purchase. Show each category only once for each purchase.
Solution explanation: In this exercise, we're joining three tables: purchase_item , product , and category . Joining more than two tables is achieved by sequentially connecting each table through their related columns. If you want to learn more about joining multiple tables, read How to Join 3 Tables (or More) in SQL .
The use of the DISTINCT keyword here ensures that each product category appears only once for each purchase, providing a clear and concise list of categories associated with every purchase. This can be especially useful when you want to avoid redundant information in your result set.
ORDER BY Queries
Sorting data is a crucial step in data analysis because it allows you to organize information in a structured and meaningful way. The following exercises will teach you how to arrange data meaningfully for reporting and analysis purposes.
Exercise: Display all categories' data. Sort the categories by name in ascending (A to Z) order.
Solution explanation: In this exercise, we use the ORDER BY clause to sort the results from the category table in ascending order based on the name column. This arrangement allows you to view the categories in alphabetical order. The ASC keyword is optional here; it represents the default sorting order, which is ascending.
Exercise: Show employees’ last names, first names, and birthdates. Sort results by employee age in ascending order ( Hint: Use the birth_date column ).
Solution explanation: Since there is no age column in our table, we sort employees by birth_date in descending order using the DESC keyword. Sorting by birth_date in descending order allows you to view employees from the youngest to the oldest.
The use of DESC is crucial here, it reverses the default ascending sorting order and achieves the desired outcome.
Exercise: Display data for all products, sorting the results by the number of units in descending order and product name in ascending order.
Solution explanation: This query orders products first by units_in_stock in descending order, and then by product_name in ascending order. The first sorting condition ensures that products with the most units in stock appear at the top; products with the same number of units are further sorted alphabetically by name.
GROUP BY Queries
In this section, we explore SQL queries that involve grouping data for analysis. GROUP BY is essential for aggregating and summarizing information based on specific criteria. Check out GROUP BY in SQL Explained for more information.
Exercise: For each product category, show its name and find the average unit price. Display two columns: name and average_unit_price .
Solution explanation: In this exercise, we're calculating the average unit price for each product category. The query joins the product and category tables to associate products with their respective categories. The GROUP BY clause is then used to group the data by category_name . Using AVG() , we can calculate the average unit price within each category – giving us insights into the price distribution across different product categories.
Exercise: Count how many customers live in each city except for Knoxville and Stockton. Sort the results by the city name in ascending order. Display two columns: city and customers_quantity .
Solution explanation: In this query, we use the WHERE clause with the <> operator (which means not equal to ) to filter out records with the city name of Knoxville or Stockton . This filtering ensures that the analysis covers all cities except for the specified ones.
The COUNT() function then calculates the customer count for each of the remaining cities. The GROUP BY clause groups the data by city name, enabling us to count customers for each city.
Finally, the results are ordered in ascending order by city, providing a clear and organized view of customer distribution across various cities.
Exercise: For each category, find the number of discontinued products. Show only the categories with at least three discontinued products. Sort the rows by the number of discontinued products in descending order. Display two columns: name (the name of the category) and discontinued_products_number .
Solution explanation: In this query, we utilize the HAVING clause to filter categories with at least three discontinued products. The HAVING clause is applied after the GROUP BY operation and allows us to filter the aggregated results based on the specific condition. For more information on using HAVING , read our articles The SQL HAVING Clause Explained and HAVING vs. WHERE in SQL: What You Should Know .
Additionally, you'll notice the use of the COUNT() function within the ORDER BY clause. This allows us to sort the rows based on the count of discontinued products in descending order.
The ORDER BY clause is flexible and can include aggregate functions , making it a powerful tool for arranging data based on aggregated values.
Other SQL Features
In this section, we delve into additional SQL features to expand your toolkit. We'll explore working with NULL values and cleaning up data using the ROUND() function . These features are crucial for handling complex data analysis scenarios.
Exercise: Display the last and first names of employees with an unknown hire date.
Solution explanation: In this query, the WHERE clause with hire_date IS NULL allows us to filter and select records where the hire date is missing. This type of query can be a crucial analysis for identifying incomplete employee records or data entry errors within the dataset.
Exercise: Count the number of employees with both unknown birth and hire dates.
Solution explanation: In this query, we again use the IS NULL condition to filter for rows where the birth_date and hire_date are both missing. This allows us to COUNT() only those employees who lack both birth and hire date information.
Exercise: For each customer who made a purchase, display the ID of each purchase made by this customer and the percentage of money spent on that purchase relative to all the money spent by that customer.
Solution explanation: In this solution, we use two queries. The main query incorporates a subquery within the SELECT statement to calculate the SUM() of total prices for purchases made by the same customer.
The percentage is then calculated using the provided formula and the ROUND() function is applied to round the result. This query is a powerful tool for gaining insights into the purchasing behavior of each customer.
Mastering SQL is an essential skill for data analysis – and the best way to learn it is by doing. In this article we went through a selection of 15 beginner-friendly SQL exercises drawn from our comprehensive course, Basic SQL Practice: A Store .
But these exercises are just the beginning. If you're eager for a more extensive learning experience, we invite you to explore our complete course that features 169 interactive exercises. For those who crave even greater challenges, this course is just one of the nine courses available on the SQL Practice learning path – each offering an engaging format.
We also have our SQL Monthly Practice track, which is regularly updated with fresh exercises to keep your skills sharp and up-to-date with the latest SQL developments.
Immerse yourself in more SQL exercises and you'll master the art of data analysis. Your journey to becoming an SQL expert begins with continuous practice. So, keep exploring and honing your skills. Success is just around the corner!
You may also like
How Do You Write a SELECT Statement in SQL?
What Is a Foreign Key in SQL?
Enumerate and Explain All the Basic Elements of an SQL Query
IMAGES
COMMENTS
Database Query Languages. Multiple Choice Question Max Score: 2 Success Rate: 83.86%. Solve Challenge. ... Easy Problem Solving (Basic) Max Score: 5 Success Rate: 97.26%.
Oct 22, 2024 · Master SQL with our essential SQL exercises designed for all skill levels. Boost your database management skills, improve your data manipulation techniques, and become proficient in SQL queries. Perfect for beginners and experienced professionals alike.
Aug 19, 2022 · MySQL is the world's most widely used open-source relational database management system (RDBMS), enabling the cost-effective delivery of reliable, high-performance and scalable Web-based and embedded database applications. It is widely-used as the database component of LAMP (Linux, Apache, MySQL, Perl/PHP/Python) web application software stack.
Oct 27, 2023 · Problem-Solving: SQL enables you to extract, transform, and manipulate data. Regular practice sharpens your problem-solving skills, making you adept at tackling real-world data challenges.
4 days ago · SQL stands for Structured Query Language and it is an ANSI standard computer language for accessing and manipulating database systems. It is used for managing data in relational database management system which stores data in the form of tables and relationship between data is also stored in the form of tables.
Nov 30, 2023 · We’re going to shine a spotlight on the critical domain of data analysis, where SQL takes center stage. SQL, or Structured Query Language, plays a pivotal role in data analysis. It provides a robust framework for querying, transforming, and extracting invaluable insights from databases.