I am trying to filter rows from my Postgres database with below query. Everything works fine but when I try to check if latesttask
column is null or has some value then it shows error:
error: column "latesttask" does not exist
SELECT *,
(
SELECT
JSON_BUILD_OBJECT(
'id', taskhistories.id, 'task', taskhistories.task,
'taskname', t.name, 'project', taskhistories.project,
'projectname', p.name, 'started_at',
taskhistories.started_at, 'stopped_at',
taskhistories.stopped_at
)
FROM
tasks AS t,
projects AS p,
latesttasks,
taskhistories
WHERE
taskhistories.user = users.id
AND latesttasks.task = t.id
AND latesttasks.project = p.id
AND taskhistories.id = latesttasks.taskhistory
AND (
LOWER(t.name) LIKE '%we%'
OR LOWER(p.name) LIKE '%we%'
)
) as latestttask
FROM
users
WHERE
(
latesttask IS NULL
AND (
LOWER(name) LIKE '%we%'
OR LOWER(email) LIKE '%we%'
)
OR latesttask IS NOT NULL
)
2
Answers
One "t" to many in your column alias
latestttask
.But, more importantly, you cannot reference output column names in the
WHERE
clause anyway. There would have to be a columnusers.latesttask
to make theWHERE
clause work.This would be a working equivalent with a
LEFT JOIN
to aLATERAL
subquery:Please try with…