When you encounter SQL Server error 102—incorrect syntax near [a keyword or token]—it means the T-SQL query you wrote doesn’t match the expected grammar for that operation. This error often stems from missing colons, mismatched parentheses, incorrect reserved words, or improper table/column names. You can resolve it by rewriting the query with the correct syntax, verifying reserved words, and ensuring proper delimiters. If you’re still stuck, check for hidden special characters or unescaped quotes in your input.

What You'll Need

  • A working SQL Server client (SQL Server Management Studio, SSMS, or a free tool like Azure Data Studio or DBeaver)
  • Access to the SQL Server instance where the error occurs (local, remote, or cloud)
  • Basic knowledge of reserved keywords and T-SQL syntax
  • A query editor open with your existing query or a new blank one

Step-by-Step

  1. Check for hidden special characters: Search your query for invisible characters like non-breaking spaces, tabs, or carriage returns. Copy the query into plain text (not Notepad++) and paste it into the editor—this often reveals hidden formatting issues. Tools like Notepad++ or the "Trim Whitespace" feature in Visual Studio can help clean up lines with stray spaces. If that did not work: Use the CHECKPOINT command to reset the query before executing it again: SET QUOTEPACKETOUTPUT ON; GO Then re-enter the query.
  2. Validate basic syntax structure: Ensure your query follows the correct order of operations. For example:
    • SELECT must come before FROM in a basic query.
    • Every GROUP BY must pair with an aggregate function like COUNT, SUM, or AVG.
    • Parentheses must match (one opening for every closing).
    Example of a correct query: SELECT Column1, Column2 FROM TableName WHERE Column1 = 'Value'; Example of an incorrect query (missing semicolon): SELECT Column1, Column2 FROM TableName WHERE Column1 = 'Value' SELECT Column3 FROM Table4 Remedy: Add a semicolon after the first query and execute separately. Check for reserved keywords: If your query contains a reserved keyword like ORDER (should be ORDER BY) or DESC (as part of ORDER BY DESC), enclose it in double quotes if it’s a user-defined column name: "ORDER" as "MyColumn"
  3. Review table/column names: Ensure you’re using exact names as defined in your database schema. For example:
    • Case sensitivity matters in SQL Server (unless collation is set to case-insensitive).
    • Use double quotes for names with spaces or special characters: SELECT "Customer Name" FROM Customers WHERE "Order Date" = '2023-01-01'
  4. Test with a minimal query: Strip your query down to its core parts and incrementally rebuild it. For example: If you’re writing: SELECT * FROM Employees WHERE Department = 'Finance' AND Salary > 75000 ORDER BY Name First try: SELECT * FROM Employees WHERE Department = 'Finance' Then add conditions one by one. A failing query often highlights the specific line causing the syntax issue.
  5. Use the correct data type: If your query references a column incorrectly (e.g., mixing INT with DATE), the server will flag it. For example: SELECT ID, date_of_birth FROM Employees WHERE date_of_birth = 1990 Should be: SELECT ID, date_of_birth FROM Employees WHERE CONVERT(VARCHAR, date_of_birth) = '1990' Or (better): SELECT ID, date_of_birth FROM Employees WHERE YEAR(date_of_birth) = 1990

Common Mistakes

  • Missing semicolon: Queries without semicolons at the end are often truncated or misinterpreted by SQL Server. Always end each statement with a semicolon, even in stored procedures.
  • Unescaped quotes in identifiers: If your column or table name contains single quotes (e.g., Product 'Price'), enclose the entire identifier in double quotes: SELECT "Product 'Price'" FROM Products
  • Parentheses imbalance: Use tools like CHECKPOINT or a syntax analyzer (e.g., SSMS’s "Script" > "Generate Script") to verify balanced parentheses. For example: SELECT * FROM (SELECT 1) AS Temp is missing a closing parenthesis.
  • Reserved keywords as identifiers: Words like GROUP, ORDER, or SELECT cannot be used as column names unless quoted as shown earlier.
  • Cross-database queries without validation: If querying across databases (e.g., SELECT FROM Database1.Dbo.Table1), ensure the database and schema exist and are accessible.

