Given I have an array containing the numbers 13777xx in an array, how would I generate this query?
Arbitrary numbers
If you have an actual array, just pass the array literal, in the form of:
'{1377776,1377792,1377793}'
For small arrays with just a hand full of values, you can just use the ANY
construct in the join:
SELECT col1, col2
FROM entity
WHERE entityid = ANY ($my_array::int[]);
For string literal you'll need an explicit type cast as demonstrated.
For long arrays, it will be more efficient to unnest the array to a set (derived table) and then join like mu commented:
SELECT col1, col2
FROM unnest(my_array::int[]) ex(entityid)
JOIN entity USING (entityid);
With a matching column name for the unnested numbers you can conveniently use the short USING
clause for the join condition.
Note a subtle difference: The first query implicitely folds duplicates in the input, while the second with the join produces duplicates for duplicates in the input. Your pick.
Alternatively you can also pass individual values to an IN
expression. But that's typically slower. (Again: folds duplicates.) Like:
...
WHERE entityid IN (1377776, 1377792, 1377793);
See:
For repeated operations you might create a VARIADIC
function and pass individual numbers as parameters (or a single array literal, at your choosing). See:
Not so arbitrary numbers
If you actually want to base you query on "the numbers 13777xx", meaning all numbers between 1377700 and 1377799, use generate_series()
instead. Like:
SELECT col1, col2
FROM generate_series(1377700, 1377799) entityid
JOIN entity USING (entityid);
Or, simplest and fastest, adapt the WHERE
clause with a single range predicate:
SELECT col1, col2
FROM entity
WHERE entityid BETWEEN 1377700 AND 1377799;