15

I have a table that has several columns. The value of one column is 0 or 1. I want to write a query that returns "Hello" if the value was 0, or "Bye" if it was 1. What is the appropriate way to write this query?

Chris Cashwell
  • 22,308
  • 13
  • 63
  • 94
Tavousi
  • 14,848
  • 18
  • 51
  • 70

2 Answers2

19

Use a CASE expression

SELECT CASE YourCol
         WHEN 0 THEN 'Hello'
         WHEN 1 THEN 'Bye'
       END AS SomeAlias
FROM   YourTable  
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • Plz help me.If I want to select several column. For example select ID,YourCol,Name.(YourCol is that column that were select case expression). – Tavousi Dec 11 '11 at 15:51
1

If you choose multi/all columns, please try with below:

SELECT Column1, Column2,  -- Put other column name here 
        CASE TargetColumnName
         WHEN 0 THEN 'Hello'
         WHEN 1 THEN 'Bye'
       END AS TargetAliasColumnName
FROM   YourTableName 
Elias Hossain
  • 4,410
  • 1
  • 19
  • 33
  • Is the name "TargetColumnName" an intrinsic name of SQL thus SQL knows that it refers to "Column1, Column2, ..."? – Hans Sep 30 '16 at 20:32
  • You can write your desired column name say your column name is Column2 instead of TargetColumnName - I've written TargetColumnName in my answer because there may have many column name in your SELECT statement and you need to specify your required column name in 'CASE' expression in SQL, hope you've got my point. Thanks – Elias Hossain Oct 09 '16 at 05:19
  • So you are saying "TargetColumnName" is place holder for one of Column1, Column2. I thought you were coding for multiple columns and perform the conditional replacement task for all the selected columns rather than just one. If that is the case, what is the difference between operation on a single column such as shown in the answer by Martin Smith and that on multiple columns as you seem to suggest your code would perform? – Hans Oct 09 '16 at 23:32
  • You may choose multiple columns in `SELECT` statement and can use one column in a `CASE` statement (in my answer), in Martin Smith's answer he used one column in `SELECT` and used the value of that column in `CASE` statement - hope you've got my point, thanks. – Elias Hossain Oct 10 '16 at 04:35