Using CASE statements

Like any other programming language, Teradata SQL provides if-then-else logic using the CASE statement. It helps in fetching alternate values for a column based on the condition specified in the expression. If any one of the values gets qualified as TRUE, its value gets captured and the counter goes on until all the rows have been processed.

Every CASE statement needs to have a pair of WHEN and THEN statements and to be closed using an END statement. 

The syntax of CASE is as follows:

The syntax of case statement

Let's put this into a code statement as follows:

/*CASE SELECT*/
SELECT
EMP_name, Month,
CASE WHEN MONTH = 'JUNE' THEN 'yes' ELSE NULL END AS SUMMER
FROM Table_CASE

Let's understand this by means of a flow chart:

Decoding the statement:

  1. The CASE 1 statement checks each row to see if the conditional statement is met.
  2. For any given row for CASE 1, if that conditional statement is true, the counter for the true condition is increased or the corresponding value gets stored. 
  3. In any row for which the conditional statement is false, nothing happens in that row, and the false statement is executed.
  4. If the query has other CASEs involved, the flow will continue with another CASE statement.
  5. Rows that don't qualify are executed by the default CASE statement.

In this recipe, we will write a CASE statement identifying customers who have pre-paid or post-paid connection.