Use sql syntax error

SQLShack Common SQL syntax errors and how to resolve them In the SQL Server Management Studio, errors can be tracked down easily, using the built in Error List pane. This pane can be activated in the View menu, or by using shortcuts Ctrl+ and Ctrl+E The Error List pane displays syntax and semantic errors […]

Содержание

  1. SQLShack
  2. Common SQL syntax errors and how to resolve them
  3. SQL Keyword errors
  4. Arrangement of commands
  5. Using quotation marks
  6. Finding SQL syntax errors
  7. Related posts:
  8. About Milena Petrovic
  9. SQL Errors: Five Common SQL Mistakes
  10. Watch Your Language (and Syntax)
  11. 1. Misspelling Commands
  12. Solution:
  13. 2. Forgetting Brackets and Quotes
  14. Solution:
  15. 3. Invalid statement order
  16. Solution:
  17. 4. Omitting Table Aliases
  18. Solution:
  19. 5. Using Case-Sensitive Names
  20. Solution:
  21. Everybody Makes SQL Mistakes

SQLShack

Common SQL syntax errors and how to resolve them

In the SQL Server Management Studio, errors can be tracked down easily, using the built in Error List pane. This pane can be activated in the View menu, or by using shortcuts Ctrl+ and Ctrl+E

The Error List pane displays syntax and semantic errors found in the query editor. To navigate directly to the SQL syntax error in the script editor, double-click the corresponding error displayed in the Error List

SQL Keyword errors

SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. For example, writing “UPDTE” instead of “UPDATE” will produce this type of error

In this example, the keyword “TABLE” is misspelled:

As shown in the image above, not only the word “TBLE” is highlighted, but also the words around it. The image below shows that this simple mistake causes many highlighted words

In fact, there are total of 49 errors reported just because one keyword is misspelled

If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem

It’s also possible that all SQL keywords are spelled correctly, but their arrangement is not in the correct order. For example, the statement “FROM Table_1 SELECT *” will report an SQL syntax error

Arrangement of commands

The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue

If the user, for example, is trying to create a new schema into an existing database, but first wants to check if there is already a schema with the same name, he would write the following command

However, even though each command is properly written, and is able to run separately without errors, in this form it results in an error

As the error message states, CREATE SCHEMA command has to be the first command that is given. The correct way of running this commands together looks like this

Using quotation marks

Another common error that occurs when writing SQL project is to use double quotation marks instead of single ones. Single quotation marks are used to delimit strings. For example, double quotation marks are used here instead of single ones, which cause an error

Replacing quotation marks with the proper ones, resolves the error

There are situations where double quotation marks need to be used, for writing some general quotes, for example

As shown in the previous example, this will cause an error. But, this doesn’t mean that double quotes can’t be used, they just have to be inside the single quotes. However, adding single quotes in this example won’t solve the problem, but it will cause another one

Since there is an apostrophe inside this quote, it is mistakenly used as the end of a string. Everything beyond is considered to be an error

To be able to use an apostrophe inside a string, it has to be “escaped”, so that it is not considered as a string delimiter. To “escape” an apostrophe, another apostrophe has to be used next to it, as it is shown below

Finding SQL syntax errors

Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code

Another way to help, is to properly format the code

This can improve code readability, thus making the search for errors easier

Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University.

She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014.

Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring.

  • Using custom reports to improve performance reporting in SQL Server 2014 – running and modifying the reports — September 12, 2014
  • Using custom reports to improve performance reporting in SQL Server 2014 – the basics — September 8, 2014
  • Performance Dashboard Reports in SQL Server 2014 — July 29, 2014

About Milena Petrovic

Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University. She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014. Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring. View all posts by Milena «Millie» Petrovic

Источник

SQL Errors: Five Common SQL Mistakes

As you learn SQL, watch out for these common coding mistakes

You’ve written some SQL code and you’re ready to query your database. You input the code and …. no data is returned. Instead, you get an error message.

Don’t despair! Coding errors are common in any programming language, and SQL is no exception. In this article, we’ll discuss five common mistakes people make when writing SQL.

The best way to prevent mistakes in SQL is practice. LearnSQL.com offers over 30 interactive SQL courses. Try out our SQL Practice track with 5 courses and over 600 hands-on exercises.

Watch Your Language (and Syntax)

The most common SQL error is a syntax error. What does syntax mean? Basically, it means a set arrangement of words and commands. If you use improper syntax, the database does not know what you’re trying to tell it.

To understand how syntax works, we can think of a spoken language. Imagine saying to a person “Nice dof” when you mean “Nice dog”. The person does not know what “dof” means. So when you tell your database to find a TABEL instead of a TABLE, the database does not know what it needs to do.

People tend to make the same kinds of syntax mistakes, so their errors are usually easy to spot and very much the same. After you read this article, you should be able to remember and avoid (or fix) these common mistakes. Knowing what errors to look for is very important for novice SQL coders, especially early on. New coders tend to make more mistakes and spend more time looking for them.

