Home  >  Q&A  >  body text

Solve mysql CREATE TABLE syntax questions

I try to create a table in mysql using the following command:

CREATE TABLE keys (id INT(10), key VARCHAR(100));

But it always gives me an error similar to this:

Error 1064 (42000): There is an error in your SQL syntax; check the manual for your MySQL server version for "keys (id INT(10), key VARCHAR(100))" on line 1 Correct syntax to use nearby `

P粉347804896P粉347804896404 days ago519

reply all(2)I'll reply

  • P粉253518620

    P粉2535186202023-09-13 13:54:33

    You should be very careful about naming tables and columns as you may face a lot of problems in the future.

    I recommend finding names that are not MySQL reserved words.

    If you still want to keep these names, you should surround them with backticks.

    mysql> CREATE TABLE keys (id INT(10), key VARCHAR(100));
    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 'keys (id INT(10), key VARCHAR(100))' at line 1
    
    mysql> CREATE TABLE `keys` (id INT(10), `key` VARCHAR(100));
    Query OK, 0 rows affected, 1 warning (0.97 sec)
    
    mysql> show create table keys;
    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 'keys' at line 1
    mysql>
    mysql>
    mysql> show create table `keys`;
    +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------+
    | Table | Create Table                                                                                                                                        |
    +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------+
    | keys  | CREATE TABLE `keys` (
      `id` int DEFAULT NULL,
      `key` varchar(100) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
    +-------+-----------------------------------------------------------------------------------------------------------------------------------------------------+
    1 row in set (0.01 sec)

    Please note that backticks must be used when using tables

    reply
    0
  • P粉649990163

    P粉6499901632023-09-13 13:29:28

    So the table name keys and field key are reserved in the Mysql namespace. If you choose a different table name (e.g. keys_tbl) and rename the second field to key_id, your code will work correctly.

    reply
    0
  • Cancelreply