Format SQL: Tips for Writing Efficient and Readable Queries
Format SQL (Structured Query Language) refers to the process of beautifying or styling SQL queries to make them more organized, easier to read and more human-friendly. This involves making use of whitespace characters, indentation, comment lines, and line breaks to break up the code into logical sections and align keywords, clauses, and values in a consistent manner.
For example, suppose we have the following SQL query:
SELECT customerId, firstName, lastName, email
FROM customer
WHERE firstName = 'John' AND lastName = 'Doe';
We can format it properly by adding whitespace characters, indentation, and lines breaks:
SELECT customerId,
firstName,
lastName,
FROM customer
WHERE firstName = 'John'
AND lastName = 'Doe';
This formatted code is much easier to read and understand at a glance.
In addition, there are various tools and libraries available to automatically format SQL code. For example, the popular SQL formatter tool, SQLFormat.io, can quickly re-format any SQL query you paste into it.
Here is an example of using the popular SQLAlchemy library to format SQL:
from sqlalchemy import text
# The unformatted SQL query
sql = text("SELECT customerId,firstName,lastName,email FROM customer WHERE firstName = 'John' AND lastName = 'Doe';")
# The formatted SQL query
formatted_sql = sql.columns('customerId', 'firstName', 'lastName', 'email') \
.table('customer') \
.where(text("firstName = 'John' AND lastName = 'Doe'")).string
By using the SQLAlchemy's text function, we can pass in the unformatted SQL query and then use the columns, table, and where functions to format it accordingly.