Pete Freitag Pete Freitag

SQL Case Statement


Here's a simple example of a SQL CASE statement for Microsoft SQL Server:

  WHEN (DateAdded IS NULL) THEN 'Unknown'
  WHEN (DateDiff(day, DateAdded, getdate()) = 0) THEN 'Today'
  WHEN (DateDiff(day, DateAdded, getdate()) = 1) THEN 'Yesterday'
  WHEN (DateDiff(day, DateAdded, getdate()) = -1) THEN 'Tomorrow'
  ELSE DATENAME(dw , DateAdded) 
FROM Table

In this CASE statement example we are switching on a column called DateAdded which is a date time field. Using various date functions we are creating a column called Day with values Today, Yesterday, Tomorrow, or the day of the week (eg Sunday).

You can also add a WHERE clause, and select other columns from the query

If you found this handy you might also like my SQL Server Cheat Sheet, enjoy.

Like this? Follow me ↯

SQL Case Statement was first published on October 15, 2008.

If you like reading about sql, case, statement, or sqlserver then you might also like: