Search code examples
pythonpython-2.7pep8

How to format long SQL queries according to PEP8


According to PEP 8 (Maximum Line Length), a line should never be longer than 79 characters.

When I try to split up queries, however, I run into issues like continuation characters, and invalid tokens, etc.

For example, what would be the best way to format this query, according to PEP8?

cursor.execute("SELECT pivot_id FROM aud_qty WHERE hshake1 is NULL AND ((strftime('%s', DATETIME('now')) - strftime('%s', sent_to_pivot)) / (60)) > 30;")

Solution

  • What about

    cursor.execute("""SELECT pivot_id
                        FROM aud_qty
                       WHERE hshake1 is NULL
                         AND ((strftime('%s', DATETIME('now')) -
                             strftime('%s', sent_to_pivot)) / (60)) > 30;
                   """)
    

    ? Using """ or ''' you get the same behaviour as a very long string but you can use newlines just fine. And your database won't mind them either.