Ошибка 1064 mysql workbench как исправить

I created this using MySQL WorkBench

CREATE  TABLE IF NOT EXISTS `bakasura_new`.`cities` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(255) NOT NULL COMMENT 'City Name' ,
  `short_name` VARCHAR(255) NOT NULL COMMENT 'Short Name' ,
  `country_id` INT(11) UNSIGNED NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_cities_countries` (`country_id` ASC) ,
ENGINE = InnoDB;

I am getting this error

MySQL said: Documentation

#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 ‘= InnoDB’ at line 8

Community's user avatar

asked Sep 26, 2010 at 10:30

Harsha M V's user avatar

Harsha M VHarsha M V

54.1k125 gold badges354 silver badges529 bronze badges

You have a dangling comma here:

INDEX `fk_cities_countries` (`country_id` ASC) ,

And you also have a missing parenthesis at the end:

CREATE  TABLE IF NOT EXISTS `bakasura_new`.`cities` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(255) NOT NULL COMMENT 'City Name' ,
  `short_name` VARCHAR(255) NOT NULL COMMENT 'Short Name' ,
  `country_id` INT(11) UNSIGNED NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_cities_countries` (`country_id` ASC)
) ENGINE = InnoDB;

answered Sep 26, 2010 at 10:31

Daniel Vassallo's user avatar

Daniel VassalloDaniel Vassallo

338k72 gold badges505 silver badges443 bronze badges

1

There is a ) missing at the end of the last )

INDEX `fk_cities_countries` (`country_id` ASC) )

answered Sep 26, 2010 at 10:33

DrColossos's user avatar

7

Have you ever encountered an SQL error 1064 while trying to execute a query? It can be frustrating, but don’t worry – you’re not alone. This error message typically marks a syntax error in your MySQL query.

Fortunately, there are only a handful of problems triggering that error. You can efficiently resolve them with a bit of persistence and proper guidance. In this article, we’ll explain what SQL Error 1064 is, what causes it, and how to resolve it. Plus, you’ll learn three tips to avoid it in the future.

What is SQL Error 1064?

SQL Error code 1064 represents a SQL syntax error. It means that the SQL query you’ve written isn’t valid because it contains a mistake in the syntax. In other words, MySQL doesn’t understand your request and returns the error in response.

You will likely see the SQL error code 1064 in a database administration tool like phpMyAdmin or MySQL Workbench. SiteGround users have phpMyAdmin at their disposal in Site Tools > Site > MySQL > PHPMYADMIN > ACCESS PHPMYADMIN.

How to access phpMyAdmin from the MySQL section in Site Tools

Below, you can see a screenshot of phpMyAdmin producing the error.

SQL Error 1064 in phpMyAdmin

There are several variants of the error message:

  • error 1064 (42000) – you have an error in your SQL syntax
  • #1064 – you have an error in your SQL syntax

This error message looks daunting, especially if you’re new to SQL. However, it’s essential to remember that syntax errors are common, and with some practice, you can learn to avoid them.

Understanding SQL Syntax

SQL syntax is a crucial aspect of database management. You can create, modify, and retrieve data from databases using correctly structured SQL commands.

SQL syntax is a set of rules that determine the structure of commands used to interact with a database. SQL commands include the following elements:

  • operators,
  • clauses,
  • expressions,
  • keywords.

The SQL syntax is similar to many other programming languages. While SQL keywords are not case-sensitive, writing them in uppercase is standard practice. SQL statements are typically separated by semicolons.

Familiarizing yourself with the MySQL Reference Manual is essential for working with a MySQL database. You will get a better understanding of the syntax, which in turn will help you avoid syntax errors in SQL queries.

What Causes SQL Error 1064?

As the description suggests, the main reason for the SQL error 1064 is a syntax error in your command. However, other problems can trigger the error, as well. Below, you’ll find a list of the most common ones.

  • Syntax errors – The most common cause of SQL Error 1064. Syntax errors occur when the SQL statement is miswritten or violates the established syntax rules.
  • Obsolete commands – Using outdated and deprecated commands or commands no longer supported in the current version of SQL.
  • Using reserved words out of context – Reserved words are words already used by the SQL language for specific purposes. Examples are SELECT, INSERT, UPDATE, ALTER, DELETE, etc. If you use reserved words for a purpose outside of their designated use in your SQL code, you will encounter SQL Error 1064.
  • Incorrect data types – Using incorrect data types in the SQL statement. Inserting text into a numeric field is a typical example.
  • Missing data – If you try to insert or update data in a database missing a required field, the result could be an SQL error 1064.

How to Fix SQL Error 1064

The SQL syntax error can originate from various issues. Here is an order you can follow to find the source of the problem and solve it.

  • Step 1.Read the Error Message Carefully

    When encountering an SQL Error 1064, read the error message carefully. It will indicate which line or section of the SQL statement contains a mistake.

    Below is an example of phpMyAdmin producing the error and pointing out which part is problematic.

    Check the message for the SQL error 1064

  • Step 2.Check Your MySQL Query for Syntax Errors

    Once you’ve identified the part of the SQL statement causing the error, check the SQL code for syntax errors. Look for missing brackets, commas, or misspelled operators, clauses, expressions, or keywords.

    The example from the previous step shows that the problematic part of the SQL command is:

    ''WERE `fpj_options`.`option_id` = 1' at line 1

    Looking closely at the line, it becomes clear that the issue comes from the misspelled “WERE” clause. Its proper form is “WHERE” so the missing “H” triggered the error. Correcting the clause results in a successful execution of the SQL command.

    Successful execution of SQL query after correcting a syntax error

  • Step 3.Check If You Are Using Reserved Words

    If you are using MySQL and receive an error message with the code 1064, it may be because you used words that MySQL considers special. These are called “reserved words,” and examples are ALTER, TABLE, SELECT, etc.

    Reserved words have specific meanings in MySQL. You can’t use them as names for tables, columns, or other parts of a MySQL database without causing errors. Below is an example of the SQL syntax error caused by using the reserved word alter as a table name.

    SQL error 1064 caused by using the reserved word "alter"

    To prevent this error, check for any reserved words used out of place in your queries. You can find a complete list of these words in the MySQL manual. If you use a reserved word, change it to something else.

    If you prefer to use the reserved word, surround it with backticks (`). These backticks will instruct MySQL to treat it as a name and not a reserved word.

    Fixing the SQL error 1064 by using backticks on the reserved word "alter"

  • Step 4.Replace Obsolete Commands

    MySQL has undergone several revisions and changes over the years. Some of these changes have affected the SQL syntax rules. Many of the commands have been abandoned and replaced by new ones.

    You can check the MySQL server version you are using in phpMyAdmin. For more information, read this guide on how to check the MySQL version on the server hosting your account.

    If you’ve identified that you’re using obsolete commands or no longer supported ones, replace them with up-to-date commands.

    For editing outdated commands in files, you can save time by using find and replace tools in your File manager. They can replace all the commands causing the issue with the correct new versions in one go.

    The File Manager in Site Tools offers this functionality for SiteGround users. Open the file you wish to edit, and press the button Replace.

    "Replace" function in File Manager to replace obsolete commands

    In the Find field, type the obsolete command that needs to be updated. In Replace, write the updated command to replace the old one. The tool will rewrite all instances of the outdated command with the new one.

    IMPORTANT! The new SQL command may not work as expected. Before making changes to the file, create a website backup. It will allow you to restore your website quickly in case the changes affect it negatively.

  • Step 5.Check If You Are Using the Correct Data Type

    SQL databases are designed to store various data types. Each has its own specific format and storage requirements. For example, a numeric value requires a different amount of storage space than a string value.

    If you are trying to insert data of one type into a column of another type, you will encounter SQL Error 1064. This error message is usually accompanied by “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…”.

    For instance, if you insert a text string into a column defined as a numeric value, you will get SQL Error 1064.

    Wrong data type causing the SQL error 1064

    To avoid this database error, ensure that the data types of the columns in your SQL code match the data types of the values you are inserting.

  • Step 6.Add Missing Data

    Another common cause of SQL Error 1064 is missing data. For example, if you try to insert data into a table with mandatory fields but leave some fields empty, you will get an SQL Error 1064.

    To fix this error, ensure you have provided all the required data. You may have to add the missing data manually.

    Furthermore, the error may appear when importing your database from a corrupted backup file. Create a new backup of your original database and import it on the new server again.

    SiteGround users can take advantage of the tool Import Database Dump, designed for importing larger databases.

    Use "Import Database Dump" in Site Tools to import large databases

    If unsure about the mandatory fields, check the table definition or consult the database administrator.

  • Step 7.Seek Assistance

    If you have tried all the above steps and still can’t fix SQL Error 1064, try finding help.

    You can contact the database administrator or consult an online forum or community dedicated to SQL programming.

    Many online resources are available for beginners and experienced programmers alike, and you can find answers to most SQL-related questions. You can find helpful information in the official MySQL forum, where users aid each other with more elaborate problems and share their experiences.

3 Tips to Avoid SQL Error 1064

You can prevent SQL Error 1064 by following good practices that reduce the chance of making a syntax error.

Use an SQL Validator to Detect a Syntax Error

An SQL validator is a tool that checks the syntax of your SQL code and identifies errors. Using it lets you catch and fix errors early before executing the code.

EverSQL is one of the most popular free SQL validator tools. Submit your SQL query and press the button Validate SQL Syntax. The checker will inspect the code and point out potential mistakes in the MySQL queries.

EverSQL SQL validator tool

Use SQL Aliases

SQL aliases allow you to assign a temporary name to a table or column. Using aliases, you can simplify your SQL code and avoid syntax errors caused by typos or ambiguities. Note that the SQL alias remains active only for the duration of the SQL query.

The clause AS enables an alias for a table or column. To assign an alias for a column, use the following template.

SELECT column_name AS alias_name
FROM table_name;

For assigning an alias to a table, use the format below.

SELECT column_name(s)
FROM table_name AS alias_name;

Replace column_name and table_name with the existing names in your database and alias_name – with your chosen custom alias.

Break Down SQL Statements

Breaking down complex SQL statements into smaller, manageable parts can help you easily identify errors. By testing smaller parts of your SQL code, you can isolate and fix errors before they cause significant problems.

Conclusion

SQL Error 1064 is a common error encountered by SQL programmers. Syntax errors, obsolete commands, incorrect data types, missing data, or other mistakes in the SQL code usually cause this error.

By following the steps outlined in this guide and implementing the tips to prevent MySQL Error 1064, you can avoid it and ensure your SQL code runs smoothly. Remember to always check for syntax errors and seek assistance when needed.

When issuing a command to MySQL, I’m getting error #1064 «syntax error».

  1. What does it mean?

  2. How can I fix it?

asked May 7, 2014 at 10:32

eggyal's user avatar

TL;DR

Error #1064 means that MySQL can’t understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn’t a reserved word (and, if it is, ensure that it’s properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they’re (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this «syntax» of which you speak? Is it witchcraft?

      Whilst «syntax» is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article «a» must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is «parse» that command in order to make sense of it. A «syntax error» means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It’s important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL’s grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      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 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn’t expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you’ll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we «check the manual that corresponds to our MySQL version for the right syntax to use«. Let’s do that.

      I’m using MySQL v5.6, so I’ll turn to that version’s manual entry for an UPDATE command. The very first thing on the page is the command’s grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it’s enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual’s description of what was expected at that point), virtually every syntax error can be readily identified.

    I say «virtually all», because there’s a small class of problems that aren’t quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn’t intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

3

It is late but will help others and ofcourse will save time :)
My query was working in MySQL 5.7 in local system but on live we have version MySQL 8 and query stop working.

Query:

SELECT t.*
FROM groups t
ORDER BY t.id DESC
LIMIT 10 OFFSET 0

Output in MySQL 8:

Error in query (1064): Syntax error near ‘groups t ORDER BY t.id DESC’
at line …

I came to know groups is reserved word so I have to wrap groups with « quotes or change the table name to solve this issue.

answered Jul 18, 2021 at 13:13

Muhammad Shahzad's user avatar

Muhammad ShahzadMuhammad Shahzad

9,34821 gold badges86 silver badges130 bronze badges

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can’t figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

answered Apr 19, 2017 at 10:54

Umair Malhi's user avatar

Umair MalhiUmair Malhi

5651 gold badge5 silver badges16 bronze badges

3

Read time 5 minutes

At first, the syntax errors seem very tedious and cryptic while working with SQL database programs. But, at a closer glance, one can easily understand the errors as they are descriptive enough about the problem that finding possible solutions becomes a step easier. Every error code has a unique 4 digits number that determines the type of error. One such SQL error code is Error: 1064 which occurs due to wrongly typed syntax of SQL queries. Let’s dig deep to know more about this error and how to fix it.

The error message with error code 1064 occurs due to the incorrect syntax of MySQL queries. In simple words, MySQL does not understand the commands that you have written. The commands are mistyped or misspelled within the MySQL environment which the database does not recognize. Say for example UPDATE is typed as UPADTE. Also, don’t get confused between syntax error and grammar error, because grammar rules are valid for a syntax error. The parser disagrees to understand the command and fails to perform a task.

Reasons for MySQL Syntax Error: 1064

The possible reasons due to which MySQL faces syntax error – 1064 are mentioned here:

  • It can occur due to mistyping the spelling of command.
  • The error can take place due to the use of outdated or depreciated commands.
  • It may happen when the specific data required by the query goes missing.
  • Due to wrong reserved words typed as they vary from version to version in MySQL.
  • This occurs due to a mistake in the spelling of the command resulting in MySQL not being able to understand it.
  • The error can take place due to the use of outdated or obsolete commands which are no longer in function.
  • It may happen when some data goes missing in the written database.
  • Due to wrong reserved words typed as they vary from version to version in MySQL. Reserve words are used for specific context only.

Instant Solution

Avail the fastest solution Kernel for MySQL Database recovery to fix SQL Syntax Error 1064. This software can quickly resolve problems related to MySQL Database.

How to Resolve Syntax Error: 1064?

When any MySQL error occurs, it indicates the problem along with a description and the way to fix it. Hence, for different syntax errors, it shows different fix solutions. Some of them are mentioned here, follow them according to the syntax error that is troubling you:

Fix 1: Mistyped Commands

The foremost reason due to which 1064 error occurs when you type incorrect spelling of a command or typos.

Example: UDPATE table emp set id = 0;
The UPDATE command is mistyped.

Solution to Fix

To fix the spelling errors mistyped commands and typos you must recheck before executing them. In case, you are unable to recall the correct syntax; we advise you to refer MySQL Manual and search for the syntax for the version you’re using. The error will get resolved if you replace all the typos and mistyped commands with the correct syntax.

You can also try IDEs and MySQL tools that help you with MySQL syntax errors by highlighting or pop-up alerts when you execute the query. If the IDE that you installed is lacking the feature of detecting syntax errors, look for a plugin that is designed for this purpose to debug the issue.

Fix 2: Reserved Words

Reserved words vary from one MySQL version to another as every version has its list of keywords that are reserved. The reserved words are for performing a specific task and are used for different purposes in the MySQL database engine. The error 1064 might pop up in cases when you are not using the right keyword meant for serving the specific function, or the version of MySQL is not meeting the exact requirements for using the particular keyword.

For example, Create Table alter (name, id);

Here, alter is a reserved word, but it cannot be used as it needs some special requirements. Let’s know how to use a reserved keyword in a query.

Solution to Fix

To use alter in MySQL query as you need to fulfill the unique requirements to call the functionality of the alter command, you cannot use it as mentioned above. You need to enclose the alter word with backticks (`), present on your keyboard just above the Tab button.`

For example: Create Table `alter` (name, id);

Fix 3: Missing Data

At times, the relevant data goes missing from the database which is required for the execution of a query. Hence, leading to 1064 error when the data is not found in the database.

For example: Select * from students where studentID = $id

Suppose if the $id not correctly filled, the above query for the server is like this:

Select * from students where studentID =
That is the reason the server pops up error 1064 because it gets confused.
Solution to Fix

You can enter the missing data using the dashboard interface of the application, which is usually done through phpMyAdmin or MySQL Workbench. The applications allow you to bring up the record and add the missing data manually to an appropriate row of the table.

Recommended: Automated Solution to Fix MySQL Database Errors

At times, the error 1064 becomes a bit tricky to resolve as it might occur due to the corruption of database files, i.e., MyIASM, .cnf, .ddl, .arm, etc. If that is the case, then you must use the professional automated solution to recover and restore database files of any MySQL server version. The best-recommended solution is the Kernel for MySQL Database recovery. The solution is highly efficient and works immediately to resolve problems caused by MySQL database files.

Concluding Words

The error 1064 seems simple to remove if you are aware of the exact cause behind the error. The manual solution may not work correctly if you do not use the correct steps to eliminate the error. You should use Kernel SQL Database Recovery software to handle each kind of error, whether physical or logical. The software will recover the complete databases with their tables, relationships, and dependencies.

If you’ve been using WordPress for a while, you may have decided to get into more advanced database management. This often involves using the MySQL command line, which can, in turn, lead to confusing problems such as MySQL 1064 errors.

Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.

In this post, we’ll cover the various possible causes of the MySQL 1064 error. Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.

Let’s get started!

Why the MySQL 1064 Error Occurs

The MySQL 1064 error is a syntax error. This means the reason there’s a problem is because MySQL doesn’t understand what you’re asking it to do. However, there are many different situations that can lead to this type of miscommunication between you and your database.

The simplest cause is that you’ve made a mistake while typing in a command and MySQL can’t understand your request. Alternatively, you may be attempting to use outdated or even obsolete commands that can’t be read.

In other cases, you may have attempted to include a ‘reserved word’ in one of your commands. Reserved words are terms that can only be used in specific contexts in MySQL. If you attempt to use them in other ways, you’ll be faced with an error.

It’s also possible that there is some data missing from your database. When you make a request via MySQL which references data that isn’t where it’s supposed to be, you’ll also see the 1064 error. Finally, transferring your WordPress database to another server can also lead to the same issue.

As you can see, there are many potential causes for this problem, which can make it tricky to resolve. Unless you’re in the process of moving your database or taking some other action that points to a specific cause, you’ll likely need to try a few different solutions before you land on the right one. Fortunately, none of them are too difficult to execute, as we’ll see next.

Oh no, you’re getting the MySQL 1064 Error…😭 Don’t despair! Here are 5 proven solutions to get it fixed immediately 🙏Click to Tweet

How to Fix the MySQL 1064 Error (5 Methods)

If you already have an idea of what’s causing your MySQL 1064 error, you can simply skip down to the resolution for your specific situation. However, if you’re not sure why the error has occurred, the simplest strategy is to try the easiest solution first.

In that case, we’d suggest testing out the five most likely fixes in the following order.

1. Correct Mistyped Commands

The good thing about MySQL typos is that they’re the simplest explanation for syntax issues such as the 1064 error. Unfortunately, they can also be the most tedious to correct. Generally speaking, your best option is to manually proofread your code and look for any mistakes you may have made.

We suggest using the MySQL Manual as a reference while you do so, double-checking anything you’re not sure about. As you might imagine, this can get pretty time-consuming, especially if you’ve been working in the MySQL command line for a while or if you’re new to this task.

An alternative to manually checking your work is to employ a tool such as EverSQL:

MySQL 1064 Error: EverSQL syntax checker

EverSQL syntax checker

With this solution, you can simply input your MySQL to check for errors automatically. However, keep in mind that these platforms aren’t always perfect and you may still want to validate the results yourself.

2. Replace Obsolete Commands

As platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. MySQL is no exception. If you’re working on your database following a recent update or have referenced an outdated source during your work, it’s possible that one or more of your commands are no longer valid.

You can check to see whether this is the case using the MySQL Reference Manual. You’ll find mentions of commands that have been made obsolete by each MySQL version in the relevant sections:

MySQL 1064 Error: Manually removing obsolete commands

Manually removing obsolete commands

Once you’ve determined which command is likely causing the problem, you can simply use the ‘find and replace’ function to remove the obsolete command and add in the new version. For example, if you were using storage_engine and find that it no longer works, you could simply replace all instances with the new default_storage_engine command.

3. Designate Reserved Words

In MySQL, using a reserved word out of context will result in a syntax error, as it will be interpreted as incorrect. However, you can still use reserved words however you please by containing them within backticks, like this: `select`

Each version of MySQL has its own reserved words, which you can read up on in the MySQL Reference Manual. A quick find and replace should enable you to resolve this issue if you think it may be causing your 1064 error.

4. Add Missing Data

If your latest MySQL query attempts to reference information in a database and can’t find it, you’re obviously going to run into problems. In the event that none of the preceding solutions resolves your MySQL 1064 error, it may be time to go looking for missing data.

Unfortunately, this is another solution that can be quite tedious and has to be done by hand. The best thing you can do in this situation is to work backward, starting with your most recent query. Check each database it references, and make sure all the correct information is present. Then move on to the next most recent query, until you come to the one that’s missing some data.

5. Use Compatibility Mode to Transfer WordPress Databases

This final 1064 error solution isn’t as straightforward as the others on our list. However, if you’re migrating your WordPress site to a new host or otherwise moving it to a different server, you’ll need to take extra steps to avoid causing problems with your database.

The simplest solution is to use a migration plugin that includes a compatibility mode, such as WP Migrate DB:

WP Migrate DB WordPress plugin

WP Migrate DB WordPress plugin

This will enable an auto-detection feature that will make sure your latest site backup and database are compatible with multiple versions of MySQL. You can access the compatibility mode setting by navigating to Tools > Migrate DB > Advanced Options:

WP Migrate DB settings

WP Migrate DB settings

Check the box next to Compatible with older versions of MySQL before starting your site migration. This way, you should be able to avoid any issues during the process.

Summary

Database errors can throw a wrench in your plans, and may even compromise your website’s stability. Knowing how to resolve issues such as the MySQL 1064 error can help you react quickly, and minimize downtime on your site.

There are five methods you can try to fix the MySQL 1064 error when you encounter it, depending on its most likely cause:

  1. Correct mistyped commands.
  2. Replace obsolete commands.
  3. Designate reserved words.
  4. Add missing data.
  5. Transfer WordPress databases in compatibility mode.

So I have an error, when I want to add a foreign key. I added the foreign key in MySQL Workbench with an EER Diagram Model. The lines workbench tries to add are:`

