Search code examples
sqlpostgresqlpsycopg2

postgresSQL universal query


Let's suppose we have two queries (I use postgresSQL with psycopg2):

1 -

query= """
SELECT * FROM same_table
"""

2 -

query= """
SELECT * FROM same_table
WHERE id = %(some_id)s
"""

Is it possible to crate a single statement for both situations? To retrieve a specific one row by sending an ID in a variable and to retrieve all rows by sending null, 0, or anything differnt from an integer greater than 0.

A nice solucion would be some kind of if-than structure, but I'm not sure if how this is done in sql.


Solution

  • This would probably work:

    query= """
    SELECT * FROM same_table
    WHERE case when %(some_id)=0 then true else id = %(some_id)s end
    """