The "IF" statement is not used in a "SELECT" statement. Instead, the "CASE" statement can be used to determine the output value depending on the values of a column.
The syntax for using "CASE" statement in a "SELECT" statement is as follows:
SELECT column1, column2,
CASE
WHEN condition1 THEN output_value1
WHEN condition2 THEN output_value2
ELSE default_output_value
END as output_column
FROM table_name;
Here, "column1" and "column2" are the columns in the table "tablename". "condition1" and "condition2" are the conditions that are evaluated for each row in the table. If "condition1" is true for a row, "outputvalue1" is returned for the "outputcolumn" for that row. Similarly, if "condition2" is true, "outputvalue2" is returned for the "outputcolumn". If none of the conditions are true, "defaultoutputvalue" is returned for the "outputcolumn".
For example, suppose we have a table "students" with columns "name" and "grade". Now, we want to create a column "result" which indicates whether the student has passed or failed based on their grade. We can use the following query:
SELECT name, grade,
CASE
WHEN grade >= 60 THEN 'Pass'
ELSE 'Fail'
END as result
FROM students;
In this query, if the grade is greater than or equal to 60, "Pass" is returned for the "result" column, otherwise "Fail" is returned.
Asked: 2022-12-27 11:00:00 +0000
Seen: 9 times
Last updated: Feb 06 '23