The types of SQL errors we will look at are:

  1. Misspelling Commands
  2. Forgetting Brackets and Quotes
  3. Specifying an Invalid Statement Order
  4. Omitting Table Aliases
  5. Using Case-Sensitive Names

Ready? Let’s start.

SQL Errors:

1. Misspelling Commands

This is the most common type of SQL mistake among rookie and experienced developers alike. Let’s see what it looks like. Examine the simple SELECT statement below and see if you can spot a problem:

If you run this query, you’ll get an error which states:

Each database version will tell you the exact word or phrase it doesn’t understand, although the error message may be slightly different.

What is wrong here? You misspelled FROM as FORM. Misspellings are commonly found in keywords (like SELECT, FROM, and WHERE), or in table and column names.

Most common SQL spelling errors are due to:

  • “Chubby fingers” where you hit a letter near the right one: SELEVT or FTOM or WJIRE
  • “Reckless typing” where you type the right letters in the wrong order: SELETC or FORM or WHEER

Solution:

Use an SQL editor that has syntax highlighting: the SELECT and WHERE keywords will be highlighted, but the misspelled FORM will not get highlighted.

If you’re learning with interactive SQL courses in LearnSQL.com , the code editor puts every SELECT statement keyword in light purple. If the keyword is black, as it is with any other argument, you know there’s a problem. (In our example, FORM is black).

So if we correct our statement we get:

The keyword is now the right color and the statement executes without an error.

2. Forgetting Brackets and Quotes

Brackets group operations together and guide the execution order. In SQL (and in all of the programming languages I use), the following order of operations …

… is not the same as:

Can you figure out why?

A very common SQL mistake is to forget the closing bracket. So if we look at this erroneous statement :

We get an error code with the position of the error (the 102nd character from the beginning):

Remember: brackets always come in pairs.

The same is true with single quotes ( ‘ ‘ ) or double quotes ( ” ” ). There is no situation in SQL where we would find a quote (either a single quote or a double quote) without its mate. Column text values can contain one quote ( e.g. exp.last_name = «O’Reilly» ) and in these situations we must mix two types of quotes or use escape characters. ( In SQL, using escape characters simply means placing another quote near the character you want to deactivate – e.g. exp.last_name = ‘O’’Reilly. )

Solution:

Practice, practice, practice. Writing more SQL code will give you the experience you need to avoid these mistakes. And remember people usually forget the closing bracket or quotation mark. They rarely leave out the opening one. If you’re running into problems, take a close look at all your closing punctuation!

3. Invalid statement order

When writing SELECT statements, keep in mind that there is a predefined keyword order needed for the statement to execute properly. There is no leeway here.

Let’s look at an example of a correctly-ordered statement:

There’s no shortcut here; you simply have to remember the correct keyword order for the SELECT statement:

  • SELECT identifies column names and functions
  • FROM specifies table name or names (and JOIN conditions if you’re using multiple tables)
  • WHERE defines filtering statements
  • GROUP BY shows how to group columns
  • HAVING filters the grouped values
  • ORDER BY sets the order in which the results will be displayed

You cannot write a WHERE keyword before a FROM , and you can’t put a HAVING before a GROUP BY . The statement would be invalid.

Let’s look at what happens when you mix up the statement order. In this instance, we’ll use the common SQL error of placing ORDER BY before GROUP BY :

The error message we see is pretty intimidating!

Solution:

Don’t be discouraged! You can see that all of the keywords are highlighted correctly and all the quotations and brackets are closed. So now you should check the statement order. When you’re just beginning your SQL studies, I suggest using a SELECT order checklist. If you run into a problem, refer to your list for the correct order.

4. Omitting Table Aliases

When joining tables, creating table aliases is a popular practice. These aliases distinguish among columns with the same name across tables; thus the database will know which column values to return. This is not mandatory when we’re joining different tables, since we can use the full table names. But it is mandatory if we join a table to itself.

Suppose we’re writing an SQL statement to find an exhibition’s current location and the location from the previous year:

The database would return an error:

Note: Whenever you encounter “ambiguous column name” in your error message, you surely need table aliases.

The correct statement (with aliases) would be:

Solution:

Practice using table aliases for single-table SELECT statements. Use aliases often – they make your SQL more readable.

5. Using Case-Sensitive Names

This error only occurs when you need to write non-standard names for tables or database objects.

Let’s say that you need to have a table named LargeClient and for some reason you add another table called LARGECLIENT. As you already know, object names in databases are usually case-insensitive. So when you write a query for the LargeClient table, the database will actually query LARGECLIENT.

To avoid this, you must put double quotes around the table name. For example:

When creating a table, you will need to use double quotes if:

  • The table will have a case-sensitive name.
  • The table name will contain special characters. This includes using a blank space, like “Large Client”.

Solution:

Avoid using these names if you can. If not, remember your double quotes!

Everybody Makes SQL Mistakes

Those are the five most common errors in SQL code. You’ll probably make them many times as you learn this language. Remember, everybody makes mistakes writing code. In fact, making mistakes is a normal and predictable part of software development.

So don’t be discouraged. When you make mistakes in the future, try to analyze your code in a structured way. With a structured analysis, you can find and correct your errors quicker.

If you would like to learn about some other syntactic mistakes that I’ve not included here, please let me know. In an upcoming article, we’ll look at non-syntactic errors. These return or modify data and are therefore much more dangerous. Subscribe to our blog so you won’t miss it!

Источник

So, you’re creating a custom SQL query to perform a task in the database. After putting the code together and running it in PHPmyAdmin it responds with a 1064 error. It may look similar to this:

1064 error message

The 1064 error displays any time you have an issue with your SQL syntax, and is often due to using reserved words, missing data in the database, or mistyped/obsolete commands. So follow along and learn more about what the 1064 error is, some likely causes, and general troubleshooting steps.

Note: Since syntax errors can be hard to locate in long queries, the following online tools can often save time by checking your code and locating issues:

  • PiliApp MySQL Syntax Check
  • EverSQL SQL Query Syntax Check & Validator

Causes for the 1064 error

  • Reserved Words
  • Missing Data
  • Mistyped Commands
  • Obsolete Commands

This may seem cryptic since it is a general error pointing to a syntax issue in the SQL Query statement. Since the 1064 error can have multiple causes, we will go over the most common things that will result in this error and show you how to fix them. Follow along so you can get your SQL queries updated and running successfully.

Using Reserved Words

Every version of MySQL has its own list of reserved words. These are words that are used for specific purposes or to perform specific functions within the MySQL engine. If you attempt to use one of these reserved words, you will receive the 1064 error. For example, below is a short SQL query that uses a reserved word as a table name.

CREATE TABLE alter (first_day DATE, last_day DATE);

How to fix it:

Just because the word alter is reserved does not mean it cannot be used, it just has special requirements to use it as the MySQL engine is trying to call the functionality for the alter command. To fix the issue, you will want to surround the word with backticks, this is usually the button just to the left of the “1” button on the keyboard. The code block below shows how the code will need to look in order to run properly.

CREATE TABLE `alter` (first_day DATE, last_day DATE);

Missing Data

Sometimes data can be missing from the database. This causes issues when the data is required for a query to complete. For example, if a database is built requiring an ID number for every student, it is reasonable to assume a query will be built to pull a student record by that ID number. Such a query would look like this:

SELECT * from students WHERE studentID = $id

If the $id is never properly filled in the code, the query would look like this to the server:

SELECT * from students WHERE studentID =

Since there is nothing there, the MySQL engine gets confused and complains via a 1064 error.

How to fix it:

Hopefully, your application will have some sort of interface that will allow you to bring up the particular record and add the missing data. This is tricky because if the missing data is the unique identifier, it will likely need that information to bring it up, thus resulting in the same error. You can also go into the database (typically within phpMyAdmin) where you can select the particular row from the appropriate table and manually add the data.

Mistyping of Commands

One of the most common causes for the 1064 error is when a SQL statement uses a mistyped command. This is very easy to do and is easily missed when troubleshooting at first. Our example shows an UPDATE command that is accidentally misspelled.

UDPATE table1 SET id = 0;

How to fix it:

Be sure to check your commands prior to running them and ensure they are all spelled correctly.

Below is the syntax for the correct query statement.

UPDATE table1 SET id = 0;

Obsolete Commands

Some commands that were deprecated (slated for removal but still allowed for a period of time) eventually go obsolete. This means that the command is no longer valid in the SQL statement. One of the more common commands is the ‘TYPE‘ command. This has been deprecated since MySQL 4.1 but was finally removed as of version 5.1, where it now gives a syntax error. The ‘TYPE‘ command has been replaced with the ‘ENGINE‘ command. Below is an example of the old version:

CREATE TABLE t (i INT) TYPE = INNODB;

This should be replaced with the new command as below:

CREATE TABLE t (i INT) ENGINE = INNODB;

For developers or sysadmins experienced with the command line, get High-Availability and Root Access for your application, service, and websites with Cloud VPS Hosting.

Error 1064 Summary

As you can see there is more than one cause for the 1064 error within MySQL code. Now, you know how to correct the issues with your SQL Syntax, so your query can run successfully. This list will be updated as more specific instances are reported.

  • Debugging a SQL query
  • How does SQL debugging work?
  • Debugging SQL syntax
  • Common SQL reference guides
  • Common SQL syntax errors
    • Column or table name is “not found” or “not recognized”
    • SQL function does not exist
  • How to find the failing line in a SQL query
    • Reading your SQL error message
    • Reducing the size of a SQL query
  • How to find out what SQL dialect to use
  • Do you have a different problem?
  • Are you still stuck?

