MySQL
ORACLE
POSTGRESQL
SQL
SQL SERVER

SQL Variable: What It Is and How To Use It

intro

Explore how the SQL variable mechanism can help you write complex SQL statements in MySQL, PostgreSQL, SQL Server, and Oracle.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

Similar to programming, writing complex SQL stored procedures or functions becomes easier when you can store values in local variables. Here is where the SQL variable definition mechanism comes in!

SQL variables can significantly simplify your SQL logic by allowing you to store temporary data in named placeholders. In this article, you will find out what SQL variables are, why they are useful, and how to declare them.

Let’s dive in!

What Is an SQL Variable?

An SQL variable is a placeholder used to store temporary data during the execution of particular SQL statements. Usually, these variables can be used in stored procedures, user-defined SQL functions, dynamic SQL, batches, and scripts.

Just like variables in programming languages, SQL variables are used to store intermediate results, enhance the complexity of procedures, or simplify repetitive tasks. The main benefits of this mechanism are:

  • Enhanced readability: By assigning meaningful names to values, statements become easier to understand.
  • Increased reusability: Reuse a specific value across multiple parts of the statement.
  • Improved performance: Improve execution efficiency by reducing redundancy.

Use Cases of SQL Variables

Below are the most common use cases for declaring a variable in SQL:

  • Parameterized queries: Variables support the creation of dynamic, flexible, and reusable queries. By specifying variables in a query and using them as arguments, you can customize their values at runtime. This makes the resulting data adaptable and responsive to different inputs. The usage of parameterized queries is one of the primary ways to squash SQL injection too because parameterized queries provide the query and the user input to the database separately and not as a whole.
  • Store intermediate results: Variables can hold temporary data or calculation results within a function or stored procedure. That simplifies complex logic and facilitates further processing without recalculating values.
  • Control flow: Variables help you manage the flow of execution in procedural SQL by storing values that can control conditional logic, loops, and decision-making processes.

Declaring a Variable in SQL

Explore how to create and assign SQL variables in the leading database systems. You will also learn when you can define them in each DBMS.

Note that the syntax for declaring and using variables varies between database systems.

MySQL

In MySQL, you can define one or more user-defined variables using the following syntax:

Copy
        
1 SET @var_name_1 = expr_1 [, ..., @var_name_n = expr_n];

The variable name @var_name must start with @ and can include alphanumeric characters, ., _, and $. If you need to use other characters, you may need to quote the variable name as a string or identifier, like @'my-var', @"my-var", or @my-var.

In MySQL, user-defined variables are session-specific, meaning a variable defined by one client cannot be accessed or used by any other client. That also means that these variables are automatically freed when the client session ends.

Here is an example of how you can use them:

Copy
        
1 SET @total = 100; 2 SELECT @total;

MySQL also supports local variables, which are defined using the DECLARE statement within stored procedures and custom SQL functions:

Copy
        
1 DECLARE variable_name datatype [DEFAULT value];

Where:

  • variable_name is the name of the variable you are declaring.
  • datatype is the data type the variable will hold. You can choose any MySQL data type.
  • value is an optional default value assigned to the variable when it gets declared. If no value is specified, the variable will have a value of NULL.

Local variables are only permitted inside the BEGIN ... END statement and can be assigned values using the SET statement:

Copy
        
1 CREATE PROCEDURE incrementNumber(IN number INT) 2 BEGIN 3 DECLARE count INT DEFAULT number; 4 SET count = count + 1; 5 SELECT count; 6 END;

Local variables are restricted to the procedure or function where they are declared, making them ideal for temporary data within complex SQL logic.

PostgreSQL

Variables in PostgreSQL are only supported in PL/pgSQL, the Postgres procedural language. A PL/pgSQL block is defined through this syntax:

Copy
        
1 [ DECLARE declarations ] 2 BEGIN 3 statements 4 END [ label ];

The declarations section after the DECLARE keyword contains a list of variables, each specified in this way:

Copy
        
1 var_name [ CONSTANT ] var_type [ NOT NULL ] [ DEFAULT = value ];

Where:

  • var_name is the name you are giving to the variable.
  • CONSTANT is an optional keyword that, if used, makes the variable's value unchangeable after it is set. This means the variable can be assigned a value only once.
  • var_type is the data type of the variable. You can use any of the PostgreSQL data types.
  • NOT NULL is An optional constraint that ensures the variable cannot hold a NULL value. If the variable is not assigned a value and NOT NULL is specified, an error will occur.
  • DEFAULT value gives an optional value to the variable when it is declared. If no default value is provided, the variable will be initialized to NULL (unless NOT NULL is specified, in which case an error occurs if no default value is set).

SQL Server

In SQL Server, variables are defined through the DECLARE statement as follows:

Copy
        
1 DECLARE @VariableName Type;

Where:

  • @VariableName is the name assigned to the variable. The name must have a single @ as the first character.
  • Type is a system-supplied or user-defined data type.

By default, the variable is given the NULL value.

For example, the following DECLARE statement creates a local variable named @mycounter with an INT data type and NULL value:

Copy
        
1 DECLARE @MyCounter INT;

DECLARE can also be used to create multiple local SQL variables at the same time, as in the example below:

