THEN
THEN in SQL is a clause utilized within the CASE statement. It dictates the output value or operation to be executed if the preceding WHEN condition is met. It forms an essential part of the CASE expression, allowing users to perform conditional logic in SQL queries.
Example
Output
Explanation
The CASE
statement is used to perform conditions in SQL. The THEN
keyword acts as the outcome when the condition in the WHEN
clause is met. In the given code, the CASE
statement checks the price
column, if the price is greater than 200 it displays ‘Expensive’, otherwise it displays ‘Cheap’. The result is a new column named Price_Category
with the price categories.
Example
Output
Explanation
In the example provided, an integer variable (@Num) is declared and assigned the value of 10. The IF statement checks if the value of @Num is greater than 5. If the condition is met (which it is, because 10 is greater than 5), then it executes the statement within the BEGIN and END block after the IF clause, printing the message “The condition is met.”. If the condition is not met, then it executes the block after ELSE, printing “The condition is not met.” (This block is not executed in our example). The THEN keyword is implicit in SQL Server and is not explicitly written in the statement.
Example
Output
Explanation
In the given SQL statement, a CASE
function is being used to create a new column department_status
. If the department_id
for a particular employee is NULL
, the department_status
is set as No department
. If the department_id
is not NULL
, the department_status
is set as Has department
.
Example
Output
Explanation
The CASE
function in SQL performs a conditional logic in a SQL query. The THEN
keyword plays a crucial role in this function where the output is defined based on the conditions. In this example, the CASE
statement checks each row to see if the ‘type’ column corresponds to ‘dog’ or ‘cat’. If it’s ‘dog’, then ‘Canine’ is returned, if it’s ‘cat’, then ‘Feline’ is returned. If the ‘type’ column neither corresponds to ‘dog’ nor ‘cat’, ‘Other’ is returned. The new value is returned in a column named ‘Animal_Class’.