What is the Difference Between If and When?
🆚 Go to Comparative Table 🆚The main difference between "if" and "when" lies in the level of certainty they convey about a future situation or condition. Here are the key distinctions:
- If:
- Introduces a possible or unreal situation or condition.
- Used when there is a chance or possibility that something will occur, but it is not certain.
- Can be used to introduce conditions, showing that an action or event happens when another action is fulfilled.
- When:
- Refers to the time of a future situation or condition that we are certain of.
- Used to express certain events in the future, indicating that we are sure these events will occur.
- Can be used interchangeably with "if" when talking about general things, where "if" means "whenever".
Examples:
- If you lose your student ID card, you won't be able to access the library. (There is a possibility of losing the card, but it is not certain.)
- When you finish your exams, you can relax and enjoy your vacation. (It is certain that you will finish your exams and take a vacation.)
Remember that the choice between "if" and "when" depends on the speaker's perspective and the level of certainty associated with the event or situation being discussed.
Comparative Table: If vs When
The difference between "IF" and "WHEN" statements in SQL lies in their usage and syntax. Here is a table comparing the two:
IF | WHEN |
---|---|
Controls the flow and decides what has to be evaluated next based on the condition. | Part of the CASE statement, which is a function that takes an expression and a list of conditions to check. |
In the context of creating a new column in a table based on certain conditions, you would typically use the CASE statement with the WHEN clause. For example:
SELECT *,
CASE
WHEN number > 40 THEN 'high'
WHEN number BETWEEN 30 AND 40 THEN 'medium'
ELSE 'low'
END AS newColumn
FROM myTable
This code snippet uses the CASE statement with the WHEN clause to check the value in the "number" column and assign a corresponding value to the new "newColumn". The IF statement is not used for this purpose, as it is designed for control flow and deciding the sequence of execution based on conditions. Instead, the CASE statement with the WHEN clause is more appropriate for this kind of conditional expression.