Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Possible to use input array in where clause? [duplicate]

Tags:

sql

Possible Duplicate:
Parameterizing an SQL IN clause?

Suppose I had a table of schools which school_name, school_enrolment

As input to my program, someone types a list of schools that they would like to see the enrolment for. Instead of generating an sql query like:

SELECT * FROM school_table
WHERE
school_name = 'program_input_1' or school_name = 'program_input_2' or school_name = 'program_input_3'

is it possible or straightforward to do something like

SELECT * from school_table
WHERE
school name in [array of program inputs]

as a much cleaner way of writing this?

like image 233
user1771624 Avatar asked Nov 16 '12 21:11

user1771624


People also ask

Can we use array in WHERE clause in SQL?

We can pass an array with the help of where IN clause.

Can you use WHERE clause twice in SQL?

But yes, you can use two WHERE.

Can we have WHERE and having in same query?

You can create a WHERE clause and HAVING clause involving the same column. To do so, you must add the column twice to the Criteria pane, then specify one instance as part of the HAVING clause and the other instance as part of the WHERE clause.

Can we use SELECT in WHERE clause?

You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.


2 Answers

Yes, this is what IN is for:

SELECT col1, col2, ..., coln
FROM school_table
WHERE school_name IN ('program_input_1', 'program_input_2', 'program_input_3')
like image 85
Mark Byers Avatar answered Nov 03 '22 04:11

Mark Byers


You can use the IN(...) clause:

WHERE School_name in ('school 1','school 2')

In terms of passing an array, it depends on the programming language you are using to generate the SQL.

You would have to write a custom function that loops over the array, dynamically generating the IN clause

like image 23
Lock Avatar answered Nov 03 '22 03:11

Lock