Ask the Expert

Referencing a renamed column on SELECT clause in SQL

I am beginning to use SQL and wondered if this is possible. How can I define a column in the SELECT statement and use it in the WHERE:
SELECT name, CASE WHEN type = 1 THEN 'A' WHEN type = 2 THEN 'B' ELSE 'C' END AS typeflag FROM custtable WHERE typeflag = 'B'

I know this can be done by doing "where type = 2" but I can't give you an easier example. When I try this, SQL says "typeflag is not a column in the table."

Unfortunately, the SQL Standard does not allow a renamed column (typeflag in your example) on the SELECT clause to be referenced on a different part of the SQL statement such as the WHERE clause. That's why the error message states that typeflag is not found because the WHERE clause doesn't have access to the renamed column name on the SELECT clause.

To do this on a single statement, you can use an SQL common table expression. I find table expressions helpful in breaking a complex SQL statement into smaller, simpler components. Here's an example of implementing your statement with a common table expression:

WITH custexp AS (SELECT name, CASE WHEN type = 1 THEN 'A' WHEN type = 2 THEN 'B' ELSE 'C' END AS typeflag FROM custtable) SELECT name, typeflag FROM custexp WHERE typeflag='B'

This was first published in October 2008

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: