An SQL string can be built in many ways in JavaScript and other languages. Below are the variations I've seen and have used.
My personal favourite at the moment is the Concatenated array items.
Have your own way? Add it below.
var sql = 'SELECT * FROM table WHERE column = value';
- Simple
- Minimal typing
- Can't grow without becoming unreadable
var sql = 'SELECT * ';
sql += 'FROM table ';
sql += 'WHERE column = value ';
Or if you'd like things to line up:
var sql = '' ;
sql = 'SELECT *' ;
sql += 'FROM table ';
sql += 'WHERE column = value ';
- Simple(ish)
- Can grow as needed
- Each line is consistent
- A space is needed on each line (beginning or end)
- A bunch more typing for each line
var sql = [
'SELECT *',
'FROM table',
'WHERE column = value'
];
- Nice to read
- Will grow
- No leading/trailing space needed
- sql.join(' ') is needed when used
var sql = "SELECT * \
FROM table \
WHERE column = value";
- No extra whitespace required
- No need for closing/opening quotes repeatedly
- Will grow
- Having to escape newline looks ugly
var sql = multiline(function(){/*
SELECT *
FROM table
WHERE column = value
*/});
- Write everything as is
- No newline escape
- Will grow
- No extra whitespace
- Extra package dependency
- Micro performance hit
- JavaScript only (AFAIK)
ES6 natively supports multiline strings.
var sql = `
SELECT *
FROM table
WHERE column = value`;
- Write everything as is
- No newline escape
- Will grow
- Requires using es6-templates to compile JavaScript written using template strings to use ES5-compatible syntax