CREATE SCHEMA IF NOT EXISTS `barberDB` DEFAULT CHARACTER SET latin1 ;
USE `barberDB` ;

-- -----------------------------------------------------
-- Table `barberDB`.`BARBER`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `barberDB`.`BARBER` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `barberDB`.`CUSTOMER`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `barberDB`.`CUSTOMER` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `isHaircut` INT NULL,
  `isBeard` INT NULL,
  `isEyebrows` INT NULL,
  `BARBER_ID` INT NOT NULL,
  PRIMARY KEY (`ID`),
  INDEX `fk_CUSTOMER_BARBER_idx` (`BARBER_ID` ASC) VISIBLE,
  CONSTRAINT `fk_CUSTOMER_BARBER`
    FOREIGN KEY (`BARBER_ID`)
    REFERENCES `barberDB`.`BARBER` (`ID`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

The error I get is:

ERROR: Error 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 'VISIBLE,
  CONSTRAINT `fk_CUSTOMER_BARBER`
    FOREIGN KEY (`BARBER_ID`)
    REF' at line 12
SQL Code:
        -- -----------------------------------------------------
        -- Table `barberDB`.`CUSTOMER`
        -- -----------------------------------------------------
        CREATE TABLE IF NOT EXISTS `barberDB`.`CUSTOMER` (
          `ID` INT NOT NULL AUTO_INCREMENT,
          `name` VARCHAR(45) NULL,
          `isHaircut` INT NULL,
          `isBeard` INT NULL,
          `isEyebrows` INT NULL,
          `BARBER_ID` INT NOT NULL,
          PRIMARY KEY (`ID`),
          INDEX `fk_CUSTOMER_BARBER_idx` (`BARBER_ID` ASC) VISIBLE,
          CONSTRAINT `fk_CUSTOMER_BARBER`
            FOREIGN KEY (`BARBER_ID`)
            REFERENCES `barberDB`.`BARBER` (`ID`)
            ON DELETE CASCADE
            ON UPDATE CASCADE)
        ENGINE = InnoDB

SQL script execution finished: statements: 6 succeeded, 1 failed

Fetching back view definitions in final form.
Nothing to fetch

I searched for solutions and find that parenthesis are important or backticks, but since the code is created by the tool, it seems correct to me.
What could cause the error?

Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

I have a problem with my database. I have created the model and now I want to sync it with my database on my WAMP Server (local) but it keeps giving me an error. I searched for the cause of the error for several days. Since I cannot find the problem, I’ve decided to share it with you.

Message log:

Executing SQL script in server

ERROR: Error 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 ') NULL DEFAULT NULL , n_category VARCHAR(45) NULL DEFAULT NULL ,    
PRIMARY K' at line 3
CREATE TABLE IF NOT EXISTS `telo2p`.`d_category` 
(
  `idd_category` INT(11) NOT NULL AUTO_INCREMENT,
  `f_sells` DOUBLE(11) NULL DEFAULT NULL,
  `n_category` VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (`idd_category`) 
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci

SQL script execution finished: statements: 6 succeeded, 1 failed

http://img855.imageshack.us/img855/4855/21725619.png

Any advice about what I am doing wrong here?

Step 1 – Solve Mysql Workbench Error Code 1064

Is Mysql Workbench Error Code 1064 appearing? Would you like to safely and quickly eliminate Mysql Workbench Error which additionally can lead to a blue screen of death?

When you manually edit your Windows Registry trying to take away the invalid mysql workbench error code 1175 keys you’re taking a authentic chance. Unless you’ve got been adequately trained and experienced you’re in danger of disabling your computer system from working at all. You could bring about irreversible injury to your whole operating system. As very little as just 1 misplaced comma can preserve your Pc from even booting every one of the way by!

Troubleshooting mysql workbench error code 1215 Windows XP, Vista, 7, 8 & 10

Simply because this chance is so higher, we hugely suggest that you make use of a trusted registry cleaner plan like CCleaner (Microsoft Gold Partner Licensed). This system will scan and then fix any Mysql Workbench Error Code 1064 complications.

Registry cleaners automate the entire procedure of finding invalid registry entries and missing file references (including the Code error) likewise as any broken hyperlinks inside of your registry.

Issue with mysql workbench error code 2013

Backups are made immediately prior to each and every scan providing you with the choice of undoing any changes with just one click. This protects you against doable damaging your pc. Another advantage to these registry cleaners is that repaired registry errors will strengthen the speed and performance of one’s procedure drastically.

  • http://stackoverflow.com/questions/32039828/mysql-workbench-error-1064
  • http://forums.mysql.com/read.php?10,506979
  • http://www.inmotionhosting.com/support/website/database-troubleshooting/error-1064
  • http://stackoverflow.com/questions/16700725/mysql-error-1064-mysql-workbench

Cautionary Note: Yet again, for those who are not an state-of-the-art consumer it’s very encouraged that you simply refrain from editing your Windows Registry manually. If you make even the smallest error within the Registry Editor it can result in you some serious issues that may even call for a brand new set up of Windows. Not all difficulties attributable to incorrect Registry Editor use are solvable.

Fixed: mysql workbench error code 1005

Symptoms of Mysql Workbench Error Code 1064
“Mysql Workbench Error Code 1064” appears and crashes the energetic method window.
Your Personal computer routinely crashes with Mysql Workbench Error Code 1064 when running the exact same system.
“Mysql Workbench Error Code 1064” is shown.
Windows operates sluggishly and responds little by little to mouse or keyboard input.
Your computer periodically “freezes” for the number of seconds in a time.

Will cause of Mysql Workbench Error Code 1064

Corrupt obtain or incomplete set up of Windows Operating System software program.

Corruption in Windows registry from a new Windows Operating System-related application adjust (install or uninstall).

Virus or malware infection which has corrupted Windows method documents or Windows Operating System-related application data files.

Another method maliciously or mistakenly deleted Windows Operating System-related files.

Mistakes this sort of as “Mysql Workbench Error Code 1064” can be brought about by several different elements, so it really is important that you troubleshoot every of the achievable brings about to forestall it from recurring.

Simply click the beginning button.
Variety “command” inside the lookup box… Will not hit ENTER nonetheless!
Although keeping CTRL-Shift in your keyboard, hit ENTER.
You’re going to be prompted that has a authorization dialog box.
Click on Of course.
A black box will open having a blinking cursor.
Variety “regedit” and hit ENTER.
Within the Registry Editor, choose the mysql workbench error code 1175 connected key (eg. Windows Operating System) you wish to back again up.
Within the File menu, choose Export.
Inside the Preserve In list, pick out the folder in which you wish to save the Windows Operating System backup key.
Inside the File Title box, sort a reputation for the backup file, these types of as “Windows Operating System Backup”.
From the Export Vary box, ensure that “Selected branch” is selected.
Click on Help you save.
The file is then saved by using a .reg file extension.
You now use a backup within your mysql workbench error code 1215 related registry entry.

Solution to your error code 1452 mysql workbench problem

There are actually some manual registry editing measures that can not be talked about in this article due to the high chance involved for your laptop or computer method. If you want to understand more then check out the links below.

Additional Measures:

One. Conduct a Thorough Malware Scan

There’s a probability the 1064 Error Code Workbench Mysql error is relevant to some variety of walware infection. These infections are malicious and ready to corrupt or damage and possibly even delete your ActiveX Control Error files. Also, it’s attainable that your Mysql Workbench Error Code 1064 is actually connected to some element of that malicious plan itself.

2. Clean error code 1054 mysql workbench Disk Cleanup

The a lot more you employ your computer the extra it accumulates junk files. This comes from surfing, downloading packages, and any sort of usual computer system use. When you don’t clean the junk out occasionally and keep your program clean, it could turn into clogged and respond slowly. That is when you can encounter an 1064 error because of possible conflicts or from overloading your hard drive.

Once you clean up these types of files using Disk Cleanup it could not just remedy Mysql Workbench Error Code 1064, but could also create a dramatic change in the computer’s efficiency.

Tip: While ‘Disk Cleanup’ is definitely an excellent built-in tool, it even now will not completely clean up Mysql Workbench discovered on your PC. There are numerous programs like Chrome, Firefox, Microsoft Office and more, that cannot be cleaned with ‘Disk Cleanup’.

Since the Disk Cleanup on Windows has its shortcomings it is extremely encouraged that you use a specialized sort of challenging drive cleanup and privacy safety application like CCleaner. This system can clean up your full pc. If you run this plan after each day (it could be set up to run instantly) you are able to be assured that your Pc is generally clean, often operating speedy, and always absolutely free of any Mysql error associated with your temporary files.

How Disk Cleanup can help mysql error 1064 (42000)

1. Click your ‘Start’ Button.
2. Style ‘Command’ into your search box. (no ‘enter’ yet)
3. When holding down in your ‘CTRL-SHIFT’ important go ahead and hit ‘Enter’.
4. You will see a ‘permission dialogue’ box.
5. Click ‘Yes’
6. You will see a black box open up plus a blinking cursor.
7. Variety in ‘cleanmgr’. Hit ‘Enter’.
8. Now Disk Cleanup will start calculating the amount of occupied disk space you will be able to reclaim.
9. Now a ‘Disk Cleanup dialogue box’ seems. There will be a series of checkboxes for you personally to pick. Generally it will likely be the ‘Temporary Files’ that consider up the vast majority of your disk area.
10. Verify the boxes that you want cleaned. Click ‘OK’.

How to repair 1064 mysql

3. System Restore can also be a worthwhile device if you ever get stuck and just desire to get back to a time when your computer system was working ideal. It will work without affecting your pics, paperwork, or other crucial information. You can discover this option with your User interface.

Mysql Workbench

Manufacturer

Device

Operating System


Mysql Workbench Error Code 1064


4.5 out of
5

based on
19 ratings.

Like this post? Please share to your friends:
  • Ошибка 10632 vag
  • Ошибка 1073548784 сбой выполнения запроса backup log
  • Ошибка 1063 сузуки
  • Ошибка 1073 митсубиси
  • Ошибка 1063 java