Explain Codes LogoExplain Codes Logo

How do I declare and assign a variable on a single line in SQL

sql
best-practices
data-type
variable-declaration
Nikita BarsukovbyNikita Barsukov·Feb 12, 2025
TLDR

Declare and set a SQL variable inline with the following syntax:

DECLARE @MyVar INT = 10;

Here, @MyVar as an INT type, is declared and subsequently initialized with the value 10.

Tackling string assignments

For string variables, make sure to enclose your assigned value within single quotes:

DECLARE @Greeting NVARCHAR(100) = 'Hello, world!';

Need a single quote inside your string? Use two single quotes to escape:

DECLARE @Phrase NVARCHAR(100) = 'He said, ''Hello, world!''';

Understanding SQL versions

The facility to declare and assign a variable inline is provided in SQL Server 2008 and later versions. For older versions like SQL Server 2005, first declare, and then set:

DECLARE @LegacyLang INT; SET @LegacyLang = 10; -- Like putting on socks before shoes!

Remember that syntax differences might exist across SQL dialects, such as MySQL or PostgreSQL.

Alternative approaches to assignment

While = is routinely used for inline declaration and assignments in T-SQL, there are other options depending on the context:

  1. Use the SET command to assign a value to a variable after its declaration:
SET @MyVar = 10; -- Old school, still cool...
  1. The SELECT clause is super handy when you need to assign a value from a returned result:
SELECT @MyVar = COUNT(*) FROM Users; -- Counting users like sheep...
  1. In case you wish to assign multiple variables in one go:
SELECT @Var1 = Column1, @Var2 = Column2 FROM MyTable; -- Two birds, one stone!

Handling edge cases

Dealing with potential NULLs and defaults could be a decisive factor:

  • You may want to assign a default value if a query could return NULL:
DECLARE @Count INT = ISNULL((SELECT COUNT(*) FROM Users WHERE IsActive = 1), 0); -- Null ghosts don't count!
  • To handle multiple potential NULL values, use COALESCE:
DECLARE @Name NVARCHAR(50) = COALESCE(@FirstName, @LastName, 'Unknown'); -- The SQL equivalent of 'finders keepers'!

Your guide to efficiency

Programming is as much an art as it is science. Make informed decisions to stay efficient.

  • Inline assignments are perfect when you need short, readable code.
  • Use distinct lines for complex logic or multiple assignments.
  • Inline declarations help avoid unnecessary code clutter, reducing maintenance overhead.

Common pitfalls

Starting with string variables, beware of these common slip-ups:

  1. Forgetting the escape sequence leads to syntax errors: 'John said ''hello'' to Emily'.
  2. Confusing single quotes for delimiters with backticks or double quotes, which qualify identifiers in certain SQL dialects.
  3. Overlooking data type sizes, leading to truncated data and error messages.

Embracing best practices

A few best practices can make your SQL journey a lot smoother:

  • Always initialize variables to avert surprises from NULL values.
  • Sprinkle some comments for enhanced readability, especially when escaping characters.
  • Rely on documentation and community resources to stay updated on new features and best practices.