0

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 )

asked Feb 7, 2022 at 12:44
7
  • 1
    just don't add the where clause. Commented Feb 7, 2022 at 12:46
  • How about dropping the whole "WHERE ..." part altogether? Commented Feb 7, 2022 at 12:46
  • sorry can you show me ? I need to have the same single function for both cases, if I drop it how can specify for the case of a,b,c only ? thanks. Commented Feb 7, 2022 at 12:47
  • Does this answer your question? Creating a dynamic SQL Query from Python Commented Feb 7, 2022 at 12:48
  • @SembeiNorimaki so how can I satisfy both cases? like a,b,c or ALL in the same function ? Commented Feb 7, 2022 at 12:49

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

Comments

1

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}"
answered Feb 7, 2022 at 12:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.