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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With