SQL IF THEN ELSE Command – Do Not Mix Up With CASE

T-SQL command IF is used to control flow of code mainly in operations where we somehow influence db (DDL, DML operations) – for example procedures. You can mix it up with CASE command quite simply. The common mistake is that we try to push sql IF into SELECT clause.

Query in which IF is used in SELECT command will definitely not work (“Incorrect syntax near the keyword IF/THEN”)

SELECT IF 1=1 THEN 'Hi'

SQL IF

IF cannot be inserted into SELECT clause. We use CASE command for this (more in article on CASE)

IF Command Syntax

We start with IF command followed by condition definition. In case when the condition is True command following OF will commence. If not ELSE command will commence.

IF condition
   ...a statement to be executed if the condition value is TRUE;

ELSE
   ...a statement to be executed if the condition is FALSE;

This syntax will work but it is more optimal to limit individual commands using BEGIN END clause

IF condition
  BEGIN
     ...a statement to be executed if the condition value is TRUE
  END;
ELSE
  BEGIN
     ...a statement to be executed if the condition is FALSE
  END;

“THEN” is not used in IF command. Command cannot operate even with ELSEIF. If we would want to test more requirements we would need to branch ot use multiple IFs one after another.

Rate this post
Category: SQL Commands

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *