Even though template strings work as expected, I have hard time to read, validate and format the SQL queries put inside of them.
I prefer to have a utility function that loads a query as a string from a file on app start.
Here is a TypeScript example of this utility function:
import {existsSync, readFileSync} from 'fs'
export const loadQuery = (queryFileName: string) => {
const path = `src/queries/${queryFileName}.sql`
if (!existsSync(path)) {
process.exit(1)
}
return readFileSync(path, 'utf8')
}
Now, I have an SQL file which I can autoformat with any tool I find handy:
SELECT
article.title,
article.description,
article.created_by,
article.company_id
FROM articles article
INNER JOIN users usr ON
usr.company_id = article.company_id AND
usr.email = $1
ORDER BY article.title;
Which looks this way in WebStorm with an SQL formatting plugin installed:

In the end, I call it this way (Koa/Express endpoint example):
import {dbClient} from '../dbClient'
import {loadQuery} from './loadQuery'
const getUserCompanyArticlesQuery = loadQuery('getUserCompanyArticles')
export const getUserCompanyArticles = async (email: string) => {
const result = await dbClient.query(
getUserCompanyArticlesQuery,
[email])
return result.rows
}
Pros:
- Autoformatting of the SQL.
- Separating SQL queries from the code which improves readability.
- I can quickly see the query itself when I need to debug.
Cons:
- You have to have and load an external file from the filesystem when
running the app.