Oracle 10.2 SQL poses a challenge when attempting to use a 'case expression column' within the WHERE clause. The error "ORA-00904: "%s: invalid identifier" is encountered due to the logical order of SQL statement processing.
SQL statements are processed in the following sequence:
In the WHERE clause of the original query:
SELECT ename , job , CASE deptno WHEN 10 THEN 'ACCOUNTS' WHEN 20 THEN 'SALES' ELSE 'UNKNOWN' END AS department FROM emp WHERE department = 'SALES'
The 'department' column, generated by the CASE expression, does not exist yet during the WHERE clause evaluation. Hence, the WHERE clause cannot use it for comparison.
To overcome this limitation, enclose the query within a subquery:
SELECT * FROM ( SELECT ename , job , CASE deptno WHEN 10 THEN 'ACCOUNTS' WHEN 20 THEN 'SALES' ELSE 'UNKNOWN' END AS department FROM emp ) tmp WHERE department = 'SALES' ;
Alternatively, duplicate the CASE expression in the WHERE clause:
SELECT ename , job , CASE deptno WHEN 10 THEN 'ACCOUNTS' WHEN 20 THEN 'SALES' ELSE 'UNKNOWN' END AS department FROM emp WHERE CASE deptno WHEN 10 THEN 'ACCOUNTS' WHEN 20 THEN 'SALES' ELSE 'UNKNOWN' END = 'SALES' ;
In cases where the WHERE clause condition directly matches a specific department number, a simplified option is possible:
SELECT ename , job , 'SALES' AS department FROM emp WHERE deptno = 20 ;
The above is the detailed content of How Can I Use a CASE Expression Column in an Oracle 10.2 WHERE Clause?. For more information, please follow other related articles on the PHP Chinese website!