AgentSkillsCN

Syntax Checker

语法检查器

SKILL.md

SQL Syntax Checker

Validate SQL syntax, identify errors, and ensure queries are structurally correct before execution.

Trigger Conditions

Activate this skill when the user:

  • Says "check this SQL", "validate my query", "is this correct"
  • Pastes SQL and asks if it will work
  • Gets a syntax error and needs help understanding it
  • Wants to verify SQL before running on production
  • Asks about SQL syntax rules

Validation Workflow

code
1. PARSE       -> Analyze query structure
2. IDENTIFY    -> Detect the SQL dialect
3. CHECK       -> Validate against syntax rules
4. REPORT      -> List errors with line numbers
5. FIX         -> Provide corrected version

Pre-Flight Checklist

Before validating any query:

code
- [ ] Identified target database dialect
- [ ] Checked for complete query (no truncation)
- [ ] Noted any placeholders or parameters

Common Syntax Rules

Universal Rules (All Dialects)

RuleCorrectIncorrect
KeywordsCase-insensitiveN/A
IdentifiersLetters, numbers, underscoresStarting with numbers
String literalsSingle quotesDouble quotes (most dialects)
Statement terminatorSemicolonNone (depends on context)
Comments-- or /* */# (MySQL only)

SELECT Statement Structure

sql
SELECT [DISTINCT | ALL]
    column_list
FROM table_reference
    [JOIN clause]
[WHERE condition]
[GROUP BY expression_list]
[HAVING condition]
[ORDER BY expression_list [ASC | DESC]]
[LIMIT count [OFFSET start]]

Common errors:

  • Columns in SELECT not in GROUP BY (when not aggregated)
  • ORDER BY position number exceeding column count
  • HAVING without GROUP BY
  • Missing table alias with ambiguous column names

Clause Order Validation

code
Required order:
1. SELECT
2. FROM
3. WHERE
4. GROUP BY
5. HAVING
6. ORDER BY
7. LIMIT/OFFSET

Syntax Error Patterns

Missing or Mismatched Parentheses

Error:

