1

I have a query which works well in psql, but generates an error in my program:

sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
cur.execute(sql)

Any pointers as to why it's not working? Or any suggestions, how I can fix it?

2 Answers 2

5

It is not about PostgreSQL vs MySQL query syntax - this is just syntactically wrong in Python:

>>> sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
  File "<stdin>", line 1
    sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
                                                              ^
SyntaxError: invalid syntax

Put the query into double quotes:

sql = "SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;"
Sign up to request clarification or add additional context in comments.

1 Comment

I feel silly now, totally never thought of it. thanks.
0

The good practice for code strings in Python is the triple quoted string which makes it much clearer and can contain both single and double quotes:

sql = '''
    SELECT id, x, y
    FROM table_name
    WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;
'''

From the manual:

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.