0

So I have a simple table of towns with Finnish and Swedish names:

CREATE TABLE town (id SERIAL PRIMARY KEY, name_fi TEXT, name_sv TEXT);

And I need to check if a particular town exists. It's rather easy:

cursor.execute(
    "SELECT EXISTS ( SELECT 1 FROM town WHERE name_fi=%s OR name_sv=%s )",
    (town, town)
)
result = cursor.fetchone()  # True/False

But now I need to do this for multiple towns to make sure they all exist:

for town in towns:
    # Code for one town from above
    if result is False:
        return False
return True

Is there a way to do this with one query instead of using a Python for loop?

Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119

1 Answers1

0

Pass the towns as a list:

cities = ['Paris', 'London']
template = ','.join(['%s'] * len(cities))

Join and aggregate as necessary:

query = '''
    select bool_and(name_fi is not null or name_sv is not null)
    from
        town
        right join
        (values {}) s (name) on name in (name_fi, name_sv)
'''.format(template)

print (cursor.mogrify(query, [tuple((city,)) for city in cities]).decode('utf8'))
cursor.execute(query, [tuple((city,)) for city in cities])

The result is either True or False

print cursor.fetchone()[0]

Output:

select bool_and(name_fi is not null or name_sv is not null)
from
    town
    right join
    (values ('Paris'),('London')) s (name) on name in (name_fi, name_sv)

True

For the Python part check this answer

Community
  • 1
  • 1
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260