I have a SQL query where the list of strings is repeated twice: ('foo', 'bar', 'baz', 'bletch')
. What is the most maintainable method to avoid such repetition and make this code more DRY?
I am not optimizing query performance, only maintainability.
select
*
from
gizmo_details
where
_gizmo_name in ('foo', 'bar', 'baz', 'bletch')
or gizmo_id in
(select id from gizmos where
gizmo_name in ('foo', 'bar', 'baz', 'bletch'));
3
Answers
You can move that to an array literal in a single-row subquery and re-use its name: demo
To hide it away completely, you can save that to a temp table, constant-returning function or a custom variable, then join/read that:
Psql
also lets youset
it as its own variable:Using a CTE:
Unfortunately ISO SQL’s
VALUES()
table-constructor is painfully verbose compared to a Postgres array literal.An alternative to using
VALUES()
is a good ol’ fashionedUNION
:With a CTE it would look like this