Tips

  • Use the Query Analyzer in SSMS: Right-click your query in SSMS and select Run SQL Server Query Analyzer. This provides detailed error messages that are often more helpful than the error code alone.
  • Enable bad script detection: In SSMS, navigate to Tools > Options > SQL Server Object Explorer > Bad Script Detection to enable warnings for potential syntax issues before execution.
  • Check for SQL injection risks: If your query includes user input (e.g., dynamic SQL), ensure all parameters are properly escaped or sanitized to avoid syntax errors or security issues.
  • Use the "Live Query" feature: In Azure Data Studio, right-click the query and select Live Query to see errors and results in real-time as you type.
  • Review the DDL for your tables: If the error persists, compare the column names in your query with the schema definition using: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName'

Troubleshooting

  1. Restart the SQL Server service: If the error persists with a recently written query, restart the SQL Server service via:
    1. Windows Task Manager > End Task for sqlservr.exe (if running locally).
    2. Or restart the service through Services.msc (search for "Services" in Windows Run).
    Then re-test your query.
  2. Check for conflicting collations: If you’re working with Unicode strings (e.g., UTF-8) and encounter case-sensitivity issues, ensure all strings use the same collation: SELECT * FROM Customers WHERE Name COLLATE Latin1_General_CS_AS = 'John' For more details, check the collation settings in your database: SELECT name, default_collation_name FROM sys.databases WHERE name = 'YourDatabase'
  3. Recreate the query in a new session: If you’re working with a stored procedure or a complex query, open a new connection to SQL Server and execute the query. Sometimes cached errors or corrupted connections cause false positives.
  4. Search for the error in the SQL Server error logs: Navigate to C:\Program Files\Microsoft SQL Server\MSSQL1XX.MSSQLSERVER\Log\ (replace XX with your version) to check for detailed error logs that might clarify the issue.

Frequently Asked Questions

How do I fix an error like "Incorrect syntax near 'SELECT'"?

This error typically occurs when you mistakenly place SELECT outside a function or table reference. The query should start with SELECT inside parentheses or a function. For example:

  • SELECT * FROM (SELECT 1) AS Temp is invalid.
  • SELECT * FROM (SELECT 1 AS Temp) is correct.

Why does my query keep saying "Incorrect syntax near 'ORDER BY'"?

This error usually means:

  • The ORDER BY clause is missing a column reference (e.g., ORDER BY alone is invalid).
  • A reserved keyword (like DESC) is not properly quoted.
Fix it by ensuring ORDER BY is followed by a column name: SELECT * FROM Employees ORDER BY Name DESC

How can I verify if my table names or column names are correct?

Use the following query to cross-check: EXEC sp_help 'YourTableName' Or for specific columns: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName'

What should I do if I’m unsure which part of my query is causing the error?

Start by executing a minimal query and gradually add lines until the error reappears. For example:

  1. Run: SELECT * FROM YourTable
  2. If it fails, add WHERE YourColumn = 'Value'.
  3. If it still fails, move to the next column.
This helps isolate the problematic section.

Why does SQL Server sometimes give a "syntax error" for a query that worked before?

This could happen due to:

  • Version upgrades in SQL Server that changed syntax rules.
  • Hidden characters or whitespace being introduced (e.g., copy-paste errors).
  • Changes in the database schema (e.g., column renames or deleted columns).
  • A corrupted connection or session cache.
Try restarting the SQL Server instance or opening a new connection.

How can I avoid "Incorrect syntax near" errors in the future?

Adopt these habits:

  • Use an IDE like SSMS or Azure Data Studio for syntax highlighting and auto-completion.
  • Run your queries through a tool like sqlcmd or bcp to catch hidden issues.
  • Write simple queries first, then expand them step-by-step.
  • Enable bad script detection in SSMS as mentioned earlier.