0

So far I have copied and pasted from SQL to Python simple codes where I have used the following formats:

sql = ("SELECT column1, column2, column3, column4 "
       "FROM table1 "
       "LEFT OUTER JOIN table2 ON x = y "
       "LEFT OUTER JOIN table3 ON table3.z = table1.y "

However now I have started to copy into Python largest and more complicated SQL codes and I find quite difficult to use the same format as the above as columns start to contain sub-codes. I have seen some python packages that format an SQL code into python and I was wondering which one you suggest or what is the best and quiker way to overcome this situation.

2 Answers 2

1

You can use python multiline strings that start and end with three ` ```This is a

a multi

   line

string``` and not worry about formatting. This is what i generally use for such purposes but ideally you should go with an ORM

For reference please check

https://www.w3schools.com/python/python_strings.asp

Sign up to request clarification or add additional context in comments.

Comments

1

For readability, you can try this

For example:

sql = """ SELECT country, product, SUM(profit) FROM sales   left join
x on x.id=sales.k GROUP BY country, product having f > 7 and fk=9
limit 5;    """

will result in:

sql = """
    SELECT
        country,
        product,
        SUM(profit)
    FROM
        sales
        LEFT JOIN x ON
            x.id = sales.k
    GROUP BY
        country,
        product
    HAVING
        f > 7
        AND fk = 9
    LIMIT 5; """

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.