sql
SELECT * FROM users WHERE (status = 'active' AND (role = 'admin')

Fixed:

sql
SELECT * FROM users WHERE (status = 'active' AND role = 'admin')

Incorrect String Quotes

Error (most dialects):

sql
SELECT * FROM users WHERE name = "John"

Fixed:

sql
SELECT * FROM users WHERE name = 'John'

Missing Commas in Column List

Error:

sql
SELECT id name email FROM users

Fixed:

sql
SELECT id, name, email FROM users

Invalid Column Reference in ORDER BY

Error:

sql
SELECT name, COUNT(*) FROM users GROUP BY name ORDER BY email

Fixed:

sql
SELECT name, COUNT(*) FROM users GROUP BY name ORDER BY name

Missing JOIN Condition

Error:

sql
SELECT * FROM orders o JOIN customers c

Fixed:

sql
SELECT * FROM orders o JOIN customers c ON o.customer_id = c.id

Aggregate Without GROUP BY

Error:

sql
SELECT department, name, COUNT(*) FROM employees

Fixed:

sql
SELECT department, COUNT(*) FROM employees GROUP BY department

Invalid NULL Comparison

Error:

sql
SELECT * FROM users WHERE deleted_at = NULL

Fixed:

sql
SELECT * FROM users WHERE deleted_at IS NULL

Ambiguous Column Reference

Error:

sql
SELECT id, name FROM users u JOIN orders o ON u.id = o.user_id

Fixed:

sql
SELECT u.id, u.name FROM users u JOIN orders o ON u.id = o.user_id

Dialect-Specific Validation

PostgreSQL Specifics

FeaturePostgreSQL Syntax
String concat`'a'
Case sensitivityIdentifiers lowercase unless quoted
BooleanTRUE, FALSE, 't', 'f'
Array accessarray_col[1] (1-indexed)
JSON accessjson_col->>'key' or json_col->'key'
Type castvalue::type or CAST(value AS type)

MySQL Specifics

FeatureMySQL Syntax
String concatCONCAT('a', 'b')
Identifier quotesBackticks: `table_name`
Limit with offsetLIMIT offset, count or LIMIT count OFFSET offset
Auto incrementAUTO_INCREMENT
Boolean1, 0, TRUE, FALSE

SQL Server Specifics

FeatureSQL Server Syntax
String concat'a' + 'b' or CONCAT('a', 'b')
Identifier quotesSquare brackets: [table_name]
Top N rowsSELECT TOP 10 *
IdentityIDENTITY(1,1)
Date functionsGETDATE(), DATEADD(), DATEDIFF()

Oracle Specifics

FeatureOracle Syntax
String concat`'a'
Row limitingFETCH FIRST 10 ROWS ONLY (12c+)
Sequencesequence_name.NEXTVAL
From dualRequired for SELECT without table
NVLUse NVL(col, default) for null handling

SQLite Specifics

FeatureSQLite Syntax
Auto incrementINTEGER PRIMARY KEY (automatic)
Boolean0 and 1 (no boolean type)
Type affinityFlexible typing
LimitLIMIT count OFFSET start
Date functionsdate(), datetime(), strftime()

Validation Checklist

Structure Validation

code
- [ ] All keywords spelled correctly
- [ ] Clauses in correct order
- [ ] Required clauses present (SELECT, FROM for queries)
- [ ] Parentheses balanced and matched
- [ ] All expressions complete

Reference Validation

code
- [ ] All column names valid or aliased
- [ ] All table names valid or aliased
- [ ] Aliases used consistently
- [ ] No ambiguous references
- [ ] Subquery columns accessible

Type Validation

code
- [ ] Comparison types compatible
- [ ] Function arguments correct type
- [ ] Literals properly quoted
- [ ] Date/time formats valid
- [ ] Numeric precision appropriate

Logic Validation

code
- [ ] JOINs have ON conditions
- [ ] WHERE conditions make sense
- [ ] GROUP BY includes all non-aggregated columns
- [ ] HAVING uses aggregate functions
- [ ] No circular references

Error Message Interpretation

PostgreSQL Errors

ErrorMeaningSolution
syntax error at or near "X"Unexpected tokenCheck syntax before token X
column "X" does not existUnknown columnVerify column name/alias
relation "X" does not existUnknown tableVerify table name
column "X" must appear in GROUP BYMissing groupingAdd column to GROUP BY or aggregate
operator does not exist: XType mismatchCast types appropriately

MySQL Errors

ErrorMeaningSolution
You have an error in your SQL syntaxParse errorCheck near indicated position
Unknown column 'X'Column not foundVerify column/alias
Table 'X' doesn't existTable not foundVerify table name
Mixing of GROUP columnsInvalid groupingFix GROUP BY
Duplicate entry 'X' for keyUnique violationHandle duplicates

SQL Server Errors

ErrorMeaningSolution
Incorrect syntax near 'X'Parse errorCheck syntax
Invalid column name 'X'Unknown columnVerify column
Invalid object name 'X'Unknown tableVerify table
Column 'X' is invalid in the select listMissing GROUP BYFix grouping
Conversion failedType errorCast appropriately

Output Format

When validating SQL, provide:

  1. Status: Valid or Invalid
  2. Errors Found: List with line numbers
  3. Warnings: Non-critical issues
  4. Corrected Query: If errors found
  5. Explanation: What was wrong and why

Example output:

code
Status: INVALID

Errors Found:
1. Line 3: Missing comma between columns
2. Line 5: Unclosed parenthesis
3. Line 7: Unknown column 'user_name' - did you mean 'username'?

Warnings:
1. SELECT * is discouraged - specify columns explicitly
2. Missing table alias may cause ambiguity with JOINs

Corrected Query:
[corrected SQL here]

Explanation:
[detailed explanation]

Additional Resources

FileContent
examples.mdCommon syntax errors and corrections