Querying in Python, SQLite 2.6.0, OperationalError: near "(": syntax error

54 views Asked by At

I'm trying to query a table that will answer the following question, but I don't understand what the error is in my code. I am new to querying so there's proabbly something simple that I'm missing.

screenshot of error received

print('Q1: Find the name of the sailor who reserved all boats')
print('Your answer should include (sname)')

answer = "SELECT S.sname FROM Sailor S WHERE NOT EXISTS((SELECT B.bid FROM Boat B) EXCEPT (SELECT R.bid FROM Reserve R WHERE R.sid = S.sid))"

t = cur.execute(answer)
names = list(map(lambda x: x[0], t.description))
print(names)
print('--------------------')
for row in t : print(row)
print('--------------------')

I tried messing with the parantheses pointed out by the debugger but the error persists in that same line of code. I was expecting a table of sailor names that answers the question, or an empty table.

Following is the preceding code:

import sqlite3
import os.path

print('SQLite version:')                           
print(sqlite3.version)                            
print('Loading the Database')                      
con = sqlite3.connect('hw10.db')                   
cur = con.cursor()                                 
print('Success!')
print('Print the Whole Dataset:\n')


# query that selects all records from the Sailor table
t = cur.execute('SELECT * FROM Sailor')           
names = list(map(lambda x: x[0], t.description))   
print(names)                                       
print('--------------------')                                                              
for row in t : print(row)                          
print('--------------------\n\n')

t = cur.execute('SELECT * FROM Boat')              
names = list(map(lambda x: x[0], t.description))
print(names)
print('--------------------')
for row in t: print(row)
print('--------------------\n\n')

t = cur.execute('SELECT * FROM Reserve')            
names = list(map(lambda x: x[0], t.description))     
print(names)
print('--------------------')
for row in t: print(row)
print('--------------------')

Image of output: enter image description here

1

There are 1 answers

0
Error_2646 On

The classical way to do this is well covered in that article. But I think this is a little more intuitive.

Basically get a result of the sailors and the number of unique boat ids they've reserved. If that count is ever equal to the total count of unique boats you know that sailor reserved all of them.

with distinct_counts_of_boat_reservations as (
    select 
          s.name,
          count(distinct b.bid) as count_distinct_bid
     from sailor s
    inner
     join reserve r
       on s.sid = r.sid
    inner
     join boat b
       on r.bid = b.bid
    group
       by s.name)
select distinct
       name
  from distinct_counts_of_boat_reservations 
 where count_distinct_bid = (
         select count(distinct bid) 
           from boat)