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
This would probably work:
You could try to solve the problem in Python instead of in SQL. A simple approach might look like this:
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: