Skip to content
Advertisement

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'

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement