Assignment Operator in SQL Server
Back to: SQL Server Tutorial For Beginners and Professionals
Assignment Operator in SQL Server with Examples
In this article, I am going to discuss Assignment Operator in SQL Server with Examples. Please read our previous article, where we discussed Clauses in SQL Server . Before understanding Assignment Operator in SQL Server, let us first understand what are operators and why we need operators, and what are the different types of operators available in SQL Server.
What is an Operator in SQL Server?
A n operator is a symbol that performs some specific operation on operands or expressions. These operators are classified as follows in SQL Server.
- Assignment operator
- Arithmetic operator
- Comparison operator
- Logical operator
- Set operator
Note: In this article, I am going to discuss Assignment Operator, rest of all other operators will discuss one by one from our upcoming articles.
Understanding the Assignment Operator in SQL Server:
Let us understand how to use the Assignment Operator in SQL Server with an example. We are going to use the following Employee table to understand the Assignment Operator.
Please use the below script to create and populate the Employee table with the required data.
Assignment operator:.
The assignment operator (=) in SQL Server is used to assign the values to a variable. The equal sign (=) is the only Transact-SQL assignment operator. In the following example, we create the @MyCounter variable, and then the assignment operator sets the @MyCounter variable to a value i.e. 1 .
DECLARE @MyCounter INT; SET @MyCounter = 1;
The assignment operator can also be used to establish the relationship between a column heading and the expression that defines the values for that column. The following example displays the column headings as FirstColumn and SecondColumn. The string ‘ abcd ‘ is displayed for all the rows in the FirstColumn column heading. Then, each Employee ID from the Employee table is listed in the SecondColumn column heading.
SELECT FirstColumn = ‘abcd’, SecondColumn = ID FROM Employee;
Compound Assignment Operators in SQL Server:
SQL SERVER 2008 has introduced a new concept of Compound Assignment Operators. The Compound Assignment Operators are available in many other programming languages for quite some time. Compound Assignment Operators are operated where variables are operated upon and assigned in the same line. Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.
Example without using Compound Assignment Operators
The following example is without using Compound Assignment Operators.
Example using Compound Assignment Operators
The above example can be rewritten using Compound Assignment Operators as follows.
Following are the list of available compound operators in SQL Server
+= Adds some amount to the original value and sets the original value to the result. -= Subtracts some amount from the original value and sets the original value to the result. *= Multiplies by an amount and sets the original value to the result. /= Divides by an amount and sets the original value to the result. %= Divides by an amount and sets the original value to the modulo.
In the next article, I am going to discuss Arithmetic Operators in SQL Server. Here, in this article, I try to explain the Assignment Operator in SQL Server with Examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
Registration Open For New ASP.NET Core Online Training
Enhance Your Professional Journey with Our Upcoming Live Session starting on today, from 8.30 PM to 10 PM, IST. For complete information on Registration, Course Details, Syllabus, and Demo Session Zoom Credentials, please click on the below link.
- ASP.NET Core Online Training with Real-time Application Development
1 thought on “Assignment Operator in SQL Server”
Operators in SQL Server covers almost all the important areas of SQL. This tutorial is very good.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
- 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
Please login to comment..., improve your coding skills with practice.
What kind of Experience do you want to share?
SQL Tutorial
Sql database, sql references, sql examples, sql exercises.
You can test your SQL skills with W3Schools' Exercises.
We have gathered a variety of SQL exercises (with answers) for each SQL Chapter.
Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.
Count Your Score
You will get 1 point for each correct answer. Your score and total score will always be displayed.
Start SQL Exercises
Start SQL Exercises ❯
If you don't know SQL, we suggest that you read our SQL Tutorial from scratch.
Kickstart your career
Get certified by completing the course
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
= (Assignment Operator) (Transact-SQL)
- 11 contributors
The equal sign (=) is the only Transact-SQL assignment operator. In the following example, the @MyCounter variable is created, and then the assignment operator sets @MyCounter to a value returned by an expression.
The assignment operator can also be used to establish the relationship between a column heading and the expression that defines the values for the column. The following example displays the column headings FirstColumnHeading and SecondColumnHeading . The string xyz is displayed in the FirstColumnHeading column heading for all rows. Then, each product ID from the Product table is listed in the SecondColumnHeading column heading.
Operators (Transact-SQL) Compound Operators (Transact-SQL) Expressions (Transact-SQL)
Was this page helpful?
Additional resources
Advanced SQL Practice: 10 Exercises with Solutions
- sql practice
- Online practice
- advanced sql
Table of Contents
Practicing Your Way to SQL Proficiency
Exercise 1: list all clothing items, exercise 2: get all non-buying customers, exercise 3: select all main categories and their subcategories, exercise 4: organize runners into groups, exercise 5: how many runners participate in each event, exercise 6: group runners by main distance and age, exercise 7: list the top 3 most expensive orders, exercise 8: compute deltas between consecutive orders, exercise 9: compute the running total of purchases per customer, exercise 10: find the invitation path for each student, advancing one query at a time.
As SQL proficiency continues to be in high demand for data professionals and developers alike, the importance of hands-on practice cannot be emphasized enough. Read on to delve into the world of advanced SQL and engage in practical exercises to enhance your skills.
This article provides you with a collection of ten challenging SQL practice exercises specifically for those seeking to enhance their advanced SQL skills. The exercises cover a selection of SQL concepts and will help you refresh your advanced SQL knowledge. Each exercise is accompanied by a detailed solution, allowing you to test your knowledge and gain a deeper understanding of complex SQL concepts. The exercises come from our advanced SQL practice courses . If you want to see more exercises like this, check out these courses:
- Window Functions Practice Set
- 2021 Monthly SQL Practice Sets - Advanced
- 2022 Monthly SQL Practice Sets - Advanced
Find out how you can practice advanced SQL with our platform.
Let’s get started.
Practice is an integral component in mastering SQL; its importance cannot be overstated. The journey to becoming proficient in advanced SQL requires dedication, perseverance, and a strong commitment to continuous practice. By engaging in regular advanced SQL practice, individuals can sharpen their skills, expand their knowledge, and develop a deep understanding of the intricacies of data management and manipulation.
Advanced SQL exercises serve as invaluable tools, challenging learners to apply their theoretical knowledge in practical scenarios and further solidifying their understanding of complex concepts. With each session of dedicated SQL practice, you can discover efficient techniques and gain the confidence needed to tackle real-world data challenges.
Let’s go over the exercises and their solutions.
Advanced SQL Practice Exercises
We’ll present various advanced SQL exercises that cover window functions , JOINs, GROUP BY, common table expressions (CTEs), and more.
Section 1: Advanced SQL JOIN Exercises
In the following advanced SQL exercises, we’ll use a sportswear database that stores information about clothes, clothing categories, colors, customers, and orders. It contains five tables: color , customer , category , clothing , and clothing_order . Let's look at the data in this database.
The color table contains the following columns:
- id stores the unique ID for each color.
- name stores the name of the color.
- extra_fee stores the extra charge (if any) added for clothing ordered in this color.
In the customer table, you'll find the following columns:
- id stores customer IDs.
- first_name stores the customer's first name.
- last_name stores the customer's last name.
- favorite_color_id stores the ID of the customer's favorite color (references the color table).
The category table contains these columns:
- id stores the unique ID for each category.
- name stores the name of the category.
- parent_id stores the ID of the main category for this category (if it's a subcategory). If this value is NULL , it denotes that this category is a main category. Note: Values are related to those in the id column in this table.
The clothing table stores data in the following columns:
- id stores the unique ID for each item.
- name stores the name of that item.
- size stores the size of that clothing: S, M, L, XL, 2XL, or 3XL.
- price stores the item's price.
- color_id stores the item's color (references the color table).
- category_id stores the item's category (references the category table).
The clothing_order table contains the following columns:
- id stores the unique order ID.
- customer_id stores the ID of the customer ordering the clothes (references the customer table).
- clothing_id stores the ID of the item ordered (references the clothing table).
- items stores how many of that clothing item the customer ordered.
- order_date stores the date of the order.
Let’s do some advanced SQL exercises that focus on JOINs .
Display the name of clothing items (name the column clothes ), their color (name the column color ), and the last name and first name of the customer(s) who bought this apparel in their favorite color. Sort rows according to color, in ascending order.
Solution explanation:
We want to display the column values from three different tables ( clothing , color , and customer ), including information on which customer ordered a certain item (from the clothing_order table). Therefore, we need to join these four tables on their common columns.
First, we select from the clothing_order table (aliased as co ) and join it with the clothing table (aliased as cl ). We join the tables using the primary key column of the clothing table ( id ) and the foreign key column of the clothing_order table ( clothing_id ); this foreign key column links the clothing and clothing_order tables.
Next, we join the color table (aliased as col ) with the clothing table (aliased as cl ). Here we use the primary key column of the color table ( id ) and the foreign key column of the clothing table ( color_id ).
Finally, we join the customer table (aliased as cus ) with the clothing_order table (aliased as co ). The foreign key of the clothing_order table ( customer_id ) links to the primary key of the customer table ( id ).
The ON clause stores the condition for the JOIN statement. For example, an item from the clothing table with an id of 23 is joined with an order from the clothing_order table where the clothing_id value equals 23.
Follow this article to see more examples on JOINing three (or more) tables . And here is how to LEFT JOIN multiple tables .
Select the last name and first name of customers and the name of their favorite color for customers with no purchases.
Here we need to display customers’ first and last names from the customer table and their favorite color name from the color table. We must do it only for customers who haven’t placed any orders yet; therefore, we require information from the clothing_order table. So the next step is to join these three tables.
First, we join the customer table (aliased as cus ) with the color table (aliased as col ). To do that, we use the following condition: the primary key column of the color table ( id ) must be equal to the foreign key column of the customer table ( favorite_color_id ). That lets us select the favorite color name instead of its ID.
Here is how to ensure that we list only customers who haven’t placed any orders yet:
- We LEFT JOIN the clothing_order table (aliased as o ) with the customer table (aliased as cus ) to ensure that all rows from the customer table (even the ones with no match) are listed.
- In the WHERE clause, we define a condition to display only the rows with the customer_id column from the clothing_order table equal to NULL (meaning only the customers whose IDs are not in the clothing_order table will be returned).
There are different types of JOINs , including INNER JOIN , LEFT JOIN , RIGHT JOIN , and FULL JOIN . You can learn more by following the linked articles.
Select the name of the main categories (which have a NULL in the parent_id column) and the name of their direct subcategory (if one exists). Name the first column category and the second column subcategory.
Each category listed in the category table has its own ID (stored in the id column); some also have the ID of their parent category (stored in the parent_id column). Thus, we can link the category table with itself to list main categories and their subcategories.
The kind of JOIN where we join a table to itself is colloquially called a self join . When you join a table to itself, you must give different alias names to each copy of the table. Here we have one category table aliased as c1 and another category table aliased as c2 .
We select the name from the category table (aliased as c1 ) and ensure that we list only main categories by having its parent_id column equal to NULL in the WHERE clause. Next, we join the category table (aliased as c1 ) with the category table (aliased as c2 ). The latter one provides subcategories for the main categories. Therefore, in the ON clause, we define that the parent_id column of c2 must be equal to the id column of c1 .
Read this article to learn more about self joins .
The exercises in this section have been taken from our course 2021 Monthly SQL Practice Sets - Advanced . Every month we publish a new SQL practice course in our Monthly SQL Practice track; every odd-numbered month, the course is at an advanced level. The advanced SQL practice courses from 2021 have been collected in our 2021 Monthly SQL Practice Sets - Advanced course. Check it out to find more JOIN exercises and other advanced SQL challenges.
Section 2: Advanced GROUP BY Exercises
In the following advanced SQL exercises, we’ll use a sportsclub database that stores information about runners and running events. It contains three tables: runner , event , and runner_event . Let's look at the data in this database.
The runner table contains the following columns:
- id stores the unique ID of the runner.
- name stores the runner's name.
- main_distance stores the distance (in meters) that the runner runs during events.
- age stores the runner's age.
- is_female indicates if the runner is male or female.
The event table contains the following columns:
- id stores the unique ID of the event.
- name stores the name of the event (e.g. London Marathon, Warsaw Runs, or New Year Run).
- start_date stores the date of the event.
- city stores the city where the event takes place.
The runner_event table contains the following columns:
- runner_id stores the ID of the runner.
- event_id stores the ID of the event.
Let’s do some advanced SQL exercises that focus on GROUP BY .
Select the main distance and the number of runners that run the given distance ( runners_number ). Display only those rows where the number of runners is greater than 3.
Solution explanation :
We want to get the count of runners for each distance that they run. To do that, we need to group all runners by distance and use the COUNT() aggregate function to calculate how many runners are in each distance group.
We select the main_distance column and GROUP BY this column. Now when we use the COUNT() aggregate functions, it is going to give us the number of runners that match each main_distance value.
The GROUP BY clause is used to group rows from a table based on one or more columns. It divides the result set into subsets or groups, where each group shares the same values in the specified column(s). This allows us to perform aggregate functions (such as SUM() , COUNT() , AVG() , etc.) on each group separately.
Here are the most common GROUP BY interview questions .
To display only the groups with more than three runners, we use a HAVING clause that filters the values returned by the COUNT() aggregate function.
The HAVING clause is often used together with the GROUP BY clause to filter the grouped data based on specific conditions. It works similarly to the WHERE clause, but it operates on the grouped data rather than individual rows. Check out this article to learn more about the HAVING clause .
Display the event name and the number of club members that take part in this event (call this column runner_count ). Note that there may be events in which no club members participate. For these events, the runner_count should equal 0.
Here we want to display the event name from the event table and the number of participants from the runner table. The event and runner tables are linked by a many-to-many relation; to join these tables, we also need the runner_event table that relates events and runners.
First, we select from the event table. Then, we LEFT JOIN it with the runner_event table, which is further LEFT JOINed with the runner table. Why do we use the LEFT JOIN here? Because we want to ensure that all events (even the ones with no participants) are displayed.
We select the event name and the count of all participants; therefore, we need to GROUP BY the event name to get the count of participants per event. Please note that we use COUNT(runner_id) instead of COUNT(*) . This is to ensure that we display zero for events with no participants (i.e. for events that do not link to any runner_id ). You can read more about different variants of the COUNT() function here .
Display the distance and the number of runners there are for the following age categories: under 20, 20–29, 30–39, 40–49, and over 50. Use the following column aliases: under_20 , age_20_29 , age_30_39 , age_40_49 , and over_50 .
This is similar to Exercise 4 – we want to know the number of runners per distance value. So we select the main_distance column and GROUP BY this column. Then, we use several COUNT() aggregate functions to get the number of runners per distance. However, here we need to further divide the runners according to their age.
The CASE WHEN statement comes in handy here, as it can be used to evaluate conditions and return different values based on the results of those conditions. We can pass it as an argument to the COUNT() aggregate function to get the number of runners fulfilling a given condition. Let’s see how that works.
This CASE WHEN statement returns id only when a runner’s age is greater than or equal to 20 and less than 30. Otherwise, it returns NULL . When wrapped in the COUNT() aggregate function, it returns the count of runners fulfilling the condition defined in the CASE WHEN statement.
To get the number of runners for each of the five age groups, we need to use as many COUNT() functions and CASE WHEN statements as we have age groups. You can read about counting rows by combining CASE WHEN and GROUP BY here .
Section 3: Advanced Window Functions Exercises
In the following advanced SQL exercises, we’ll use a Northwind database for an online shop with numerous foods. It contains six tables: customers , orders , products , categories , order_items , and channels . Let's look at the data in this database.
The customers table has 15 columns:
- customer_id stores the ID of the customer.
- email stores the customer’s email address.
- full_name stores the customer’s full name.
- address stores the customer’s street and house number.
- city stores the city where the customer lives.
- region stores the customer’s region (not always applicable).
- postal_code stores the customer’s ZIP/post code.
- country stores the customer’s country.
- phone stores the customer’s phone number.
- registration_date stores the date on which the customer registered.
- channel_id stores the ID of the channel through which the customer found the shop.
- first_order_id stores the ID of the first order made by the customer.
- first_order_date stores the date of the customer’s first order.
- last_order_id stores the ID of the customer’s last (i.e. most recent) order.
- last_order_date stores the date of the customer’s last order.
The orders table has the following columns:
- order_id stores the ID of the order.
- customer_id stores the ID of the customer who placed the order.
- order_date stores the date when the order was placed.
- total_amount stores the total amount paid for the order.
- ship_name stores the name of the person to whom the order was sent.
- ship_address stores the address (house number and street) where the order was sent.
- ship_city stores the city where the order was sent.
- ship_region stores the region in which the city is located.
- ship_postalcode stores the destination post code.
- ship_country stores the destination country.
- shipped_date stores the date when the order was shipped.
The products table has the following columns:
- product_id stores the ID of the product.
- product_name stores the name of the product.
- category_id stores the category to which the product belongs.
- unit_price stores the price for one unit of the product (e.g. per bottle, pack, etc.).
- discontinued indicates if the product is no longer sold.
The categories table has the following columns:
- category_id stores the ID of the category.
- category_name stores the name of the category.
- description stores a short description of the category.
The order_items table has the following columns:
- order_id stores the ID of the order in which the product was bought.
- product_id stores the ID of the product purchased in the order.
- unit_price stores the per-unit price of the product. (Note that this can be different from the price in the product’s category; the price can change over time and discounts can be applied.)
- quantity stores the number of units bought in the order.
- discount stores the discount applied to the given product.
The channels table has the following columns:
- channel_name stores the name of the channel through which the customer found the shop.
Let’s do some advanced SQL exercises that focus on window functions.
Create a dense ranking of the orders based on their total_amount . The bigger the amount, the higher the order should be. If two orders have the same total_amount , the older order should go higher (you'll have to add the column order_date to the ordering). Name the ranking column rank . After that, select only the orders with the three highest dense rankings . Show the rank, order_id , and total_amount .
Let’s start with the first part of the instruction. We want to create a dense ranking of orders based on their total_amount (the greater the value, the higher the rank) and their order_date value (the older the date, the higher the rank). Please note that the rank value may be duplicated only when total_amount and order_date columns are both equal for more than one row.
To do that, we use the DENSE_RANK() window function. In its OVER() clause, we specify the order: descending for total_amount values and ascending for order_date values. We also display the order_id and total_amount columns from the orders table.
Until now, we listed all orders along with their dense rank values. But we want to see only the top 3 orders (where the rank column is less than or equal to 3). Let’s analyze the steps we take from here:
- We define a Common Table Expression (CTE) using this SELECT statement – i.e. we use the WITH clause followed by the CTE’s name and then place the SELECT statement within parentheses.
- Then we select from this CTE, providing the condition for the rank column in the WHERE clause.
You may wonder why we need such a complex syntax that defines a CTE and then queries it. You may say that we could set the condition for the rank column in the WHERE clause of the first SELECT query. Well, that’s not possible because of the SQL query order of execution.
We have to use the Common Table Expression here because you can’t use window functions in the WHERE clause. The order of operations in SQL is as follows:
- FROM , JOIN
- Aggregate functions
- Window functions
You may only use window functions in SELECT and ORDER BY clauses. If you want to refer to window functions in the WHERE clause, you must place the window function computation in a CTE (like we did in our example) or in a subquery and refer to the window function in the outer query.
Follow this article to learn more about CTEs and recursive CTEs .
To give you some background on the available ranking functions , there are three functions that let you rank your data: RANK() , DENSE_RANK() , and ROW_NUMBER() . Let’s see them in action.
The RANK() function assigns the same rank if multiple consecutive rows have the same value. Then, the next row gets the next rank as if the previous rows had distinct values. Here, the ranks 1,1,1 are followed by 4 (as if it was 1,2,3 instead of 1,1,1 ).
The DENSE_RANK() function also assigns the same rank if multiple consecutive rows have the same value. Then, the next row gets the next rank one greater than the previous one. Here, 1,1,1 is followed by 2.
The ROW_NUMBER() function assigns consecutive numbers to each next row without considering the row values.
Here is an article on how to rank data . You can also learn more about differences between SQL’s ranking functions .
In this exercise, we're going to compute the difference between two consecutive orders from the same customer.
Show the ID of the order ( order_id ), the ID of the customer ( customer_id ), the total_amount of the order, the total_amount of the previous order based on the order_date (name the column previous_value ), and the difference between the total_amount of the current order and the previous order (name the column delta ).
Here we select the order ID, customer ID, and total amount from the orders table. The LAG() function fetches the previous total_amount value. In the OVER() clause, we define the LAG() function separately for each customer and order the outcome by an order date. Finally, we subtract the value returned by the LAG() function from the total_amount value for each row to get the delta.
The previous_value column stores null for the first row, as there are no previous values. Therefore, the delta column is also null for the first row. The following delta column values store the differences between consecutive orders made by the same customer.
It is worth mentioning that a delta represents the difference between two values. By calculating the delta between daily sales amounts, we can determine the direction of sales growth/decline on a day-to-day basis.
Follow this article to learn more about calculating differences between two rows . And here is how to compute year-over-year differences .
For each customer and their orders, show the following:
- customer_id – the ID of the customer.
- full_name – the full name of the customer.
- order_id – the ID of the order.
- order_date – the date of the order.
- total_amount – the total spent on this order.
- running_total – the running total spent by the given customer.
Sort the rows by customer ID and order date.
A running total refers to the calculation that accumulates the values of a specific column or expression as rows are processed in a result set. It provides a running sum of the values encountered up to the current row. A running total is calculated by adding the current value to the sum of all previous values. This can be particularly useful in various scenarios, such as tracking cumulative sales, calculating running balances or analyzing cumulative progress over time.
Follow this article to learn more about computing a running total . And here is an article about computing running averages .
We select customer ID, order ID, order date, and order total from the orders table. Then, we join the orders table with the customers table on their respective customer_id columns so we can display the customer's full name.
We use the SUM() window function to calculate the running total for each customer separately ( PARTITION BY orders.customer_id ) and then order ascendingly by date ( ORDER BY orders.order_date ).
Finally, we order the output of this query by customer ID and order date.
Section 4: Advanced Recursive Query Exercises
In the following advanced SQL exercises, we’ll use a website database that stores information about students and courses. It contains three tables: student , course , and student_course . Let's look at the data in this database.
The student table contains the following columns:
- id stores the unique ID number for each student.
- name stores the student's name.
- email stores the student's email.
- invited_by_id stores the ID of the student that invited this student to the website. If the student signed up without an invitation, this column will be NULL.
The course table consists of the following columns:
- id stores the unique ID number for each course.
- name stores the course's name.
The student_course table contains the following columns:
- id stores the unique ID for each row.
- student_id stores the ID of the student.
- course_id stores the ID of the course.
- minutes_spent stores the number of minutes the student spent on the course.
- is_completed is set to True when the student finishes the course.
The exercises in this section have been taken from our Window Functions Practice Set . In this set, you will find more window function exercises on databases that store retail, track competitions, and website traffic.
Let’s do some advanced SQL exercises that focus on recursive queries.
Show the path of invitations for each student (name this column path ). For example, if Mary was invited by Alice and Alice wasn't invited by anyone, the path for Mary should look like this: Alice->Mary .
Include each student's id , name , and invited_by_id in the results.
This exercise requires us to create a custom value for the path column that contains the invitation path for each customer. For example, Ann Smith was invited by Veronica Knight , who in turn was invited by Karli Roberson ; hence, we get the path column as Karli Roberson->Veronica Knight->Ann Smith for the name Ann Smith .
As you may notice, we need a recursion mechanism to dig down into the invitation path. We can write a recursive query by defining it with the WITH RECURSIVE statement, followed by the query name.
The content of the hierarchy recursive query is as follows:
- We select the id , name , and invited_by_id columns from the student table. Then, we use the CAST() function to cast the name column type to the TEXT data type, ensuring smooth concatenation (with -> and the following names) in the main query. The WHERE clause condition ensures that only students who haven’t been invited are listed by this query.
- The UNION ALL operator combines the result sets of two or more SELECT statements without removing duplicates. Here the queries on which UNION ALL is performed have the same sets of four columns; the result set of one is appended to the results set of another.
- In the next SELECT statement, we again select the id , name , and invited_by_id columns from the student table. Then, we concatenate the path column (that comes from the hierarchy recursive query as defined in the first SELECT statement) with the -> sign and the student name. To accomplish this concatenation, we select from both the student table and the hierarchy recursive query.(This is where the recursive mechanism comes into play.) In the WHERE clause, we define that the invited_by_id column of the student table is equal to the id column of the hierarchy recursive query, so we get the student name who invited the current student; on the next iteration, we get the name of the student who invited that student, and so on.
This is called a recursive query, as it queries itself to work its way down the invitation path.
The advanced SQL exercises presented in this article provide a comprehensive platform for honing your SQL skills, one query at a time. By delving into window functions, JOINs , GROUP BY , and more, you have expanded your understanding of complex SQL concepts and gained hands-on experience in solving real-world data challenges.
Practice is the key to mastering SQL skills. Through consistent practice, you can elevate your proficiency and transform your theoretical knowledge into practical expertise. This article showcased exercises from our courses; you can discover more exercises like this by enrolling in our:
Sign up now and get started for free! Good luck!
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
14.4.4 Assignment Operators
Table 14.6 Assignment Operators
Assignment operator. Causes the user variable on the left hand side of the operator to take on the value to its right. The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this value is a scalar value). You can perform multiple assignments in the same SET statement. You can perform multiple assignments in the same statement.
Unlike = , the := operator is never interpreted as a comparison operator. This means you can use := in any valid SQL statement (not just in SET statements) to assign a value to a variable.
You can make value assignments using := in other statements besides SELECT , such as UPDATE , as shown here:
While it is also possible both to set and to read the value of the same variable in a single SQL statement using the := operator, this is not recommended. Section 11.4, “User-Defined Variables” , explains why you should avoid doing this.
This operator is used to perform value assignments in two cases, described in the next two paragraphs.
Within a SET statement, = is treated as an assignment operator that causes the user variable on the left hand side of the operator to take on the value to its right. (In other words, when used in a SET statement, = is treated identically to := .) The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this value is a scalar value). You can perform multiple assignments in the same SET statement.
In the SET clause of an UPDATE statement, = also acts as an assignment operator; in this case, however, it causes the column named on the left hand side of the operator to assume the value given to the right, provided any WHERE conditions that are part of the UPDATE are met. You can make multiple assignments in the same SET clause of an UPDATE statement.
In any other context, = is treated as a comparison operator .
For more information, see Section 15.7.6.1, “SET Syntax for Variable Assignment” , Section 15.2.17, “UPDATE Statement” , and Section 15.2.15, “Subqueries” .
IMAGES
VIDEO
COMMENTS
SQL statements are used to retrieve and update data in a database. The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with SQL. Hope, these exercises help you to improve your SQL skills.
The assignment operator (=) in SQL Server is used to assign the values to a variable. The equal sign (=) is the only Transact-SQL assignment operator. In the following example, we create the @MyCounter variable, and then the assignment operator sets the @MyCounter variable to a value i.e. 1 .
"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.
We have gathered a variety of SQL exercises (with answers) for each SQL Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.
The equal sign (=) is the only Transact-SQL assignment operator. In the following example, the @MyCounter variable is created, and then the assignment operator sets @MyCounter to a value returned by an expression.
We present a comprehensive guide to setting up your own SQL database for practicing SQL with hands-on exercises.
We present a comprehensive guide to setting up your own SQL database for practicing SQL with hands-on exercises.
We present a comprehensive guide to setting up your own SQL database for practicing SQL with hands-on exercises.
Analyze data within a database using SQL. Create a relational database on Cloud and work with tables. Write SQL statements including SELECT, INSERT, UPDATE, and DELETE.
Assign a value (as part of a SET statement, or as part of the SET clause in an UPDATE statement) :=. Assignment operator. Causes the user variable on the left hand side of the operator to take on the value to its right.