Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a long SQL query inside a variable

Tags:

python

pep8

Following the PEP8 guidelines, what would be the best practice to format a very long sql wistatement into a variable?

An example bellow, of how im splitting the variable:

var= "some value"
query = "select a,b,c,d,e,f,g,h from a_very_long_tablename" +\
"where a_very_long_sql_statement='is_really_very_long' " +\
"or a_very_long_sql_statement='" + var + "' order by a"
like image 844
thclpr Avatar asked Mar 14 '26 12:03

thclpr


1 Answers

Use a triple quoted string:

query= """\
select a,b,c,d,e,f,g,h from a_very_long_tablename
where a_very_long_sql_statement='is_really_very_long'
or a_very_long_sql_statement='is_really_really_very_long'
"""

SQL is a whitespace-agnostic language, you can use newlines as well as spaces to delimit. The initial backslash escapes the first newline; it's a personal preference but not needed.

If you really don't want the newlines, put parenthesis around your string; no need to use + signs then as python will make it one long string for you:

query = (
    "select a,b,c,d,e,f,g,h from a_very_long_tablename "
    "where a_very_long_sql_statement='is_really_very_long' "
    "or a_very_long_sql_statement='is_really_really_very_long'")
like image 90
Martijn Pieters Avatar answered Mar 16 '26 02:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!