Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Alias Column Name for Use in CASE Statement

Tags:

sql

Is it possible to alias a column name and then use that in a CASE statement? For example,

SELECT col1 as a, CASE WHEN a = 'test' THEN 'yes' END as value FROM table; 

I am trying to alias the column because actually my CASE statement would be generated programmatically, and I want the column that the case statement uses to be specified in the SQL instead of having to pass another parameter to the program.

like image 813
Verhogen Avatar asked Oct 18 '09 00:10

Verhogen


People also ask

How can use column name in case statement in SQL?

SELECT col1 as a, CASE WHEN a = 'test' THEN 'yes' END as value FROM table; I am trying to alias the column because actually my CASE statement would be generated programmatically, and I want the column that the case statement uses to be specified in the SQL instead of having to pass another parameter to the program.

How do you indicate that a column alias should be used?

Column alias is added in the SELECT statement immediately after the column name. Optionally, you can add the keyword AS in between the column name and the column alias to clearly indicate the use of alias. Use column alias if the original column name does not meet your requirements.

Can column alias name be used for WHERE clause in SQL?

Column Alias Column aliases can be used for derived columns. Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.

Can we use the SELECT statement column name alias in HAVING clause?

Column aliases are optional, and each column name in the SELECT clause can have an alias. After you assign an alias to a column, you can use the alias to refer to that column in other clauses.


2 Answers

This:

SELECT col1 as a,        CASE WHEN a = 'test' THEN 'yes' END as value    FROM table; 

...will not work. This will:

SELECT CASE WHEN a = 'test' THEN 'yes' END as value   FROM (SELECT col1 AS a           FROM TABLE) 

Why you wouldn't use:

SELECT t.col1 as a,        CASE WHEN t.col1 = 'test' THEN 'yes' END as value    FROM TABLE t; 

...I don't know.

like image 104
OMG Ponies Avatar answered Sep 19 '22 13:09

OMG Ponies


I think that MySql and MsSql won't allow this because they will try to find all columns in the CASE clause as columns of the tables in the WHERE clause.

I don't know what DBMS you are talking about, but I guess you could do something like this in any DBMS:

SELECT *, CASE WHEN a = 'test' THEN 'yes' END as value FROM (    SELECT col1 as a FROM table ) q 
like image 38
eKek0 Avatar answered Sep 20 '22 13:09

eKek0