Computers & ProgrammingBackend DevelopmentSQL

SQL IF…ELSE Statement

The SQL IFELSE Statement imposes conditions (boolean expression) on the execution of a Transact-SQL statement. The SQL statement(s) that follows an IF keyword is executed if the condition is satisfied (TRUE).

The optional ELSE keyword will execute the SQL statement(s) that follow when the IF condition is not satisfied (FALSE). The IFELSE Statement is generally used in a SQL procedure or trigger.

Syntax

IF (expression)
BEGIN
Sql Code
...
END
ELSE
BEGIN
Sql Code
...
END

Example

IF @quantity > 0
BEGIN
SELECT [Name], [Qty]
FROM INVENTORY
WHERE InvID = @ID
END
ELSE
BEGIN
SELECT 'Not In Stock'
END

If one SQL statement follows the IF or ELSE block, the BEGIN and END keywords are optional.

Leave a Comment

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

Scroll to Top