skip to Main Content

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.

2

Answers


  1. This would probably work:

    query= """
    SELECT * FROM same_table
    WHERE case when %(some_id)=0 then true else id = %(some_id)s end
    """
    
    Login or Signup to reply.
  2. You could try to solve the problem in Python instead of in SQL. A simple approach might look like this:

    query = "SELECT * FROM same_table"
    
    if some_id is not None:
        query += " WHERE id = %(some_id)"
    

    And if you’d prefer to get away from writing SQL by hand entirely, you can look into tools like SQLAlchemy or Peewee, which allow you to write code like this:

    query = SameTable.select()
    
    if some_id is not None:
        query = query.where(SameTable.id == some_id)
    
    for row in query:
        print(row)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search