Skip to content
Advertisement

Aggregate function not accepted inside WHERE clause

I have the following command.

With this PostgreSQL schema.

After adding AND day_of_week=3 to WHERE I get the following error.

Why cannot I restrict this column?

Advertisement

Answer

You cannot use a derived column in a where clause. A simple solution is a lateral join:

Some advice:

  • Do not use NATURAL JOIN. There is nothing “natural” about it, because it does not recognize properly declared foreign key relationships. And it is very highly prone to error. And it makes the code unreadable to others (and often your future self) because the JOIN criteria are not explicitly stated.
  • Use table aliases.
  • Qualify all column references in the query.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement