In PostgreSQL I have:
SELECT *
FROM weather_data
WHERE parameter_type = 'TEMPERATURE';
I want to write this as:
WITH ParameterType AS (VALUES ('TEMPERATURE'))
SELECT *
FROM weather_data
WHERE parameter_type = ParameterType;
I get error: "column "parametertype" does not exist"
4
Answers
If you want to select from some values, rather than just creating a table and inserting into it, you can do something like:
This will outputs :
To join this dataset with your current table you can do something like :
With clause is used to define named result sets or CTEs.
In your case, the ParameterType is not accessible in the where clause.
Try something like this.
A CTE works just like a table.
The query below is an equivalent of what you wrote and it should be obvious to you why it will not work (A table is not a valid operand for the
=
operator).The correct approach would of course be:
This works only if
SELECT Column1 FROM SomeOtherTable
is a scalar subquery (i.e. 1 row, 1 column). If you have more than 1 row, use theIN
operator:Back to your query, we want to ideally name the column of your CTE, then use it as I described above:
Note#1: your CTE only has 1 column so naming it is optional; you could also make it work with
SELECT *
instead ofSELECT ParamValue
.Note#2: there are, of course, other ways to achieve the same thing, such as
INNER JOIN
,EXISTS (SELECT ...)
, etc. Such ways could be convenient for a CTE with more than 1 column.You don’t need the
cte
at all: demo at db<>fiddleThis spawns a single-value table the same way and joins it with your table the same way.