Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Invalid column when using AS

I have a raw query:

Model::selectRaw(count(column) as alias_name)..
->where('alias_name', '>', $some_value)..

But I get invalid column on the alias name - why?

0 likes
15 replies
Sinnbeck's avatar

You are using it in a where instead of having? I can only guess

If you can show the error and relevant query, I might be more helpful

1 like
Ligonsker's avatar

@Sinnbeck this is the query:

Model::selectRaw('count(end_date) as active, (count(*)-count(end_date) as not_active), country, city')
->whereBetween('end_date', [Carbon::now()->subYear(), Carbon::now()])
->where('active', '>', 0)
->groupBy('country', 'city')
->get()
Sinnbeck's avatar

But as I guessed you are using where on an aggregate which isn't possible. Use having

->having('active', '>', 0)
1 like
Ligonsker's avatar

@Sinnbeck This:

[Microsoft][ODBC Driver 17 for SQL Server]Invalid column name 'active' 
Sinnbeck's avatar

@Ligonsker can you the query after the update? Also it's always a good idea to mention that you are using mssql :)

1 like
Ligonsker's avatar

@Sinnbeck sorry haha yes I always forget to mention that 😅

query is almost same:

Model::selectRaw('count(end_date) as active, (count(*)-count(end_date) as not_active), country, city')
->whereBetween('end_date', [Carbon::now()->subYear(), Carbon::now()])
->having('active', '>', 0)
->groupBy('country', 'city')
->get()
Sinnbeck's avatar

@Ligonsker try replacing ->get() with ->toSql() and dd the result. Post the output here

1 like
Ligonsker's avatar

@Sinnbeck this is the sql query:

select count(end_date) as active, country, city from [table] where [end_date] between ? and ? group by [country], [city] having [active] > ?
Sinnbeck's avatar

@Ligonsker ok. Not sure why it didn't work. Haven't had a chance to test it on sqlsrv yet. Close the thread if it's done :)

1 like
Ligonsker's avatar

@Sinnbeck I might test it as well and see the error it gives me in the MSSMS and if yes I will come back to update if not I will close it, didn't want to close it yet because I thought you might also want to know why it didn't work

Sinnbeck's avatar

@Ligonsker Seem sqlsrv does not like to use the named column. So just use the aggregate query

Model::selectRaw('count(*) as active, (count(*)-count(*) as not_active), country, city')
->whereBetween('end_date', [Carbon::now()->subYear(), Carbon::now()])
->havingRaw('count(* '> 0')
->groupBy('country', 'city')
->get()

Please or to participate in this conversation.