Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I select a column based on condition?

I have a variable called @status which I set before this select statement:

Select ordr_num as num, ordr_date as date, ordr_ship_with as shipwith From order where ordr_num = @ordrNum 

I only want to select ordr_ship_with column if @status <> 'Cancelled', otherwise I want to select null for shipwith. How do I accomplish this?

like image 717
Riz Avatar asked Sep 02 '09 15:09

Riz


People also ask

How do I select data based on a condition in SQL?

Use WHERE Clause to Conditionally Select Rows in SQL SELECT Statement for MySQL. The WHERE clause indicates the condition or conditions that rows must satisfy to be selected. The WHERE condition is an expression that evaluates to true for each row to be selected.

How do I select multiple columns based on condition in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.

How do I select a specific column?

Select the letter at the top to select the entire column. Or click on any cell in the column and then press Ctrl + Space.


2 Answers

SELECT ordr_num as num, ordr_date as date,      CASE WHEN @status<>'Cancelled' THEN ordr_ship_with ELSE NULL END as shipwith  FROM order  WHERE ordr_num = @ordrNum 
like image 99
Joel Coehoorn Avatar answered Oct 17 '22 01:10

Joel Coehoorn


Try this out

Select      ordr_num as num,      ordr_date as date,      CASE          WHEN @Status <> 'Cancelled' THEN ordr_ship_with          ELSE NULL END     as shipwith  From order  where ordr_num = @ordrNum 

Although I have a feeling that you STATUS is an actual column in the Order table. In that case, do this:

Select      ordr_num as num,      ordr_date as date,      CASE          WHEN Status <> 'Cancelled' THEN ordr_ship_with          ELSE NULL END     as shipwith  From order  where ordr_num = @ordrNum 
like image 31
Raj More Avatar answered Oct 17 '22 01:10

Raj More