-- variables before they are cleared.
SELECT @ErrorVar = @@ERROR
,@RowCountVar = @@ROWCOUNT;
The text above is shown for @@ERROR, but the description of @@ROWCOUNT doesn't mention anything like this at all.
However, it is, of course, good practice to capture both values using a SELECT statement if you want to retrieve them simultaneously.
very nice ..... i liked it |
Nice article! Thanks.. |
I used interchangeably so far. Suprised to know these differences and excellent articulation |
Great article, very well explained. Thanks. |
Nice article, I always wondered the difference but never tested it. If I am looping through a cursor ( for admin purposes not application data purposes ) I do a Select @variable = '' to clear it also before populating it again. |
Very nice blog, infect we addressed one of our recent issue by replacing set with select but was not aware why set was assigning null values occasionally, now the reasons got cleared. |
Good article. The caveat about what happens when the variable is not populated successfully can't be overstated. The fact that a failed Select leaves the previous value in place has some serious implications for the code unless the developer gives the variable a default value and checks the value after the Select statement to ensure that it has, indeed, changed. I've been bitten by that particular issue on occasion when I forgot to add such a safeguard - the code ran and returned expected results the first time around but not in later tests. It introduces a subtle bug to the code that can be really hard to track down. Performance of Set vs Select has to be taken into consideration when deciding which to use. Unless the design has changed, using a Set executes an assignation language element (SQL Server Magazine Reader-to-Reader tip February 2007 ). According to the tip, a Select is about 59% faster than a Set and for one to a handful of value assignments that's not a problem and the standard should rule. However, what if you are assigning the variable's value repeatedly in a loop that will run thousands of times? Hopefully you won't since that solution is most likely not set-based, but if that's the only way to address a particular problem you might do it. In such a case, it would be worthwhile deviating from the ANSI standard. |
Related Content
SQL Declare Variable to Define and Use Variables in SQL Server code
How to use @@ROWCOUNT in SQL Server
Using SQL Variables in SQL Server Code and Queries
SQL Variables in Scripts, Functions, Stored Procedures, SQLCMD and More
The Basics of SQL Server Variables
Nullability settings with select into and variables
SQL Server 2008 Inline variable initialization and Compound assignment
Free Learning Guides
Learn Power BI
What is SQL Server?
Download Links
Become a DBA
What is SSIS?
Related Categories
Change Data Capture
Common Table Expressions
Dynamic SQL
Error Handling
Stored Procedures
Transactions
Development
Date Functions
System Functions
JOIN Tables
SQL Server Management Studio
Database Administration
Performance
Performance Tuning
Locking and Blocking
Data Analytics \ ETL
Microsoft Fabric
Azure Data Factory
Integration Services
Popular Articles
Date and Time Conversions Using SQL Server
Format SQL Server Dates with FORMAT Function
SQL Server CROSS APPLY and OUTER APPLY
SQL Server Cursor Example
SQL CASE Statement in Where Clause to Filter Based on a Condition or Expression
DROP TABLE IF EXISTS Examples for SQL Server
SQL NOT IN Operator
SQL Convert Date to YYYYMMDD
Rolling up multiple rows into a single row and column for SQL Server data
Format numbers in SQL Server
Script to retrieve SQL Server database backup history and no backups
Resolving could not open a connection to SQL Server errors
How to install SQL Server 2022 step by step
SQL Server PIVOT and UNPIVOT Examples
How to monitor backup and restore progress in SQL Server
An Introduction to SQL Triggers
List SQL Server Login and User Permissions with fn_my_permissions
SQL Server Management Studio Dark Mode
Using MERGE in SQL Server to insert, update and delete at the same time
SQL Server Loop through Table Rows without Cursor
Back to: SQL Server Tutorial For Beginners and Professionals
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.
Please use the below script to create and populate the employee table with the required data., assignment operator:.
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.
Example without using compound assignment operators.
The following example is without using Compound Assignment Operators.
Following are the list of available compound operators in sql server.
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.
SQL Server provides us with two methods in T-SQL to assign a value to a previously created local SQL variable. The first method is the SET statement, the ANSI standard statement that is commonly used for variable value assignment. The second statement is the SELECT statement. In addition to its main usage to form the logic that is used to retrieve data from a database table or multiple tables in SQL Server, the SELECT statement can be used also to assign a value to a previously created local variable directly or from a variable, view or table.
Although both T-SQL statements fulfill the SQL variable value assignment task, there is a number of differences between the SET and SELECT statements that may lead you to choose one of them in specific circumstances, over the other. In this article, we will describe, in detail, when and why to choose between the SET and SELECT T-SQL statements while assigning a value to a variable.
We will start with creating a new table and fill it with few records for our demo. This can be achieved using the below script:
SQLShackDemo TABLE SetVsSelectDemo ID INT IDENTITY (1,1) PRIMARY KEY, Name NVARCHAR (50), GroupNumber INT, Grade INT INTO SetVsSelectDemo VALUES ('Adel',1,350) INTO SetVsSelectDemo VALUES ('Faisal',1,240) INTO SetVsSelectDemo VALUES ('Huda',2,180) INTO SetVsSelectDemo VALUES ('Zaid',2,170) INTO SetVsSelectDemo VALUES ('Zaina',3,290) INTO SetVsSelectDemo VALUES ('John',4,400) INTO SetVsSelectDemo VALUES ('Igor',4,375) |
The inserted data can be checked using the following SELECT statement:
FROM SetVsSelectDemo |
And the data will be shown as below:
If we manage to assign a scalar value for the SQL variable that is previously defined using the DECLARE statement, both the SET and SELECT statements will achieve the target in the same way. The below SET statement is used to assign the @EmpName1 variable with the scalar “Ali” value:
@EmpName1 NVARCHAR(50) @EmpName1 = 'Ali' @EmpName1 |
In the same way, the below SELECT statement can be used to assign the @EmpName2 variable with the scalar “Ali” value:
@EmpName2 NVARCHAR(50) @EmpName2 = 'Ali' @EmpName2 |
The assigned values for the variables in the previous queries will be printed in the Messages tab as shown below:
SQL Server allows us to assign value for a SQL variable from a database table or view. The below query is used to assign the @EmpName variable the Name column value of the third group members from the SetVsSelectDemo table using the SET statement:
@EmpName NVARCHAR(50) @EmpName = (SELECT [Name] FROM SetVsSelectDemo WHERE GroupNumber = 3) @EmpName |
The SELECT statement can be also used to perform the same assignment task in a different way as shown below:
@EmpName NVARCHAR(50) @EmpName = [Name] FROM SetVsSelectDemo WHERE GroupNumber = 3 @EmpName |
The results of the previous two queries will be displayed in the Messages tab as shown below:
Until this point, you can see that both the SET and SELECT statements can perform the variable value assignment task in the same way and differ from the code side only.
Assume that we need to assign values to multiple variables at one shot. The SET statement can assign value to one variable at a time; this means that, if we need to assign values for two variables, we need to write two SET statements. In the below example, each variable requires a separate SET statement to assign it scalar value, before printing it:
@EmpName1 NVARCHAR(50) , @EmpName2 NVARCHAR(50) @EmpName1 = 'Ali' @EmpName2 = 'Fadi' @EmpName1 @EmpName2 |
On the other hand, the SELECT statement can be used to assign values to the previously defined multiple SQL variables using one SELECT statement. The below SELECT statement can be easily used to assign scalar values to the two variables using one SELECT statement before printing it:
@EmpName1 NVARCHAR(50) , @EmpName2 NVARCHAR(50) @EmpName1 = 'Ali', @EmpName2 = 'Fadi' @EmpName1 @EmpName2 |
You can see from the printed result below, that both statements achieve the same task, with the SELECT statement better than the SET statement when trying to assign values to multiple variables due to code simplicity:
Again, if we try to assign values from database table to multiple variables, it requires us SET statements equal to the number of variables. In our example, we need two SET statements to assign values from the SetVsSelectDemo table to the @EmpName and @EmpGrade variables as shown in the script below:
@EmpName NVARCHAR(50), @EmpGrade INT @EmpName = (SELECT [Name] FROM SetVsSelectDemo WHERE GroupNumber = 3) @EmpGrade = (SELECT [Grade] FROM SetVsSelectDemo WHERE GroupNumber = 3) @EmpName @EmpGrade |
On the other hand, only one SELECT statement can be used to assign values from the SetVsSelectDemo table to the @EmpName and @EmpGrade SQL variables, using simpler query as shown clearly below:
@EmpName NVARCHAR(50), @EmpGrade INT @EmpName=[Name] , @EmpGrade =[Grade] FROM SetVsSelectDemo WHERE GroupNumber = 3 @EmpName @EmpGrade |
It is obvious from the previous two queries that the query that is using the SELECT statement is more efficient than the one using the SET statement when assigning values to multiple variables at the same time, due to the fact that, the SET statement can only assign one variable at a time. The similar results of the previous two queries that are printed in the Messages tab will be like the below in our case:
The second point, in which the difference between assigning values to the SQL variables using the SELECT or SET statements appears, is when the result set of the subquery query that is used to assign a value to the variable returns more than one value. In this case, the SET statement will return an error as it accepts only one scalar value from the subquery to assign it to the variable, while the SELECT statement accepts that situation, in which the subquery will return multiple values, without raising any error. You will not, though, have any control on which value will be assigned to the variable, where the last value returned from the subquery will be assigned to the variable.
Assume that we need to assign the Name value of the second group from the previously created SetVsSelectDemo table to the @EmpName SQL variable. Recall that the second group on that table contains two records in the result set as shown below:
The script that is used to assign the @EmpName variable value from the SetVsSelectDemo table using the SET and SELECT statements will be like:
@EmpName NVARCHAR(50) @EmpName = (SELECT [Name] FROM SetVsSelectDemo WHERE GroupNumber = 2) @EmpName @EmpName NVARCHAR(50) @EmpName = [Name] FROM SetVsSelectDemo WHERE GroupNumber = 2 @EmpName |
Due to the fact that, the subquery statement returned two records, assigning value to the @EmpName SQL variable using the SET statement will fail, as the SET statement can assign only single value to the variables. This is not the case when assigning value to the @EmpName variable using the SELECT statement that will succeed with no error, assigning the name from the second returned record, which is “Zaid”, to the variable as shown in the result messages below:
We can learn from the previous result that, when you expect that the subquery will return more than one value, it is better to use the SET statement to assign value to the variable by implementing a proper error handling mechanism, rather than using the SELECT statement that will assign the last returned value to the SQL variable, with no error returned to warn us that the subquery returned multiple values.
Another difference between assigning values to the SQL variables using the SET and SELECT statements, is when the subquery that is used to assign a value to the variable return no value. If the previously declared variable has no initial value, both the SET and SELECT statement will act in the same way, assigning NULL value to that variable.
Assume that we need to assign the @EmpName variable, with no initial value, the Name of the fifth group from the SetVsSelectDemo table. Recall that this table has no records that belong to the fifth group as shown below:
The script that is used to assign the value to the @EmpName variable from the SetVsSelectDemo table will be like:
@EmpName NVARCHAR(50) @EmpName = (SELECT [Name] FROM SetVsSelectDemo WHERE GroupNumber = 5) @EmpName AS SET_Name @EmpName NVARCHAR(50) @EmpName = [Name] FROM SetVsSelectDemo WHERE GroupNumber = 5 @EmpName AS SELECT_Name |
Having no initial value for the @EmpName variable, and no value returned from the subquery, a NULL value will be assigned to that variable in both cases as shown clearly in the result message below:
If the previously declared SQL variable has an initial value, and the subquery that is used to assign a value to the variable returns no value, the SET and SELECT statement will behave in different ways. In this case, the SET statement will override the initial value of the variable and return the NULL value. On the contrary, the SELECT statement will not override the initial value of the variable and will return it, if no value is returned from the assigning subquery.
If we arrange again to assign the @EmpName variable, the Name of the fifth group from the SetVsSelectDemo table, recalling that this table has no records that belong to the fifth group, but this time, after setting an initial value for the @EmpName SQL variable during the variable declaration, using the SET and SELECT statements, as shown in the script below:
@EmpName NVARCHAR(50)='Sanya' @EmpName = (SELECT [Name] FROM SetVsSelectDemo WHERE GroupNumber = 5) @EmpName AS SET_Name @EmpName NVARCHAR(50)='Sanya' @EmpName = [Name] FROM SetVsSelectDemo WHERE GroupNumber = 5 @EmpName AS SELECT_Name |
Taking into consideration that the assigning subquery retuned no value, the query that used the SET statement to assign value to the SQL variable will override the initial value of the variable, returning NULL value, while the query that used the SELECT statement to assign value to the variable will keep the initial value with no change as no value is returned from the subquery, as shown clearly in the results below:
Tony Rogerson brings us an interesting blog post about T-SQL variable assignment and SET vs. SELECT . The issue? With SELECT you can assign values to multiple variables simultaneously. But with SET, you can set up your assignment such that you get an exception if more than one row is assigned to the variable. Both are desirable qualities… But unfortunately, as Tony shows us, it’s difficult to achieve both multiple assignment and getting the exception thrown, at the same time. Tony shows us a solution involving checking for the number of rows affected after the assignment. Creative and effective, but it still has an issue: Unlike with SET when it throws an exception, with Tony’s solution the variables will still have been affected by the assignment.
As I was reading Tony’s post, I couldn’t help but think that there must be another way. And low and behold, there is — at least, in SQL Server 2005. Thanks to the power of windowed aggregates we can have our multiple pieces of cake and eat them, all at the same time. Wonderful stuff.
So, here’s what you do: Set up a CTE that selects the columns you’d like to assign to your variables, and also get COUNT(*), partitioned by 1 (or some other arbitrary literal). By partitioning by a literal, we will end up with the row count for the entire set. In the outer query, express the assignments from the columns returned by the CTE, but add an additional WHERE clause that compares the value of the COUNT(*) column with a subquery against a table of numbers. In the following example which I’ve adapted from Tony’s blog, I’m using master..spt_values for the numbers, but you are encouraged to use a properly-indexed table of numbers, should you decide to use this technique:
As you’ll see if you run this on your end, an exception is thrown and the values of the variables are not affected. This works because the subquery used in the WHERE clause will return more than one value if theCount is greater than 1, thereby violating the rule that subqueries must only return one value.
The price you’ll pay for this convenience? Extremely complex code for a simple variable assignment, in addition to a slight performance penalty. Is it worth it? Probably not, at least for me. To be honest, I seriously doubt I will ever use this — I’ve never been especially concerned with the chance of multiple rows screwing up my variable assignment, and those times that it has happened, I’ve remedied the situation other ways (e.g., defining a better primary key). That said, I think this was an interesting T-SQL challenge, and if anyone comes up with a more elegant solution than Tony’s or mine, I’d love to see it!
Looking forward 100 months (t-sql tuesday #100): the roundup, t-sql tuesday #200 (v1.0): last of the dbas, invitation: t-sql tuesday #100 – looking forward 100 months.
Hi Adam, A similar effect can be obtained (with a more efficient plan and fewer keystrokes!) by using the ROW_NUMBER function in an ORDER BY clause on the assignment, as shown in this example: — Table representing some arbitrary result set DECLARE @T TABLE (id INT NOT NULL) — Simulate a query returning more than 1 row INSERT @T (id) SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3; — The variable we will assign to DECLARE @id INTEGER; — Default value SET @id = -1; — The assignment statement — The ORDER BY clause will throw an exception — if row number 2 exists… SELECT @id = id FROM @T ORDER BY (1 / (ROW_NUMBER() OVER (ORDER BY (SELECT 1)) – 2)); — Untouched value if more than one row was returned SELECT @id; … The "ORDER BY (1 / (ROW_NUMBER() OVER (ORDER BY (SELECT 1)) – 2))" clause can be appended to any assignment statement (the ‘select 1’ part removes any dependency on the preceding query). If not saying for a moment that I’ll be using this routinely – but thanks for the puzzle! </Paul>
Good job, Paul!
Thanks Adam!
what about trick with tinyint (MS SQL 2008)? DECLARE @reserved INT =-1, @rowcnt INT=-1, @used INT=-1, @control TINYINT=0 SELECT @control=255*COUNT(*) OVER(PARTITION BY 1) , @reserved = reserved, @rowcnt = rowcnt, @used = used FROM sysobjects so INNER JOIN sysindexes si ON si.id = so.id WHERE so.name = ‘sysrowsets’ SELECT @reserved, @rowcnt, @used, @control
Nice one, Limojoe!
This tweaks what has been said above? DECLARE @reserved INT, @rowcnt INT, @used INT SELECT @reserved = reserved, @rowcnt = rowcnt, @used = used FROM sysobjects so INNER JOIN sysindexes si ON si.id = so.id WHERE so.name = ‘sysrowsets’ order by case when COUNT(*) OVER(PARTITION BY 1) > 1 then cast(cast(COUNT(*) OVER(PARTITION BY 1) as varchar ) + ‘ Rows returned, expected only one.’ as int) end — Should return: Msg 245, Level 16, State 1, Line 8 Conversion failed when converting the varchar value ‘3 Rows returned, expected only one.’ to data type int.
Comments are closed.
The career influence of usenet strangers (t-sql tuesday #096), playing the third-party recruiter game (t-sql tuesday #093), the sql hall of shame, the guru (t-sql tuesday #089), solving the net changes problem with temporal tables (t-sql tuesday #087).
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.
You will get 1 point for each correct answer. Your score and total score will always be displayed.
Start SQL Exercises ❯
If you don't know SQL, we suggest that you read our SQL Tutorial from scratch.
Get certified by completing the course
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top references, top examples, get certified.
T-sql variables - declare and set variable.
One of the key features of SQL Server that helps in managing and manipulating data efficiently is the use of variables. Variables in SQL Server are used to store data temporarily during the execution of code. They are essential in writing reusable, readable, and modular code. By using variables, developers can write more flexible and dynamic SQL queries, enhancing the capability to handle data dynamically during runtime. Understanding how to declare, initialize, and manipulate variables is fundamental for anyone looking to master SQL Server programming.
In SQL Server, variables are used to store and manipulate data within a T-SQL script or a stored procedure. Variables provide a way to store temporary values that can be used in various parts of a script or procedure. They can hold different data types, such as integers, strings, dates, or other SQL Server data types.
A Transact-SQL local variable is an database object that can store a single data value of a specific type. Variables are particularly useful for temporarily storing data, which can be manipulated or transferred as needed within batches, stored procedures, or scripts.
The following are the two main types of SQL Server variables: Local variables . They are declared by the user and start with the '@' symbol. Local variables can be used within a procedure or batch. The scope of a local variable is limited to the batch or stored procedure in which it is declared. Once the batch or procedure ends, the variable is de-allocated and ceases to exist. Global variables . They are declared by the system beforehand and start with the '@@' symbol. Global variables can store session information. As these are system-defined, their lifecycle and scope are managed by SQL Server itself, and they persist across different batches and sessions.
To declare a variable uses the keyword DECLARE , assign a variable name and a data type . The DECLARE statement of Transact-SQL will declare a variable as per the instruction given by the user.
The following are the rules behind the DECLARE statement: A name should be assigned by having '@' before itself. A data type and length should be assigned. The most used date types are: INT , DATE , VARCHAR . Initially, the value of the variable is set to null. Examples: DECLARE @EMP_ID INT; DECLARE @EMP_ID AS INT; DECLARE @EMP_NAME VARCHAR (50); DECLARE @EMP_ID AS INT, @EMP_NAME VARCHAR (50);
Syntax for the SET statement to set multiple variables: DECLARE @Local_Variable_1 Data_Type, @Local_Variable_2 Data_Type SET @Local_Variable_1 = Value SET @Local_Variable_2 = Value Example: DECLARE @EMP_ID as INT, @EMP_NAME AS VARCHAR(50) SET @EMP_ID = 5 SET @EMP_NAME = 'STEVE' PRINT @EMP_ID PRINT @EMP_NAME
The SELECT statement can be used to select the assigned values by certain criteria as per the requirement of the user. Syntax for the SELECT statement of one variable or multiple variables: DECLARE @Local_Variable Data_Type SET @Local_Variable = Value Example: DECLARE @EMP_ID as INT, @EMP_NAME AS VARCHAR(50) SELECT @EMP_ID = 5, @EMP_NAME = 'STEVE' PRINT @EMP_ID PRINT @EMP_NAME
T-SQL certification
Variables are a fundamental aspect of SQL Server programming, enabling developers to write more efficient, dynamic, and readable SQL scripts. Understanding how to properly declare, initialize, and manage variables can significantly enhance your database operations. Practice is key to mastering their use, so experimenting with different scenarios and applications will build your proficiency and confidence in handling variables effectively in SQL Server.
Table of Contents
Exercise 1: selecting all columns from a table, exercise 2: selecting a few columns from a table, exercise 3: selecting a few columns and filtering numeric data in where, exercise 4: selecting a few columns and filtering text data in where, exercise 5: selecting a few columns and filtering data using two conditions in where, exercise 6: filtering data using where and sorting the output, exercise 7: grouping data by one column, exercise 8: grouping data by multiple columns, exercise 9: filtering data after grouping, exercise 10: selecting columns from two tables, that was fun now, time to do sql practice on your own.
Solve these ten SQL practice problems and test where you stand with your SQL knowledge!
This article is all about SQL practice. It’s the best way to learn SQL. We show you ten SQL practice exercises where you need to apply essential SQL concepts. If you’re an SQL rookie, no need to worry – these examples are for beginners.
Use them as a practice or a way to learn new SQL concepts. For more theoretical background and (even more!) exercises, there’s our interactive SQL Basics course. It teaches you how to select data from one or more tables, aggregate and group data, write subqueries, and use set operations. The course comprises 129 interactive exercises so there is no lack of opportunities for SQL practice, especially if you add some of the 12 ways of learning SQL online to it.
Speaking of practice, let’s start with our exercises!
The question is always where to find data for practicing SQL. We’ll use our dataset for all exercises. No need to limit yourself to this, though – you can find other free online datasets for practicing SQL .
Our dataset consists of two tables.
The table distribution_companies lists movie distribution companies with the following columns:
The table is shown below.
id | company_name |
---|---|
1 | Columbia Pictures |
2 | Paramount Pictures |
3 | Warner Bros. Pictures |
4 | United Artists |
5 | Universal Pictures |
6 | New Line Cinema |
7 | Miramax Films |
8 | Produzioni Europee Associate |
9 | Buena Vista |
10 | StudioCanal |
The second table is movies . These are the columns:
id | movie_title | imdb_rating | year_released | budget | box_office | distribution_company_id | language |
---|---|---|---|---|---|---|---|
1 | The Shawshank Redemption | 9.2 | 1994 | 25.00 | 73.30 | 1 | English |
2 | The Godfather | 9.2 | 1972 | 7.20 | 291.00 | 2 | English |
3 | The Dark Knight | 9.0 | 2008 | 185.00 | 1,006.00 | 3 | English |
4 | The Godfather Part II | 9.0 | 1974 | 13.00 | 93.00 | 2 | English, Sicilian |
5 | 12 Angry Men | 9.0 | 1957 | 0.34 | 2.00 | 4 | English |
6 | Schindler's List | 8.9 | 1993 | 22.00 | 322.20 | 5 | English, German, Yiddish |
7 | The Lord of the Rings: The Return of the King | 8.9 | 2003 | 94.00 | 1,146.00 | 6 | English |
8 | Pulp Fiction | 8.8 | 1994 | 8.50 | 213.90 | 7 | English |
9 | The Lord of the Rings: The Fellowship of the Ring | 8.8 | 2001 | 93.00 | 898.20 | 6 | English |
10 | The Good, the Bad and the Ugly | 8.8 | 1966 | 1.20 | 38.90 | 8 | English, Italian, Spanish |
Exercise: Select all data from the table distribution_companies .
Solution explanation: Select the data using the SELECT statement. To select all the columns, use an asterisk ( * ). The table from which the data is selected is specified in the FROM clause.
Solution output:
Exercise: For each movie, select the movie title, the IMDb rating, and the year the movie was released.
Solution explanation: List all the columns needed ( movie_title , imdb_rating , and year_released ) in the SELECT statement, separated by the comma. Reference the table movies in the FROM clause.
movie_title | imdb_rating | year_released |
---|---|---|
The Shawshank Redemption | 9.2 | 1994 |
The Godfather | 9.2 | 1972 |
The Dark Knight | 9.0 | 2008 |
The Godfather Part II | 9.0 | 1974 |
12 Angry Men | 9.0 | 1957 |
Schindler's List | 8.9 | 1993 |
The Lord of the Rings: The Return of the King | 8.9 | 2003 |
Pulp Fiction | 8.8 | 1994 |
The Lord of the Rings: The Fellowship of the Ring | 8.8 | 2001 |
The Good, the Bad and the Ugly | 8.8 | 1966 |
Exercise: Select the columns movie_title and box_office from the table movies . Show only movies with earnings above $300 million.
Solution explanation: List the columns in SELECT and reference the table in FROM . Use a WHERE clause to filter the data – write the column box_office and use the ‘greater than’ operator ( > ) to show only values above $300 million.
movie_title | box_office |
---|---|
The Dark Knight | 1,006.00 |
Schindler's List | 322.20 |
The Lord of the Rings: The Return of the King | 1,146.00 |
The Lord of the Rings: The Fellowship of the Ring | 898.20 |
Exercise: Select the columns movie_title , imdb_rating , and year_released from the table movies . Show movies that have the word ‘Godfather’ in the title.
Solution explanation: List the columns in SELECT and reference the table in the FROM clause. Use a WHERE clause to filter the data. After writing the column name, use the LIKE logical operator to look for ‘Godfather’ in the movie title, written in single quotes. To find the word anywhere in the movie title, place the wildcard character ( % ) before and after the word.
movie_title | imdb_rating | year_released |
---|---|---|
The Godfather | 9.2 | 1972 |
The Godfather Part II | 9.0 | 1974 |
Exercise: Select the columns movie_title , imdb_rating , and year_released from the table movies . Show movies that were released before 2001 and had a rating above 9.
Solution explanation: List the columns in SELECT and reference the table in FROM . Set the first condition that the year released is before 2001 using the ‘less than’ ( < ) operator. To add another condition, use the AND logical operator. Use the same logic as the first condition, this time using the ‘greater than’ operator with the column imdb_rating .
movie_title | imdb_rating | year_released |
---|---|---|
The Shawshank Redemption | 9.2 | 1994 |
The Godfather | 9.2 | 1972 |
Exercise: Select the columns movie_title , imdb_rating , and year_released from the table movies . Show movies released after 1991. Sort the output by the year released in ascending order.
Solution explanation: List the columns in SELECT and reference the table in FROM . Filter the data with WHERE by applying the ‘greater than’ operator to the column year_released . To sort the data, use an ORDER BY clause and write the column name by which you wish to sort. The type of sorting is specified by writing ASC (ascending) or DESC (descending). If the type is omitted, the output is sorted in ascending order by default.
movie_title | imdb_rating | year_released |
---|---|---|
Schindler's List | 8.9 | 1993 |
The Shawshank Redemption | 9.2 | 1994 |
Pulp Fiction | 8.8 | 1994 |
The Lord of the Rings: The Fellowship of the Ring | 8.8 | 2001 |
The Lord of the Rings: The Return of the King | 8.9 | 2003 |
The Dark Knight | 9.0 | 2008 |
Exercise: Show the count of movies per each language category.
Solution explanation: Select the column language from the table movies . To count the number of movies, use the aggregate function COUNT() . Use the asterisk ( * ) to count the rows, which equals the count of movies. To give this column a name, use the AS keyword followed by the desired name. To show the count by language, you need to group the data by it, so write the column language in the GROUP BY clause.
language | number_of_movies |
---|---|
English | 7 |
English, German, Yiddish | 1 |
English, Sicilian | 1 |
English, Italian, Spanish | 1 |
Exercise: Show the count of movies by year released and language. Sort results by the release date in ascending order.
Solution explanation: List the columns year_released and language from the table movies in SELECT . Use COUNT(*) to count the number of movies and give this column a name using the AS keyword. Specify the columns by which you want to group in the GROUP BY clause. Separate each column name with a comma. Sort the output using ORDER BY with the column year_released and the ASC keyword.
year_released | language | number_of_movies |
---|---|---|
1957 | English | 1 |
1966 | English, Italian, Spanish | 1 |
1972 | English | 1 |
1974 | English, Sicilian | 1 |
1993 | English, German, Yiddish | 1 |
1994 | English | 2 |
2001 | English | 1 |
2003 | English | 1 |
2008 | English | 1 |
Exercise: Show the languages spoken and the average movie budget by language category. Show only the languages with an average budget above $50 million.
Solution explanation: Select the column language from the table movies . To compute the average budget, use the aggregate function AVG() with the column budget in parentheses. Name the column in the output by using the AS keyword. Group the data by rating using GROUP BY . To filter the data after grouping, use a HAVING clause. In it, use the same AVG() construct as in SELECT and set the values to be above 50 using the ‘greater than’ operator.
language | movie_budget |
---|---|
English | 59.01 |
Exercise: Show movie titles from the table movies , each with the name of its distribution company.
Solution explanation: List the columns movie_title and company_name in SELECT . In the FROM clause, reference the table distribution_companies . Give it an alias dc to shorten its name for use later. The AS keyword is omitted here; you may use it if you wish. To access the data from the other table, use JOIN (it may also be written as INNER JOIN ) and write the table name after it. Give this table an alias also. The join used here is an inner type of join; it returns only the rows that match the joining condition specified in the ON clause. The tables are joined where the column id from the table distribution_companies is equal to the column distribution_company_id from the table movies . To specify which column is from which table, use the corresponding alias of each table.
movie_title | company_name |
---|---|
The Shawshank Redemption | Columbia Pictures |
The Godfather Part II | Paramount Pictures |
The Godfather | Paramount Pictures |
The Dark Knight | Warner Bros. Pictures |
12 Angry Men | United Artists |
Schindler's List | Universal Pictures |
The Lord of the Rings: The Fellowship of the Ring | New Line Cinema |
The Lord of the Rings: The Return of the King | New Line Cinema |
Pulp Fiction | Miramax Films |
The Good, the Bad and the Ugly | Produzioni Europee Associate |
These ten SQL practice exercises give you a taste of what practicing SQL looks like. Whether you are at the beginner, intermediate, or advanced level, it’s the same. What changes is the complexity of the problems you solve and of the code you write.
Look for more challenges in the SQL Basics course and the Monthly SQL Practice track. Both are excellent for your SQL practice online. This is true, especially if you do not have an opportunity to use SQL on a daily basis in your job.
So, don’t try to test how long it takes to forget what you once knew in SQL! Use every opportunity to solve as many SQL practice problems as possible.
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
What is sql.
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. 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. Currently following sections are available, we are working hard to add more exercises. Happy Coding!
You may read our SQL tutorial before solving the following exercises.
List of SQL Exercises
Structure of inventory database :
Structure of HR database :
Structure of movie database :
Structure of soccer database :
Structure of employee database :
Structure of hospital database :
Syntax diagram of SQL SELECT statement
You may download the structure and data of the tables of database on which SQL Exercises are built.
Please note that PostgreSQL 9.4 is used and the file which you would download is generated using pg_dump
Follow us on Facebook and Twitter for latest update.
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 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 .
let’s create the table schemas and insert some sample data into them.
sale_id | product_id | quantity_sold | sale_date | total_price |
---|---|---|---|---|
1 | 101 | 5 | 2024-01-01 | 2500.00 |
2 | 102 | 3 | 2024-01-02 | 900.00 |
3 | 103 | 2 | 2024-01-02 | 60.00 |
4 | 104 | 4 | 2024-01-03 | 80.00 |
5 | 105 | 6 | 2024-01-03 | 90.00 |
product_id | product_name | category | unit_price |
---|---|---|---|
101 | Laptop | Electronics | 500.00 |
102 | Smartphone | Electronics | 300.00 |
103 | Headphones | Electronics | 30.00 |
104 | Keyboard | Electronics | 20.00 |
105 | Mouse | Electronics | 15.00 |
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.
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.
product_name | unit_price |
---|---|
Laptop | 500.00 |
Smartphone | 300.00 |
Headphones | 30.00 |
Keyboard | 20.00 |
Mouse | 15.00 |
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.
sale_id | sale_date |
---|---|
1 | 2024-01-01 |
2 | 2024-01-02 |
3 | 2024-01-02 |
4 | 2024-01-03 |
5 | 2024-01-03 |
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.
sale_id | product_id | quantity_sold | sale_date | total_price |
---|---|---|---|---|
1 | 101 | 5 | 2024-01-01 | 2500.00 |
2 | 102 | 3 | 2024-01-02 | 900.00 |
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.
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.
sale_id | total_price |
---|---|
4 | 80.00 |
5 | 90.00 |
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.
product_id | product_name |
---|---|
101 | Laptop |
102 | Smartphone |
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.
total_revenue |
---|
3630.00 |
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.
average_unit_price |
---|
173 |
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.
total_quantity_sold |
---|
20 |
This SQL query calculates the total quantity_sold by summing up the quantity_sold column in the Sales table using the SUM() function.
sale_id | product_id | total_price |
---|---|---|
1 | 101 | 2500.00 |
5 | 105 | 90.00 |
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.
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.
product_name |
---|
3630.00 |
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.
average_total_price |
---|
726.000000 |
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.
sale_id | formatted_date |
---|---|
1 | 2024-01-01 |
2 | 2024-01-02 |
3 | 2024-01-02 |
4 | 2024-01-03 |
5 | 2024-01-03 |
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.
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.
product_name | unit_price |
---|---|
Laptop | 500.00 |
Smartphone | 300.00 |
Headphones | 30.00 |
Keyboard | 20.00 |
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 $50 and $200 using the BETWEEN operator.
product_name | category |
---|---|
Laptop | Electronics |
Smartphone | Electronics |
Headphones | Electronics |
Keyboard | Electronics |
Mouse | Electronics |
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.
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.
product_name | total_price |
---|---|
Laptop | 2500.00 |
Smartphone | 900.00 |
Headphones | 60.00 |
Keyboard | 80.00 |
Mouse | 90.00 |
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.
category | total_revenue |
---|---|
Electronics | 3630.00 |
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.
category |
---|
Electronics |
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.
product_name |
---|
Headphones |
Keyboard |
Laptop |
Mouse |
Smartphone |
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.
month | sales_count |
---|---|
2024-01 | 5 |
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.
average_quantity_sold |
---|
4.0000 |
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.
product_name | total_revenue |
---|---|
Laptop | 2500.00 |
Smartphone | 900.00 |
Headphones | 60.00 |
Keyboard | 80.00 |
Mouse | 90.00 |
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.
sale_id | product_name |
---|---|
1 | Laptop |
2 | Smartphone |
3 | Headphones |
4 | Keyboard |
5 | Mouse |
This query joins the Sales and Products tables on the product_id column and retrieves the sale_id and product_name for each sale.
category | category_revenue | revenue_percentage |
---|---|---|
Electronics | 3630.00 | 100.000000 |
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.
product_name | total_revenue | revenue_rank |
---|---|---|
Laptop | 2500.00 | 1 |
Smartphone | 900.00 | 2 |
Mouse | 90.00 | 3 |
Keyboard | 80.00 | 4 |
Headphones | 60.00 | 5 |
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.
category | product_name | sale_date | running_total_revenue |
---|---|---|---|
Electronics | Laptop | 2024-01-01 | 2500.00 |
Electronics | Smartphone | 2024-01-02 | 3460.00 |
Electronics | Headphones | 2024-01-02 | 3460.00 |
Electronics | Keyboard | 2024-01-03 | 3630.00 |
Electronics | Mouse | 2024-01-03 | 3630.00 |
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.
sale_id | sales_category |
---|---|
1 | High |
2 | High |
3 | Low |
4 | Low |
5 | 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”.
sale_id | product_id | quantity_sold | sale_date | total_price |
---|---|---|---|---|
1 | 101 | 5 | 2024-01-01 | 2500.00 |
5 | 105 | 6 | 2024-01-03 | 90.00 |
This query selects all sales where the quantity sold is greater than the average quantity sold across all sales in the Sales table.
month | sales_count |
---|---|
2024-01 | 5 |
sale_id | days_since_sale |
---|---|
1 | 185 |
2 | 184 |
3 | 184 |
4 | 183 |
5 | 183 |
This query calculates the number of days between the current date and the sale date for each sale using the DATEDIFF function.
sale_id | day_type |
---|---|
1 | Weekday |
2 | Weekday |
3 | Weekday |
4 | Weekend |
5 | Weekend |
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.
product_name | category | total_sales_amount |
---|---|---|
Laptop | Electronics | 2500.00 |
Smartphone | Electronics | 900.00 |
Headphones | Electronics | 60.00 |
Keyboard | Electronics | 80.00 |
Mouse | Electronics | 90.00 |
This query creates a view named Total_Sales that displays the total sales amount for each product along with their names and categories.
product_name | category | unit_price |
---|---|---|
Laptop | Electronics | 500.00 |
Mouse | Electronics | 15.00 |
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.
sale_id | product_id | quantity_sold | sale_date | total_price |
---|---|---|---|---|
4 | 104 | 4 | 2024-01-03 | 80.00 |
5 | 105 | 6 | 2024-01-03 | 90.00 |
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.
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.
product_name | total_quantity_sold |
---|---|
Mouse | 6 |
Laptop | 5 |
Keyboard | 4 |
This query creates a view named Top_Products that lists the top 3 products based on the total quantity sold.
The quantity in stock for product with product_id 101 should be updated to 5.The transaction should be committed successfully.
product_name | sales_count |
---|---|
Headphones | 1 |
Keyboard | 1 |
Laptop | 1 |
Mouse | 1 |
Smartphone | 1 |
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.
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.
Query without indexing:.
Operation | Details |
---|---|
Filter: (sales.sale_date = DATE’2024-01-01′) | (cost=0.75 rows=1) (actual time=0.020..0.031 rows=1 loops=1) |
Table scan on Sales | (cost=0.75 rows=5) (actual time=0.015..0.021 rows=5 loops=1) |
Operation | Details |
---|---|
Index lookup on Sales using idx_sale_date (sale_date=DATE’2024-01-01′) | (cost=0.35 rows=1) (actual time=0.024..0.024 rows=1 loops=1) |
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.
sale_id | product_id | quantity_sold | sale_date | total_price |
---|---|---|---|---|
1 | 101 | 5 | 2024-01-01 | 2500.00 |
2 | 102 | 3 | 2024-01-02 | 900.00 |
3 | 103 | 2 | 2024-01-02 | 60.00 |
4 | 104 | 4 | 2024-01-03 | 80.00 |
5 | 105 | 6 | 2024-01-03 | 90.00 |
All rows in the Sales table meet the condition of the check constraint, as each quantity_sold value is greater than zero.
product_id | product_name | category | unit_price | total_sales |
---|---|---|---|---|
101 | Laptop | Electronics | 500.00 | 1 |
102 | Smartphone | Electronics | 300.00 | 1 |
103 | Headphones | Electronics | 30.00 | 1 |
104 | Keyboard | Electronics | 20.00 | 1 |
105 | Mouse | Electronics | 15.00 | 1 |
This view provides a concise and organized way to view product details alongside their respective sales information, facilitating analysis and reporting tasks.
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).
product_id | product_name | category | unit_price |
---|---|---|---|
101 | Laptop | Electronics | 550.00 |
102 | Smartphone | Electronics | 300.00 |
103 | Headphones | Electronics | 30.00 |
104 | Keyboard | Electronics | 20.00 |
105 | Mouse | Electronics | 15.00 |
This will update the unit price of the product with product_id 101 to 550.00 in the Products table.
category | total_revenue |
---|---|
Electronics | 3630.00 |
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:
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, improve your coding skills with practice.
As you were browsing something about your browser made us think you were a bot. There are a few reasons this might happen:
To regain access, please make sure that cookies and JavaScript are enabled before reloading the page.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Sets a local variable to the value of an expression.
For assigning variables, we recommend that you use SET @local_variable instead of SELECT @ local_variable .
To view Transact-SQL syntax for SQL Server 2014 (12.x) and earlier versions, see Previous versions documentation .
A declared variable for which a value is to be assigned.
{ = | += | -= | *= | /= | %= | &= | ^= | |= } Assign the value on the right to the variable on the left.
Compound assignment operator:
Operator | Action |
---|---|
= | Assigns the expression that follows, to the variable. |
+= | Add and assign |
-= | Subtract and assign |
*= | Multiply and assign |
/= | Divide and assign |
%= | Modulo and assign |
&= | Bitwise AND and assign |
^= | Bitwise XOR and assign |
|= | Bitwise OR and assign |
Any valid expression . This includes a scalar subquery.
SELECT @ local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.
If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL.
One SELECT statement can initialize multiple local variables.
A SELECT statement that contains a variable assignment cannot be used to also perform typical result set retrieval operations.
In the following example, the variable @var1 is assigned "Generic Name" as its value. The query against the Store table returns no rows because the value specified for CustomerID doesn't exist in the table. The variable retains the "Generic Name" value.
This example uses the AdventureWorksLT sample database, for more information, see AdventureWorks sample databases . The AdventureWorksLT database is used as the sample database for Azure SQL Database.
Here is the result set.
In the following example, a subquery is used to assign a value to @var1 . Because the value requested for CustomerID doesn't exist, the subquery returns no value, and the variable is set to NULL .
Avoid the following pattern for recursive use of variables and expressions:
In this case, it isn't guaranteed that @Var would be updated on a row by row basis. For example, @Var may be set to initial value of @Var for all rows. This is because the order and frequency in which the assignments are processed is nondeterminant. This applies to expressions containing variables string concatenation, as demonstrated below, but also to expressions with non-string variables or += style operators. Use aggregation functions instead for a set-based operation instead of a row-by-row operation.
For string concatenation, instead consider the STRING_AGG function, introduced in SQL Server 2017 (14.x), for scenarios where ordered string concatenation is desired. For more information, see STRING_AGG (Transact-SQL) .
The Transact-SQL code samples in this article use the AdventureWorks2022 or AdventureWorksDW2022 sample database, which you can download from the Microsoft SQL Server Samples and Community Projects home page.
An example to avoid, where using ORDER BY in attempt to order concatenation causes list to be incomplete:
Result set:
Instead, consider:
Was this page helpful?
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .
Submit and view feedback for
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
I'd like to assign some variables inside a query that uses CASE statements for it's columns. Not quite sure how to do this, having trouble finding the right syntax.
This is what I have so far, but it's got syntax errors.
What's the correct place/way to stick those variables in there?
The example you've given should work. You can assign to variables from a case statement. Just pretend that the entire CASE..WHEN..THEN..ELSE..END block is a field. Here is a generic example:
Can you tell us what specific error(s) you are getting?
You could probably do this more easily using ISNULL or COALESCE :
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
IMAGES
COMMENTS
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.
If there are multiple assignment clauses in a single SELECT statement, SQL Server doesn't guarantee the order of evaluation of the expressions. Effects are only visible if there are references among the assignments.
This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts.
Problem SET and SELECT may be used to assign values to variables through T-SQL. Both fulfill the task, but in some scenarios unexpected results may be produced. In this tip I elaborate on the considerations for choosing between the SET and SELECT methods for assigning a value to variable.
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. The assignment operator can also be used to establish ...
In this blog post, we are going to explore what to choose when assigning values to vSQL variables using SET and Select SQL Statements.
Tony Rogerson brings us an interesting blog post about T-SQL variable assignment and SET vs. SELECT. The issue? With SELECT you can assign values to multiple variables simultaneously. But with SET, you can set up your assignment such that you get an exception if more than one row is assigned to the variable. Both are […]
Applies to: SQL Server Azure SQL Managed Instance. An operator is a symbol specifying an action that is performed on one or more expressions. The following table lists the operator categories that the SQL Server Database Engine uses. :: (Scope resolution) = (Assignment operator) Arithmetic operators. Bitwise operators.
Learn SQL with interactive exercises and quizzes at W3Schools SQL Exercises. Test your skills and knowledge on various SQL topics.
T-SQL Variables - Declare and Set variable One of the key features of SQL Server that helps in managing and manipulating data efficiently is the use of variables. Variables in SQL Server are used to store data temporarily during the execution of code. They are essential in writing reusable, readable, and modular code.
You can use SELECT assignment to assign multiple variables. This code generates a single row of constants and assigns each to a variable. SELECT. @var1 = 1, @var2 = 'Zeus'. You can even query tables and do assignment that way: SELECT. @var1 = c.Column1,
These 20 exercises are just what beginners need for SQL query practice. Try to solve each of them, and then look at the solutions. If something needs to be clarified, there are explanations for each solution.
Examples of the SELECT Transact-SQL statement in the Database Engine.
Here are ten SQL practice exercises for your beginner SQL skills. Then, check how you did by comparing your solution to ours.
Free SQL exercises. You are welcome to try any of the 203 exercises listed below, but please do not distribute them in any form without asking for our written permission first. Use a script to create the Wise Owl Music database which you can then use to complete a range of other exercises.
SQL Exercises, Practice, Solution: Structured Query Language (SQL) is a language used to view or change data in databases. The sentences used in this language are called SQL Queries.
CLR user-defined types are created with the CREATE TYPE statement before they can be used in a table definition. To create a column on CLR user-defined type, REFERENCES permission is required on the type. If type_schema_name isn't specified, the SQL Server Database Engine references type_name in the following order: The SQL Server system data type.
7 In SQL Server 2008 and later, it is shorthand for addition / concatenation and assignment.
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.
Information-systems document from University of Maryland, Baltimore County, 9 pages, Help Desk SQL Assignment Will Aguilar Part 2 -Queries with Join This is where you start to turn things in. To turn in your assignment, delete the preceding pages and start with this one. Make sure to put your name up top. Construct SQL to answer each of t
Applies to: SQL Server Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics SQL analytics endpoint in Microsoft Fabric Warehouse in Microsoft Fabric Sets a local variable to the value of an expression. For assigning variables, we recommend that you use SET @local_variable instead of SELECT @ local_variable.
9 I'd like to assign some variables inside a query that uses CASE statements for it's columns. Not quite sure how to do this, having trouble finding the right syntax.