CHOOSE WHERE ... hundreds of conditions

Is there an elegant way to do this:

SELECT Cols from MyTable WHERE 
zip = 90210 OR
zip = 23310 OR
zip = 74245 OR
zip = 77427 OR
zip = 18817 OR
zip = 94566 OR
zip = 34533 OR
zip = 96322 OR
zip = 34566 OR
zip = 52214 OR
zip = 73455 OR
zip = 52675 OR
zip = 54724 OR
zip = 98566 OR
zip = 92344 OR
zip = 90432 OR
zip = 91532 OR
...

(the zip codes in this post are fictitious and bear no resemblance to real zip codes, living or dead)

+3
source share
5 answers

Yes: try this sql query.

Select cols from MyTable where zip in (90210, 23310, ... etc.)
+28
source

Depends on the definition of "elegant" :)

However, with so many zip codes, I think you also want to manage them in the database.

How do you determine which zip codes should match?

So you can put the zip codes in your own table and do

SELECT cols FROM MyTable, ZipTable WHERE MyTable.zip = ZipTable.zip
+17
source

, :

SELECT cols FROM MyTable WHERE zip IN 
    (SELECT zip FROM ZipTable WHERE condition=true)
+10

- :

  • start transaction;
  • create temporary table if not exists ZIPS(ZIP integer) storage=memory;
  • insert into ZIPS (ZIP) VALUES(...)
  • select COLS from MYTABLE M, ZIPS Z where Z.ZIP = M.ZIP
  • drop table ZIPS ( , )
  • commit, rollback

API- db executemany, insert into TABLE(COLUMNS) VALUES , . ​​ , INT : -)

, SQL (, MySQL), , .

+3

With these many elements, you really need to create a lookup table, especially if you need to regularly review them in other sections of the code. This will encapsulate your code, which will make editing easier if it is used in several functions and improves the aesthetics of reading.

Example: --create table Search and populate the Values ​​column with your set of zip codes in this case

SELECT Cols 
FROM MyTable  
WHERE EXISTS (Select * FROM Lookups WHERE MyTable.zip = Lookups.values)

using join

SELECT DISTINCT Cols
FROM MyTable JOIN
     Lookups ON MyTable.zip = Lookups.values
0
source

All Articles