RMi Flores
RMi Flores

Reputation: 377

How to run SQL queries in a loop

How can I run this SQL query multiple times in a loop, where I replace the word 'pubs' with another word during each iteration. Is there a way to store an array of strings and loop through them?

SELECT * FROM businesses WHERE category='pubs'

Upvotes: 2

Views: 4965

Answers (2)

Karin
Karin

Reputation: 8610

In general, it's usually better performance-wise to do bulk or batch queries than queries in a loop, since you can save round trip calls to the DB.

Consider instead doing something like SELECT * from businesses WHERE category IN ('pubs', ...), or if you plan to iterate over all categories, retrieve all item rows and programmatically use category in the returned models to do what you need to with them.

If you absolutely must use a loop, you can look at the loop documentation.

Upvotes: 5

Rahul
Rahul

Reputation: 77926

You probably don't need a loop to run them rather use a IN clause to include all the possible condition values like

SELECT * FROM businesses WHERE category IN ('pubs','subs','nubs')

Upvotes: 2

Related Questions