Using backquote/backticks for mysql queries

前端 未结 6 499
温柔的废话
温柔的废话 2020-12-09 08:28

I have building MYSQL queries with backticks. For example,

SELECT `title` FROM `table` WHERE (`id` = 3)

as opposed to:

SELE         


        
相关标签:
6条回答
  • 2020-12-09 09:05

    My belief was that the backticks were primarily used to prevent erroneous queries which utilized common SQL identifiers, i.e. LIMIT and COUNT.

    0 讨论(0)
  • 2020-12-09 09:15

    You read the documentation on identifiers at http://dev.mysql.com/doc/refman/5.6/en/identifiers.html

    SQL generators will often include backticks, as it is simpler than including a list of all MySQL reserved words. To use any1 sequence of BMP Unicode characters except U+0000 as an identifier, they can simply

    1. Replace all backticks with double backticks
    2. Surround that with single backticks

    When writing handmade queries, I know (most of) MySQL's reserved words, and I prefer to not use backticks where possible as it is shorter and IMO easier to read.

    Most of the time, it's just a style preference -- unless of course, you have a field like date or My Field, and then you must use backticks.

    1. Though see https://bugs.mysql.com/bug.php?id=68676

    0 讨论(0)
  • 2020-12-09 09:18

    Well, if you ensure that you never accidentally use a keyword as an identifier, you don't need the backticks. :-)

    0 讨论(0)
  • 2020-12-09 09:24

    Backticks also allow spaces and other special characters (except for backticks, obviously) in table/column names. They're not strictly necessary but a good idea for safety.

    If you follow sensible rules for naming tables and columns backticks should be unnecessary.

    0 讨论(0)
  • 2020-12-09 09:29

    Every time I see this discussed, I try to lobby for their inclusion, because, well, the answer is hidden in here already, although wryly winked away without further thought. When we mistakenly use a keyword as a field or table name, we can escape confusion by various methods, but only the keenly aware back-tick ` allows an even greater benefit!!!

    Every word in a sql statement is run through the entire keyword hash table to see if conflicts, therefore, you've done you query a great favor by telling the compiler that, hey, I know what I'm doing, you don't need to check these words because they represent table and field names. Speed and elegance.

    Cheers, Brad

    0 讨论(0)
  • 2020-12-09 09:31

    backticks are used to escape reserved keywords in your mysql query, e.g. you want to have a count column—not that uncommon.

    you can use other special characters or spaces in your column/table/db names

    they do not keep you safe from injection attacks (if you allow users to enter column names in some way—bad practice anyway)

    they are not standardized sql and will only work in mysql; other dbms will use " instead

    0 讨论(0)
提交回复
热议问题