SQL Use alias in Where statement

Viewed 92322

I wounder how I could use an alias in a where statement.

Example :

SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
WHERE Col1 = 'MySearch'

I use MSSQL 2005

10 Answers

Not possible, but you can do the following:

SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
WHERE SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'

No subqueries or hacks required

Use a subquery:

SELECT * 
FROM 
  (SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 FROM MyTable)
WHERE Col1 = 'MySearch'
SELECT * FROM (
  SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
  FROM MyTable
)
WHERE Col1 = 'MySearch'

(I know this works in Oracle, I believe it is standard SQL and would work in MSSQL.)

You can do this:

SELECT Col1
FROM ( SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 ) AS x
WHERE Col1 = 'MySearch'

With PostgreSQL 9.3+ OR Oracle 12c, there is now lateral join that allows creating an alias.

Lateral joins are joints inside witch you can reference preceding tables.

SELECT col1, col2,col3
FROM MyTable m
JOIN LATERAL (
    SELECT SUBSTRING(m.Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1 
) x ON true
WHERE Col1 = 'MySearch'

With this syntax, you don't have to use '*' that can be non-performing or recopy all the columns.

I think it is not possible, but maybe you can take a look on Common Table Expressions over SQL 2005

Like this:

WITH MyCTE( Col1) AS
(
SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
)
SELECT *
FROM MyCTE
WHERE Col1 = 'MySearch'

use a view or a derived table.

Using a derived table, your example would look like:

select col1 
from 
(SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable) 
where col1='Mysearch'

Actually, using alias won't make your query any faster as SQL optimizer is not as dumb as you think, so I'd just repeat the SUBSTRING expression again.

The answer is you can't - you can do this

SELECT 
    SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM 
    MyTable
WHERE 
    SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'
Related