Sorry if this is basic. I have a function that get as an argument one of these 2 :
subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these
So in my function I need to query according to subjects argument
def function (subjects):
query = ('''
SELECT date_num, subject, in_col
FROM base
WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?
''').format(subjects=subjects)
so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?
Could I send * instead ? like subjects[*] ?
(I do turn the ['a','b'] into ('a','b') in my code )
2 Answers 2
subjects = ['ALL']
# subjects = ['A', 'B']
where_clause = f"WHERE subject in {tuple(subjects)}" if subjects[0] != "ALL" else ""
query = f'''SELECT date_num, subject, in_col FROM base {where_clause}'''
Try uncommenting the second line to check how the query modifies
answered Feb 7, 2022 at 12:53
John Giorgio
6591 gold badge4 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Create a generic query and add the where clause if needed
query = "SELECT date_num, subject, in_col FROM base"
if subjects[0] != "ALL":
query += f" WHERE subject in {subjects}"
Comments
default
whereclause.