2

I have to perfrom a lot of queries where the same value is being reused. I thought of something like:

varName = 'value';
select * from sometable t where
 t.field1 = varName 
 or t.field2 = varName;

How can this be done with PostgreSQL 12?

I tried a lot of stuff I found, but nothing seems to work.

3
  • What client application or programming library do you use to run the query? Commented Dec 11, 2020 at 11:37
  • plain simple sql, but I found a solution now by experimenting Commented Dec 11, 2020 at 11:45
  • 2
    Write an answer then, please Commented Dec 11, 2020 at 11:49

2 Answers 2

1

I found a solution meanwhile

with varName as (select 'value'::text) 
select * from sometable t where
 t.field1 = (select * from varName)
 or t.field2 = (select * from varName);
Sign up to request clarification or add additional context in comments.

5 Comments

alternatively you can use WITH varname ( VALUES ('value1'),('value2'),...) .... If you're interested, I can add another answer
@JimJones I tried this, but this did not work out
I just added an answer to make my point clearer
@JimJones ok, it turned out that I missed the correct syntax. yields the same result.
It indeed does. The only difference is that using this other approach you avoid the multiple subselects and you're able to have multiple values inside your variable. +1 and cheers
0

Alternatively you can use VALUES inside of your CTE. This will enable you to have multiple values in the same "variable".

Data Sample:

CREATE TABLE t (c1 int, c2 text);
INSERT INTO t VALUES (42,'foo'),(1,'xpto');

Query

WITH j (var) AS (VALUES ('foo'),('bar')) 
SELECT t.c1,j.var FROM t
JOIN j ON j.var = t.c2;

 c1 | var 
----+-----
 42 | foo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.