This should be a quick one, but it is something that took me a little while to work out, but now I know I use it pretty much every day in my projects to save me a lot of time.

This is the ability to copy and paste my SQL code into my python code as a multi-line string without having to reduce it to be all on one line or using escape characters. Both of which can take a bit of time depending on how big your SQL is. You usually need to have SQL code as a string like this to use in spark or python to query databases to bring data in for projects, and it’s much easier to be able to directly paste this code in and edit it like you would in your usual SQL editor.

The solution is to use triple quotes. Simply place a triple quote (“””) then underneath paste your SQL, then underneath that place another triple quote. For example, the below SQL would go from:

SQL_query = ” SELECT * from DB where x =1 and y = ‘yes’ and z = True order by 1 desc”

to

SQL_query= “””
SELECT * from DB
where x =1
and y = ‘yes’
and z = True
order by 1 desc
“””

While this is a simple example, I’m sure you can imagine how useful this can be for much longer and more complex queries, as it lets you see and edit the query as you could in your native SQL editor, with the bonus of much less messing around to get the code into your project in a useable format.

Tags: , , , ,