SQL formatting: comments, line breaks and quoted names

Choose the SQL dialect, retain line-comment boundaries, quoted names and spacing between adjacent strings, then review the formatted query.

Content reviewed ·

The problem and context

SQL whitespace cannot always be collapsed freely. A SQLite double-hyphen comment lasts through the next newline; deleting that newline can leave the following expression inside the comment. Text inside a quoted name is part of the name itself. PostgreSQL also uses newline-containing whitespace to concatenate adjacent strings, so those boundaries must survive formatting.

Method and calculation

Choose the actual database dialect before setting indentation and keyword case. Uppercase keywords need not alter strings or quoted identifiers. After formatting, check that SQL following a line comment is still outside it, compare names inside backticks, brackets or double quotes, and retain the text within and between string constants.

Worked example

Write SELECT 1-- keep from here, start a new line, then add +2 AS n. SQLite returns 3. Joining the lines turns the rest into comment text and changes the result to 1. In SQLite, `from` and [where] are quoted names whose contents must not gain newlines. PostgreSQL single-quoted strings joined by a newline also need that boundary retained.

Checklist

Copy the formatted text or download query.sql. The tool arranges source without connecting to a database; table definitions, parameter binding and query results belong to the actual database. Stored procedures, custom DELIMITER directives and template syntax need separate handling. Input, lexical-complexity and output limits appear beside the editor. Tasks stop after 30 seconds and can be retried after editing. Use explicit AS aliases when result-column names must stay fixed; unaliased names are chosen by the database.

SQL Formatter

Input

Up to 1000000 UTF-16 input units, 50000 tokens, 64 levels and 5000 statements; at most 2000000 output units and 30 seconds per task.

Formatting options

Quotes, comments and parameters follow the chosen dialect. Case options change keywords while retaining strings and quoted names.

Enter SQL, select its dialect and format, or load the sample.

Use these tools with this article

  • JSON Tools

    Online JSON tool supporting formatting, compression, validation and beautification. Essential tool for developers, runs locally.

  • SQL Formatter

    Format SQL by dialect while retaining comments, strings and quoted names. Choose indentation and keyword case, then copy or download query.sql.

  • JSON to TS

    Generate TypeScript types from JSON samples, merge array-object fields into unions and optional properties, then copy or download types.ts.

  • CSV ⇄ JSON

    Convert header-based CSV and JSON object arrays with comma, semicolon or tab delimiters.

Sources