Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use "on-the-fly" column names in SQL WHERE clasue?

Tags:

sql

sql-server

I'm a bit rusty with my SQL.

I thought I could do something like this:

SELECT *, DATEADD(d, 1 ,dStartDateTime) dCloseDate
FROM EventItem 
WHERE dCloseDate > '1990-01-01 07:00:00.000'

But when I do that I get the error:

Invalid column name 'dCloseDate'.

Anyone know a way around that? I just want to do it to make my code more readable/maintainable.

Any advice as to why I shouldn't do it would also be appreciated :)

like image 802
Ev. Avatar asked Dec 10 '25 04:12

Ev.


1 Answers

You can not use “on-the-fly” column names in SQL WHERE clause. (You can in the ORDER BY clause.) You have to subquery it, or repeat the expression

SELECT * FROM (
SELECT *, DATEADD(d, 1 ,dStartDateTime) dCloseDate
FROM EventItem
) SUBQ
WHERE dCloseDate > '1990-01-01 07:00:00.000'

-or-

SELECT *, DATEADD(d, 1 ,dStartDateTime) dCloseDate
FROM EventItem 
WHERE DATEADD(d, 1 ,dStartDateTime) > '1990-01-01 07:00:00.000'

Why you shouldn't do it?

Having said that, you are performing a function against your column dStartDateTime which requires a table scan. Always perform functions on the other side, so that the value found can be tested against an index on dStartDateTime (datetime column).

SELECT *, DATEADD(d, 1 ,dStartDateTime) dCloseDate
FROM EventItem 
WHERE dStartDateTime > DATEADD(d, -1 ,'1990-01-01 07:00:00.000')
like image 96
RichardTheKiwi Avatar answered Dec 12 '25 19:12

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!