Try it yourself with our free Sql Formatter tool — runs entirely in your browser, no signup needed.

How to Format SQL queries in JavaScript

How to Format SQL Queries in JavaScript

Formatting SQL queries in JavaScript is an essential skill for any developer working with databases. Not only does it improve the readability of your code, but it also helps prevent errors and makes it easier to debug. In this guide, we will explore how to format SQL queries in JavaScript, covering the basics, common edge cases, and performance tips.

Quick Example

Here is a minimal example of how to format a SQL query in JavaScript:

const sqlFormatter = require('sql-formatter');

const query = "SELECT * FROM users WHERE name = 'John' AND age > 18";
const formattedQuery = sqlFormatter.format(query);

console.log(formattedQuery);

This code uses the sql-formatter library to format a simple SQL query. The output will be:

SELECT *
FROM users
WHERE name = 'John'
  AND age > 18;

Step-by-Step Breakdown

Let's break down the code line by line:

  1. const sqlFormatter = require('sql-formatter');:
    • We import the sql-formatter library, which is a popular and widely-used library for formatting SQL queries in JavaScript.
    • You can install it using npm by running npm install sql-formatter in your terminal.
  2. const query = "SELECT * FROM users WHERE name = 'John' AND age > 18";:
    • We define a SQL query as a string. This is a simple example, but in a real-world scenario, this query might be generated dynamically or come from a user input.
  3. const formattedQuery = sqlFormatter.format(query);:
    • We use the format() method of the sqlFormatter library to format the query.
    • The format() method takes the query as an input and returns a formatted string.
  4. console.log(formattedQuery);:
    • We log the formatted query to the console.

Handling Edge Cases

Empty/Null Input

If the input query is empty or null, the format() method will throw an error. To handle this, we can add a simple check:

const query = "";
if (query) {
  const formattedQuery = sqlFormatter.format(query);
  console.log(formattedQuery);
} else {
  console.log("Error: Empty or null query");
}

Invalid Input

If the input query is invalid (e.g., contains syntax errors), the format() method will throw an error. To handle this, we can use a try-catch block:

try {
  const formattedQuery = sqlFormatter.format(query);
  console.log(formattedQuery);
} catch (error) {
  console.log(`Error: ${error.message}`);
}

Large Input

If the input query is very large, the format() method might take a significant amount of time to format it. To handle this, we can use a timeout or a streaming approach:

const largeQuery = "..."; // very large query
const timeout = 1000; // 1 second timeout

const formattedQuery = sqlFormatter.format(largeQuery, { timeout });
console.log(formattedQuery);

Unicode/Special Characters

If the input query contains Unicode or special characters, the format() method will handle them correctly:

const query = "SELECT * FROM users WHERE name = 'Jöhn' AND age > 18";
const formattedQuery = sqlFormatter.format(query);
console.log(formattedQuery);

Common Mistakes

1. Not installing the library

Make sure to install the sql-formatter library using npm by running npm install sql-formatter in your terminal.

Wrong code:

const sqlFormatter = require('sql-formatter');

Correct code:

npm install sql-formatter
const sqlFormatter = require('sql-formatter');

2. Not checking for empty/null input

Make sure to check for empty or null input before formatting the query.

Wrong code:

const query = "";
const formattedQuery = sqlFormatter.format(query);

Correct code:

const query = "";
if (query) {
  const formattedQuery = sqlFormatter.format(query);
  console.log(formattedQuery);
} else {
  console.log("Error: Empty or null query");
}

3. Not handling errors

Make sure to handle errors that might occur during the formatting process.

Wrong code:

const query = "SELECT * FROM users WHERE name = 'John' AND age > 18";
const formattedQuery = sqlFormatter.format(query);
console.log(formattedQuery);

Correct code:

try {
  const formattedQuery = sqlFormatter.format(query);
  console.log(formattedQuery);
} catch (error) {
  console.log(`Error: ${error.message}`);
}

Performance Tips

1. Use caching

If you are formatting the same query multiple times, consider using caching to improve performance.

const cache = {};
const query = "SELECT * FROM users WHERE name = 'John' AND age > 18";
if (cache[query]) {
  console.log(cache[query]);
} else {
  const formattedQuery = sqlFormatter.format(query);
  cache[query] = formattedQuery;
  console.log(formattedQuery);
}

2. Use streaming

If you are formatting large queries, consider using a streaming approach to improve performance.

const largeQuery = "..."; // very large query
const stream = sqlFormatter.formatStream(largeQuery);
stream.on("data", (chunk) => {
  console.log(chunk);
});

3. Optimize the library

Make sure to optimize the sql-formatter library for your specific use case.

const options = {
  indent: 2,
  newline: "\n",
};
const formattedQuery = sqlFormatter.format(query, options);
console.log(formattedQuery);

FAQ

Q: What is the best way to format SQL queries in JavaScript?

A: The best way to format SQL queries in JavaScript is to use a library like sql-formatter.

Q: How do I handle errors when formatting SQL queries?

A: You can handle errors by using a try-catch block.

Q: Can I use sql-formatter with large queries?

A: Yes, you can use sql-formatter with large queries, but consider using a streaming approach for better performance.

Q: How do I optimize the sql-formatter library?

A: You can optimize the sql-formatter library by passing options to the format() method.

Q: Can I use sql-formatter with Unicode or special characters?

A: Yes, sql-formatter handles Unicode and special characters correctly.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp