SQL クエリをフォーマットする方法
適切なキーワードの整列、インデント、改行で SQL クエリを整形します。
问题
SQL クエリが 1 行の長い文字列になっており、レビューとデバッグのために読みやすくする必要があります。
前提条件
- SQL 構文の理解
- クエリ句への習熟
ステップ
-
1. Parse the SQL query
The formatter parses the SQL to identify keywords, identifiers, strings, and comments. It recognizes clauses like SELECT, FROM, WHERE, JOIN, GROUP BY, and ORDER BY to determine the structure.
入力SELECT id,name FROM users WHERE age>18 ORDER BY name输出parsed structure -
2. Apply formatting rules
Place each major clause on a new line. Indent subqueries and join conditions. Align column names in SELECT lists. Use consistent capitalization for keywords (upper or lower based on preference). Add spaces around operators.
入力SELECT id,name FROM users WHERE age>18输出SELECT id, name\nFROM users\nWHERE age > 18 -
3. Handle dialect-specific syntax
Different SQL dialects (PostgreSQL, MySQL, T-SQL) have unique syntax. Choose the correct dialect so the formatter parses functions, types, and keywords correctly. Misidentifying the dialect can cause formatting errors.
入力PostgreSQL query输出dialect-aware formatting
期待される結果
キーワードの整列、サブクエリのインデント、一貫したスペース配置による読みやすい SQL クエリ。
よくあるエラー
- Formatter does not recognize a dialect-specific function
- Select the correct SQL dialect. If the formatter still fails, the syntax may be unsupported; use a more capable formatter.
- String literals are modified
- A good formatter never alters string literal contents. If it does, it has a bug; use a different formatter.
トラブルシューティング指引
- If the formatted query executes differently, compare the original and formatted SQL character by character.
- Comments should be preserved. If they are lost, use a formatter that supports comments.
セキュリティ上の制限
- Formatting SQL does not execute it. However, never format untrusted SQL and then execute it — SQL injection is a separate concern.