Reading an error message shouldn’t feel like solving a riddle. This debugging guide explains what you can do about stubborn queries that refuse to run.

Debugging a SQL query

If your SQL query contains SQL variables that look like {{ variable }}, go to Troubleshooting SQL variables first.

  1. Go to the line that is failing in your SQL query.
    • I don’t know where my SQL query is failing.
  2. Check the SQL syntax on the line that is failing in your SQL query.
  3. Check your query logic if the query uses joins, subqueries, or CTEs.
  4. If you get an error message that isn’t specific to your SQL query, go to Troubleshooting error messages.

How does SQL debugging work?

  • SQL error messages are displayed for each line in your query that fails to run. You’ll need to follow the steps above for each line that failed.
  • If you make any changes to a line, run your query to check if the problem is fixed before moving on to the next step. You can add a LIMIT clause at the end of your query to speed up the process.
  • Note that SQL queries are not run from top to bottom, so you won’t be debugging your query lines in the order that they are written. Follow the error messages to help you find the lines that need attention.
  1. Review the spelling on the line that is failing in your SQL query.
  2. Review for missing brackets or commas on the line that is failing in your SQL query.
  3. Remove commented lines (lines that begin with -- or /*).
  4. Review for common syntax errors that are specific to your SQL dialect.

Explanation

Your database needs to be able to “read” your query in order to execute it.

  • Correct spelling tells your database exactly what to look for.
  • Punctuation tells your database how (e.g. what order to use) to look for your data.
  • Comments are not meant to be read or executed, but in certain edge cases, they can interfere with the reading and execution of neighboring lines.

Common SQL reference guides

Before you start, open up the SQL reference guide for the SQL dialect that you’re using. We’ve linked to some of the most common ones here:

  • MySQL
  • PostgreSQL
  • Microsoft SQL Server
  • Amazon Redshift
  • Google BigQuery
  • Snowflake
  • I don’t know what SQL dialect to use.

Common SQL syntax errors

What does your error message say?

  • My column or table name is “not found” or “not recognized”.
  • My SQL “function does not exist”.

Column or table name is “not found” or “not recognized”

If your SQL query contains SQL variables that look like {{ variable }}, go to Troubleshooting SQL variables first.

Steps

  1. Review the structure section of the reference guide for your SQL dialect.

    • Are you using the correct quotation marks? For example:

      • SELECT 'column_name'
      • SELECT "column_name"
      • SELECT `column_name`
    • Are you using the correct path to columns and tables? For example:

      • FROM table_name
      • FROM schema_name.table_name
      • FROM database_name.schema_name.table_name
    • Is your column name a reserved word? For example:

      In PostgresSQL, ‘users’ is a reserved key word.

      • SELECT users will throw an error.
      • SELECT "users" will run correctly.
    • Tip: Use Metabase to check for column and table name syntax

      1. Create a simple question in the notebook editor using the same columns and tables as your SQL question.
      2. Convert the question to SQL.
      3. Look at how the Metabase-generated SQL query refers to column and table names.
  2. Review the data reference for the column and table names in your query.

    • If the column or table name doesn’t exist in the data reference:

      • Run SELECT * FROM your_table_name LIMIT 10; to look for the column or table name to use in your query.
      • If you’re a Metabase admin, check the Data model page for the original schema.
    • If the column name exists, but you can’t query the column from the SQL editor:

      • Ask your Metabase admin if the column was re-named or removed on the database side.
      • If you’re a Metabase admin, you may need to run a sync to refresh your data.

Explanation

You need to make sure that you’re using the correct syntax for the SQL dialect used by your database.

Your query also needs to use column and table names that match the original names in your database. Metabase uses display names that can be updated by your Metabase admin, so the data reference may not match your database schema. It’s also possible that a column or table was re-named on the database side, but Metabase hasn’t run a sync to grab the updates.

Further reading

  • How Metabase executes SQL queries
  • How Metabase syncs with your database
  • SQL best practices

SQL function does not exist

If your SQL query contains SQL variables that look like {{ variable }}, go to Troubleshooting SQL variables first.

Steps

  1. Review the data type of the column that you want your function to apply to.

    • You can use the Metabase data reference to review the column’s field type (as a proxy for data type).
    • You can also directly query the information schema in your database if you have permission to access it.
  2. Review the function section of the reference guide for your SQL dialect.

    • Confirm that the function exists for your SQL dialect.
    • Review the data type(s) that are accepted by your function.
  3. If the field type of your column does not match the expected data type of your function:

    • Cast your column to the correct data type in your SQL query.
    • If you’re a Metabase admin, you can also cast data types from the Data model page.

Explanation

SQL functions are designed to work on specific data types in your database. For example, the DATE_TRUNC function in PostgresSQL works on columns with date, timestamp, and time typed data in a Postgres database. If you try to use the DATE_TRUNC function on a column with a string data type in your database, it won’t work.

Note that Metabase field types are not one-to-one with the data types in your database. In this case, the field type gives you enough information about the column data type to troubleshoot the error.

Further reading

  • How Metabase executes SQL queries
  • Field types documentation
  • SQL best practices

How to find the failing line in a SQL query

If your SQL query contains SQL variables that look like {{ variable }}, go to Troubleshooting SQL variables first.

Once you find the line that is failing in your SQL query, go to steps under Debugging a SQL query.

Reading your SQL error message

Does your error message:

  • Tell you the line or character position?
  • Include a table or column name? If the table or column name appears more than once in your query, reduce the size of your query.
  • Mention a SQL clause?

Reducing the size of a SQL query

If your query uses:

  • Subqueries (nested queries), run each subquery separately. Start with the inner subqueries and work your way out.
  • CTEs, run each CTE separately. Start with your base CTE and work your way down the query.
  • SQL variables that point to Metabase models, run each model separately. Go to the model by opening the variables panel, or enter the model ID number from the variable in the Metabase search bar.
  • Remember to read the SQL error message as you try to isolate the problem. For more information, go to How does SQL debugging work?.

Tips for working in the SQL editor

Highlight lines of your SQL query to:

  • Run the lines with Cmd + Return or Ctrl + Enter.
  • Comment/uncomment the lines with Cmd + / or Ctrl + /.

How to find out what SQL dialect to use

The SQL dialect is based on the database that stores the tables you want to query. Once you find out what SQL dialect to use, you can follow the steps under Debugging a SQL query.

To find out which database you’re querying:

  • If you’re a Metabase admin, go to Admin settings > Databases, and look under the Engine column.
  • Otherwise, ask the person who set up your Metabase.

Do you have a different problem?

  • My query results are wrong.
    • My query results have duplicated rows.
    • My query results have missing rows.
    • My aggregations (counts, sums, etc.) are wrong.
  • My dates and times are wrong.
  • My data isn’t up to date.
  • I have an error message that isn’t specific to my SQL query or syntax.

Are you still stuck?

Search or ask the Metabase community.

Thanks for your feedback!

Get articles like this one in your inbox every month

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Prerequisite – SQL Injection While checking for SQL injection we all discover various error messages. Let us figure out the basic cause behind each error and how it appears in MySQL. Below are various error and their explanation. Error-1: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ” foo ‘ at line X. Explanation – If you entered a single quote and it altered the syntax of the database query, this is the expected error message. For MySQL, SQL injection may be present, but the same error message can appear in other contexts. 
    Error-2: N/A Explanation – You have commented out or removed a variable that normally would be supplied to the database. 
    Error-3: The used SELECT statements have different number of columns. Explanation – You will see this when you are attempting a UNION SELECT attack, and you specified different number of columns to the number in the original SELECT statement. 
    Error-4: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ‘ XXX, YYY from SOME_TABLE’ at line 1 Explanation – You commonly see this error message when your injection point occurs before the FROM keyword (Example, you have injected into the columns to be returned) and you have used the comment character to remove required SQL keywords. Try completing the SQL statement yourself while using your comment character. MySQL should helpfully reveal the column names XXX, YYY when this condition is encountered. 
    Error-5: Table ‘DBNAME.SOMETABLE’ doesn’t exist. Explanation – Either you are trying to access a table or view that does not exist. Test your query against a table you know you have access to. MySQL should helpfully reveal the current database schema DBNAME when this condition is encountered. 
    Error-6: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ‘ ‘ at line 1. Explanation – You were probably altering something in a WHERE clause, and your SQL injection attempt has disrupted the grammar. 
    Error-7: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ‘ ‘ line 1. Explanation – Your SQL injection attempt has worked, but the injection point was inside parentheses. You probably commented out the closing parentheses with injected comment characters (–). 
    Error-8: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near XXXXX. Explanation – A general error message. The error messages listed previously all take precedence, so something else went wrong. It is likely that you can try alternative input and get a more meaningful message. 
     

    Contents

    1. Designing Queries
      1. Using Whitespace
      2. Table and Field Aliases
      3. Placing JOIN conditions
    2. Finding Syntax Errors
      1. Interpreting the Empty Error
      2. Checking for keywords
      3. Version specific syntax

    Designing Queries

    Following a few conventions makes finding errors in queries a lot easier,
    especially when you ask for help from people who might know SQL, but know
    nothing about your particular schema. A query easy to read is a query easy to
    debug. Use whitespace to group clauses within the query. Choose good table and
    field aliases to add clarity, not confusion. Choose the syntax that supports
    the query’s meaning.

    Using Whitespace

    A query hard to read is a query hard to debug. White space is free. New lines
    and indentation make queries easy to read, particularly when constructing a
    query inside a scripting language, where variables are interspersed throughout
    the query.

    There is a syntax error in the following. How fast can you find it?

    SELECT u.id, u.name, alliance.ally FROM users u JOIN alliance ON
    (u.id=alliance.userId) JOIN team ON (alliance.teamId=team.teamId
    WHERE team.teamName='Legionnaires' AND u.online=1 AND ((u.subscription='paid'
    AND u.paymentStatus='current') OR u.subscription='free') ORDER BY u.name;
    

    Here’s the same query, with correct use of whitespace. Can you find the error faster?

    SELECT
        u.id
        , u.name
        , alliance.ally
    FROM
        users u
        JOIN alliance ON (u.id = alliance.userId)
        JOIN team ON (alliance.teamId = team.teamId
    WHERE
        team.teamName = 'Legionnaires'
        AND u.online = 1
        AND (
            (u.subscription = 'paid' AND u.paymentStatus = 'current')
            OR
            u.subscription = 'free'
        )
    ORDER BY
        u.name;
    

    Even if you don’t know SQL, you might still have caught the missing ‘)’
    following team.teamId.

    The exact formatting style you use isn’t so important. You might like commas in
    the select list to follow expressions, rather than precede them. You might
    indent with tabs or with spaces. Adherence to some particular form is not
    important. Legibility is the only goal.

    Table and Field Aliases

    Aliases allow you to rename tables and fields for use within a query. This can
    be handy when the original names are very long, and is required for self joins
    and certain subqueries. However, poorly chosen aliases can make a query harder
    to debug, rather than easier. Aliases should reflect the original table name,
    not an arbitrary string.

    Bad:

    SELECT *
    FROM
        financial_reportQ_1 AS a
        JOIN sales_renderings AS b ON (a.salesGroup = b.groupId)
        JOIN sales_agents AS c ON (b.groupId = c.group)
    WHERE
        b.totalSales > 10000
        AND c.id != a.clientId
    

    As the list of joined tables and the WHERE clause grow, it becomes necessary to
    repeatedly look back to the top of the query to see to which table any given
    alias refers.

    Better:

    SELECT *
    FROM
        financial_report_Q_1 AS frq1
        JOIN sales_renderings AS sr ON (frq1.salesGroup = sr.groupId)
        JOIN sales_agents AS sa ON (sr.groupId = sa.group)
    WHERE
        sr.totalSales > 10000
        AND sa.id != frq1.clientId
    

    Each alias is just a little longer, but the table initials give enough clues
    that anyone familiar with the database only need see the full table name once,
    and can generally remember which table goes with which alias while reading the
    rest of the query.

    Placing JOIN conditions

    The manual warns against using the JOIN condition (that is, the ON
    clause) for restricting rows. Some queries, particularly those using implicit
    joins, take the opposite extreme — all join conditions are moved to the WHERE
    clause. In consequence, the table relationships are mixed with the business
    logic.

    Bad:

    SELECT *
    FROM
        family,
        relationships
    WHERE
        family.personId = relationships.personId
        AND relationships.relation = 'father'
    

    Without digging through the WHERE clause, it is impossible to say what links
    the two tables.

    Better:

    SELECT *
    FROM
        family
        JOIN relationships ON (family.personId = relationships.personId)
    WHERE
        relationships.relation = 'father'
    

    The relation between the tables is immediately obvious. The WHERE clause is
    left to limit rows in the result set.

    Compliance with such a restriction negates the use of the comma operator to
    join tables. It is a small price to pay. Queries should be written using the
    explicit JOIN keyword anyway, and the two should never be mixed (unless you
    like rewriting all your queries every time a new version changes operator
    precedence).

    Finding Syntax Errors

    Syntax errors are among the easiest problems to solve. MariaDB provides an error
    message showing the exact point where the parser became confused. Check the
    query, including a few words before the phrase shown in the error message. Most
    syntax and parsing errors are obvious after a second look, but some are more
    elusive, especially when the error text seems empty, points to a valid keyword,
    or seems to error on syntax that appears exactly correct.

    Interpreting the Empty Error

    Most syntax errors are easy to interpret. The error generally details the exact
    source of the trouble. A careful look at the query, with the error message in
    mind, often reveals an obvious mistake, such as mispelled field names, a
    missing ‘AND’, or an extra closing parenthesis. Sometimes the error is a little
    less helpful. A frequent, less-than-helpful message:

    ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your
    MariaDB server version for the right syntax to use near ' ' at line 1
    

    The empty ‘ ‘ can be disheartening. Clearly there is an error, but where? A
    good place to look is at the end of the query. The ‘ ‘ suggests that the parser
    reached the end of the statement while still expecting some syntax token to
    appear.

    Check for missing closers, such as ‘ and ):

    SELECT * FROM someTable WHERE field = 'value
    

    Look for incomplete clauses, often indicated by an exposed comma:

    SELECT * FROM someTable WHERE field = 1 GROUP BY id,
    

    Checking for keywords

    MariaDB allows table and field names and aliases that are also reserved words. To prevent ambiguity, such names must be enclosed in backticks (`):

    SELECT * FROM actionTable WHERE `DELETE` = 1;
    

    If the syntax error is shown near one of your identifiers, check if it appears
    on the reserved word list.

    A text editor with color highlighting for SQL syntax helps to find these
    errors. When you enter a field name, and it shows up in the same color as the
    SELECT keyword, you know something is amiss. Some common culprits:

    • DESC is a common abbreviation for «description» fields. It means «descending»
      in a MariaDB ORDER clause.
    • DATE, TIME, and TIMESTAMP are all common field names. They are
      also field types.
    • ORDER appears in sales applications. MariaDB uses it to specify sorting for
      results.

    Some keywords are so common that MariaDB makes a special allowance to use them
    unquoted. My advice: don’t. If it’s a keyword, quote it.

    Version specific syntax

    As MariaDB adds new features, the syntax must change to support them. Most of the
    time, old syntax will work in newer versions of MariaDB. One notable exception is
    the change in precedence of the comma operator relative to the JOIN keyword in
    version 5.0. A query that used to work, such as

    SELECT * FROM a, b JOIN c ON a.x = c.x;
    

    will now fail.

    More common, however, is an attempt to use new syntax in an old version. Web
    hosting companies are notoriously slow to upgrade MariaDB, and you may find
    yourself using a version several years out of date. The result can be very
    frustrating when a query that executes flawlessly on your own workstation,
    running a recent installation, fails completely in your production environment.

    This query fails in any version of MySQL prior to 4.1, when subqueries were
    added to the server:

    SELECT * FROM someTable WHERE someId IN (SELECT id FROM someLookupTable);
    

    This query fails in some early versions of MySQL, because the JOIN syntax did
    not originally allow an ON clause:

    SELECT * FROM tableA JOIN tableB ON tableA.x = tableB.y;
    

    Always check the installed version of MariaDB, and read the section of the manual
    relevant for that version. The manual usually indicates exactly when particular
    syntax became available for use.

    Дата: 25.11.2013

    Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

    Статья ориентирована на новичков. В ней объясняется, что означает ошибка сервера MySQL №1064, рассматриваются типичные ситуации и причины возникновения этой ошибки, а также даются рекомендации по исправлению.

    Рассмотрим простейший пример.

    SELECT mid, time, title, artist, download, view_count, rating, vote_num FROM dle_mservice WHERE category = ‘1’ AND approve = ‘1’ ORDER BY time DESC LIMIT -10,10;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-10,10’ at line 1

    Сервер MySQL сообщает, что в первой строке нашего SQL запроса имеется синтаксическая ошибка, и в одинарных кавычках цитирует часть запроса с того места где начинается ошибка. Это очень полезное свойство, так как позволяет сразу определить место, которое сервер счел ошибочным. В данном случае это ‘-10,10’, ошибка возникает из-за того, что параметр LIMIT не может быть отрицательным числом.

    Однако, бывает и так, что цитируемый кусок запроса не содержит синтаксической ошибки. Это означает, что данная часть запроса находится не на своем месте из-за чего весь запрос становится синтаксически неверным. Например, отсутствует разделитель между двумя запросами, пропущен кусок запроса, невидимый символ в дампе и т.д. Неудобством таких ситуаций является то, что сообщение об ошибке не содержит исходный запрос.
    Действия по исправлению зависят от контекста возникновения ошибки. Таковых всего 3:

    1. Запрос в редакторе.

    Самый простейший случай — вы пишите свой запрос в редакторе. Если причина не опечатка, то:

    • Смотреть в документации синтаксис команды для вашей версии сервера MySQL.

      Обратите внимание: речь идет о версии сервера MySQL, а не клиента (phpmyadmin, workbench и т.д.). Версию сервера можно узнать выполнив команду select version();

    • В MySQL допускается использование ключевых слов в качестве имен столбцов/таблиц, но при этом их необходимо заключать в обратные кавычки (там где буква ё на клавиатуре).
      Пример:

      select order from test;
      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘order from test’ at line 1
      MariaDB [test]> select `order` from test;
      +——-+
      | order |
      +——-+
      |  NULL |
      +——-+

    • По умолчанию ; разделяет команды. Если же нужно выполнить набор из нескольких инструкций как одну команду (например, при создании процедур, фунуций, триггеров), то в зависимости от используемого клиента может потребоваться переопределить разделитель с помощью DELIMITER, иначе интерпретация команды остановится на первой ; и будет ошибка синтаксиса. Пример:

      delimiter //
      create procedure test()
      begin
      set @a=1;
      select @a;
      end//

      Обратите внимание: DELIMITER это команда консольного клиента mysql, необходимость его использования зависит от того как вы передаете команду серверу. Например,:

      • mysql_query() выполняет содержимое как одну команду, добавление delimiter приведет к error 1064 с цитатой, начинающейся со слова delimiter
      • phpmyadmin удаляет слово delimiter из-за чего возникает error 1064 с цитатой, начинающейся с переопределенного разделителя
      • в MysqlQueryBrowser напротив необходимо использовать delimiter.

    2. Перенос базы на другой сервер.

    У вас есть дамп (т.е. файл с расширением .sql) и при попытке его импортировать вы получаете ошибку 1064. Причины:

    • В различных версиях набор ключевых слов и синтаксис может немного отличаться. Наиболее распространенный случай: команда create table, в которой ключевое слово type было заменено на engine. Например, если вы получаете ошибку:

      You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘TYPE=MyISAM CHARACTER SET `utf8`’ at line 29

      Это означает, что вы переносите базу в пятую версию сервера MySQL, в котором ключевое слово TYPE не поддерживается и его нужно заменить на ENGINE.

      Редко бываю случаи, когда перенос идет на старый (~3.23) сервер, который кодировки не поддерживает. Тогда ошибка будет иметь вид:

      #1064 — You have an error in your SQL syntax near ‘DEFAULT CHARACTER SET cp1251 COLLATE cp1251_general_ci’ at line 1

      Такое может произойти, если вы переносите базу с хостинга на локальный комп, где стоит древняя версия MySQL. Лучшим решением в данном случае будет не править дамп, а обновить MySQL.

    • Часто проблемы вызваны тем, что дамп делается неродными средствами MySQL (например, phpmyadmin) из-за чего в нем могут быть BOM-маркер, собственный синтаксис комментариев, завершения команды и т.д. Кроме того при использовании того же phpmyadmin возможна ситуация при которой из-за ограничения апача на размер передаваемого файла команда будет обрезана, что приведет к ошибке 1064.
      Например, если вы получаете ошибку:

      #1064 — You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘
      CREATE TABLE `jos_banner` (
        `bid` int(11) NOT NULL auto_increment,
        `ci‘ at line 1

      Значит ваш дамп содержит BOM-маркер. Это три байта в начале файла, помогающие программе определить что данный файл сохранен в кодировке UTF-8. Проблема в том, что MySQL пытается интерпретировать их как команду из-за чего возникает ошибка синтаксиса. Нужно открыть дамп в текстовом редакторе (например, Notepad++) и сохранить без BOM.

      Для избежания подобных проблем при создании дампа и его импорте лучше пользоваться родными средствами MySQL, см http://sqlinfo.ru/forum/viewtopic.php?id=583

    3. Некорректная работа сайта.

    Если во время работы сайта появляются ошибки синтаксиса, то, как правило, причина в установке вами сомнительных модулей к вашей cms. Лучшее решение — отказаться от их использования. Еще лучше предварительно проверять их работу на резервной копии.

    Пример. Движок dle 7.2, поставили модуль ,вроде бы все Ок, но:

    MySQL Error!
    ————————
    The Error returned was:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘AND approve=’1‘ AND date < ‘2008-10-04 04:34:25‘ LIMIT 5’ at line 1

    Error Number:
    1064
    SELECT id, title, date, category, alt_name, flag FROM dle_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘Приобретение и оплата скрипта ‘) AND id !=  AND approve=‘1’ AND date < ‘2008-10-04 04:34:25’ LIMIT 5

    В данном примере мы видим, что причина ошибки в отсутствии значения после «id != «

    Обратите внимание: из процитированного сервером MySQL куска запроса причина ошибки не ясна. Если ваша CMS не показывает весь запрос целиком, то нужно в скриптах найти место где выполняется данный запрос и вывести его на экран командой echo.

    Кусок кода, который отвечает за данный запрос это

    $db->query («SELECT id, title, date, category, alt_name, flag FROM « . PREFIX . «_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘$body’) AND id != «.$row[‘id’].» AND approve=’1′».$where_date.» LIMIT «.$config[‘related_number’]);

    Далее можно искать откуда взялась переменная $row и почему в ней нет элемента ‘id’ и вносить исправления, но лучше отказаться от использования такого модуля (неизвестно сколько сюрпризов он еще принесет).

    P.S. Если после прочтения статьи ваш вопрос с MySQL Error 1064 остался нерешенным, то задавайте его на форуме SQLinfo

    Дата публикации: 25.11.2013

    © Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

    Понравилась статья? Поделить с друзьями:
  • Use of important ошибка
  • Use error boundary
  • Use config tab is locked cisco как исправить
  • Usdownloader плагин вернул ошибку gdl error
  • Usd error что это значит