skip to Main Content

Is there a way in Postgres to fetch a list of rows having specific IDs from a table, using one query without any subqueries.

Table
id  value
---------
0 | 12
2 | 345
3 | Alan
4 | 0.345
5 | 232333.2

I want fetch rows with IDs 2, 3, and 5 using just one query.

3

Answers


  1. SELECT *
    FROM Table
    WHERE id IN (2, 3, 5);

    Login or Signup to reply.
  2. You should use IN clause

    The IN operator allows you to specify multiple values in a WHERE clause.

    SELECT * FROM Table WHERE id IN (2, 3, 5);
    
    Login or Signup to reply.
  3. You can use the IN operator as shown in previous answers. However if your list of requested IDs can be empty this will not work because IN () is a syntax error.

    If you want to handle the empty list with the same query you can use the ANY function:

    SELECT * FROM "Table"
    WHERE id = ANY(ARRAY[2, 3, 5]::int[])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search