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

By | 13. 1. 2020

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”)



(!!!) 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;

   ...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
     ...a statement to be executed if the condition value is TRUE
     ...a statement to be executed if the condition is FALSE

(!!!) “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 Jan Zedníček

My name is Jan Zedníček and I work as a freelancer. I have been working as a freelancer for many companies for more than 5 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym and I enjoy tasting of best quality rums. I am trying to summarize all my knowledge on this website not to forget them (because of the rum effect, you know =) and to put them forward to anyone. Don´t worry about asking for help or writing some comments.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.