Copy
        
1 DECLARE @FirstName NVARCHAR(30), @MiddleName NVARCHAR(20), @LastName NVARCHAR(30);

This query creates three variables named @FirstName, @MiddleName, and @LastName and gives each of the variable a default value of NULL.

To give an SQL Server variable a value, you can use an assignment after DECLARE:

Copy
        
1 DECLARE @MyCounter INT = 0;

The above line initializes the @MyCounter variable to 0.

Otherwise, you can SET on an already defined SQL variable as follows:

Copy
        
1 SET @MyCounter = 0;

Oracle

PL/SQL—Oracle's procedural extension to standard SQL—supports the use of variables. Once you define an SQL variable in Oracle within a procedural statement, you can use it wherever an expression is valid.

Oracle variables are defined using the DECLARE statement. Below is an example of how to use it:

Copy
        
1 DECLARE 2 v_hiredate DATE; 3 v_location VARCHAR2(15) := 'Paris'; 4 v_deptno NUMBER(2) NOT NULL := 8; 5 c_comm CONSTANT NUMBER := 42;

Variables in DbVisualizer

Declaring variables in SQL is certainly beneficial, but it presents some challenges. The primary issue is that not all databases let you use them, and each database has its own syntax for implementation.

Oftentimes, you want to use variables just like parameterized SQL statements. Well, this is where DbVisualizer variables come into play!

DbVisualizer is a robust database client that supports traditional SQL variables and also provides numerous other features. Among these vast set of capabilities, it allows the definition of custom variables for parameterized queries, as illustrated in this example:

Copy
        
1 SELECT * 2 FROM employees 3 WHERE name LIKE '${First Name || Phil}$' AND age > ${Age || 20}$

The full syntax for declaring DbVisualizer variables is:

Copy
        
1 ${name || value || type || options}$

These variables enable you to create parameterized SQL statements. When executing such a query in DbVisualizer, you will then be prompted to fill in some values for these variables:

Giving the DbVisualizer variables some values
Giving the DbVisualizer variables some values

This feature is particularly useful for running the same SQL query multiple times with different data inputs.

Conclusion

In this guide, you saw what an SQL variable is, when it is useful, and how to declare it in MySQL, PostgreSQL, SQL Server, and Oracle. You now know that SQL variables are a powerful tool to write complex logic in stored procedures, functions, and more.

As shown here, DbVisualizer takes variable management to the next level by supporting parameterized SQL queries. This feature allows you to write a query once and execute it with different variable values to get varying results each time.

DbVisualizer is a fully-featured database client that supports multiple DBMS technologies, offers advanced query optimization capabilities, and can generate ERD-type schemas with a few clicks. Try it for free!

FAQ

Are SQL variables part of the ISO/ANSI SQL standard?

SQL variables are not a formal part of the ISO/ANSI SQL standard. Thus, while several databases give you the ability to define an SQL variable, the standard itself does not mandate their presence or behavior. That is also why popular databases have differences in how they handle variables.

How do you set a primary key on a table variable in SQL Server?

In SQL Server, you can set the primary key on a table variable by specifying it within the declaration of the variable. In particular, you can use the PRIMARY KEY constraint to designate one or more columns as the primary key, as shown in this example:

Copy
        
1 DECLARE @MyTableVariable TABLE ( 2 Id INT PRIMARY KEY, 3 Name NVARCHAR(50) 4 );

The above logic ensures that the Id column uniquely identifies each row. The same approach can be used to add foreign keys. Learn more in our comparison of primary keys vs. foreign keys.

What is the scope of an SQL variable?

The scope of an SQL variable depends on the database management system and the context in which it is defined. Typically, the scope of a variable goes from the point it is declared to the end of the batch or stored procedure it lives in.

How can declaring a variable in SQL improve a statement?

Declaring a variable in SQL can improve a statement by enhancing readability and maintainability. Variables can store intermediate results, making complex queries easier to understand and deal with. Also, they also reduce redundancy by supporting the reuse of values. Additionally, SQL variables simplify maintenance and updates, as changes only need to be made in one place rather than in the entire query.

Do all relational databases support SQL variables?

Since SQL variables are not part of the SQL standard, not all relational databases support them. While most major systems like MySQL, PostgreSQL, and SQL Server do support SQL variables, the implementation details and syntax can vary from database to database. Consult your specific type of DBMS for more details.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

A Complete Guide to the MySQL COUNT Function

author Antonello Zanini tags MySQL 9 min 2024-12-09
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

MySQL Nullable Columns: Everything You Need to Know

author Antonello Zanini tags MySQL 6 min 2024-12-03
title

A Complete Guide to the MySQL GROUP_CONCAT Function

author Antonello Zanini tags Data aggregation MySQL 8 min 2024-12-02
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

MySQL 9.0 and the New EXPLAIN Features

author Lukas Vileikis tags MySQL SQL 9 min 2024-11-27
title

Massive SQL DELETE Operations and Database Purging Explained

author Lukas Vileikis tags DELETE SQL 4 min 2024-11-26
title

MySQL CAST: A Guide to the Data Conversion Function

author Antonello Zanini tags MySQL 3 min 2024-11-25

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