T-SQL 101: 99 Applying conditional logic with IF

In general, we try to avoid procedural logic when writing T-SQL. However, it is possible.
The most basic procedural statement is the IF statement. It allows us to apply basic conditional logic. Instead of keywords like CASE that allow you to apply logic to determine values, the IF statement allows you to decide which statements are executed.
IF @Value > 10 PRINT 'Large';
The condition can also include other clauses linked with AND and OR:
IF @Value > 10 AND @Age < 15 PRINT 'Large';
While there are precedence rules, if you need to include combinations of AND and OR, I would suggest always including parentheses:
IF (@Value > 10 OR @Value < 5) AND @Age < 15 PRINT 'Large';
After the condition, there is a single SQL statement. Depending upon the complexity of that statement, and how the developer has used indentation, the logic can get a little messy.
For that reason, I typically use a BEGIN and END wrapper around that statement.
IF @Value > 10
BEGIN
PRINT 'Large';
END;
Clearly that isn’t necessary for a single statement but I prefer it as a pattern primarily because it’s common to add additional statements later.
IF @Value > 10
BEGIN
PRINT 'Large';
SET @Age += 1;
END;
Like in other high-level languages, you can also use an ELSE clause:
IF @Value > 10
PRINT 'Large';
ELSE
PRINT 'Small';
Again, this has a single statement following it, so I also use a BEGIN and END wrapper.
IF @Value > 10
BEGIN
PRINT 'Large';
SET @Age += 1;
END ELSE BEGIN
PRINT 'Small';
END;
No matter whether you like to add the BEGIN and END or not, if you’re using IF and ELSE structures, then you should indent the code for clarity to make it clear that it’s part of this condition.
Learning T-SQL
It’s worth your while becoming proficient in SQL. If you’d like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.
2025-01-26