Home > Database > Mysql Tutorial > How Can I Escape Reserved Words When Creating MySQL Table Columns?

How Can I Escape Reserved Words When Creating MySQL Table Columns?

Barbara Streisand
Release: 2024-12-26 14:08:14
Original
620 people have browsed it

How Can I Escape Reserved Words When Creating MySQL Table Columns?

Escaping Reserved Words as Column Names in MySQL CREATE TABLE

When creating tables in MySQL, it is important to adhere to the language's reserved keywords. However, challenges arise when class field names match these keywords, such as the "key" field in the example provided.

To bypass this issue, you can utilize double quotes or backticks to escape the reserved word, ensuring its recognition as a column name rather than a MySQL keyword.

Using Double Quotes (ANSI SQL Mode Enabled)

If the ANSI SQL mode is enabled in your MySQL environment, you can enclose the reserved word within double quotes:

CREATE TABLE IF NOT EXISTS misc_info
  (
     id    INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
     "key" TEXT UNIQUE NOT NULL,
     value TEXT NOT NULL
  )
ENGINE=INNODB;
Copy after login

Using Backticks (Proprietary Escaping)

If the ANSI SQL mode is not enabled or you prefer a proprietary approach, you can use backticks to escape the reserved word:

CREATE TABLE IF NOT EXISTS misc_info
  (
     id    INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
     `key` TEXT UNIQUE NOT NULL,
     value TEXT NOT NULL
  )
ENGINE=INNODB;
Copy after login

By employing either of these methods, you can successfully create tables with column names that coincide with MySQL reserved words.

The above is the detailed content of How Can I Escape Reserved Words When Creating MySQL Table Columns?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template