Need help with this sql query for Postgres DB for a Python flask application
I think there are several problems with your method. The first question would be: do you only want to return book_id for books that have a review? In your code:
book_details = db.execute(&quot;SELECT * FROM books WHERE isbn=:g&quot;, {&quot;g&quot;: isbn_result_isbn}).fetchone()

If not mistaken, book_details is a tuple like:
(col1, col2, ...)

Second, why bother looking for the book_id in book_reviews if you already know what it is?
If you want to return the book_id for a particular ISBN, then:
book_id = db.execute(&quot;SELECT book_id FROM books WHERE isbn=:g&quot;, {&quot;g&quot;: isbn_result_isbn}).fetchone()[0]

is sufficient. If you want to return the book_id only if it has been reviewed:
book_id = db.execute(&quot;SELECT book_id FROM books b WHERE isbn=:g and exists (select 1 from book_reviews r WHERE r.book_id=b.book_id)&quot;, {&quot;g&quot;: isbn_result_isbn}).fetchone()[0]

One of the really nice things about python is multiline strings, so you could write it like:
sql = &quot;&quot;&quot;SELECT book_id 
         FROM books b 
         WHERE isbn=:g
           AND EXISTS (
               SELECT 1 
               FROM book_reviews r 
               WHERE r.book_id=b.book_id
         )&quot;&quot;&quot;
book_id = db.execute(sql, {&quot;g&quot;: isbn_result_isbn}).fetchone()[0]