patternsqlMajor
Why can't object names start with a number?
Viewed 0 times
whycannumberwithnamesstartobject
Problem
For example, if I'm creating view with a name
Additionally, what does
A string's a string, amirite?
'4aii', why does SQL Server care that it starts with a 4? I could call the table Fouraii or IVaii.Additionally, what does
[] do behind the scenes to allow for any string to be used as a name? A string's a string, amirite?
Solution
Firstly, you need to distinguish between numbers (numeric literals), strings (string literals) and identifiers.
The query parser needs to understand the meaning of a token that it is looking at. By allowing names to begin with digits, you by extension allow them to consist of digits exclusively. Then, given
However, if you allow identifiers to begin with letters only (or underscore characters), you can unambiguously say if you're looking at an identifier (
Square brackets in SQL Server, backticks (
A little dbfiddle demo.
'4aii' is a string literal, which can be a value of some "thing", but it does not identify (name) a thing. 4aii or [4aii] would be identifiers (if it were allowed).The query parser needs to understand the meaning of a token that it is looking at. By allowing names to begin with digits, you by extension allow them to consist of digits exclusively. Then, given
select 12345 from mytable, how would you (and the parser) know if 12345 is an integer literal or a name of a column? However, if you allow identifiers to begin with letters only (or underscore characters), you can unambiguously say if you're looking at an identifier (
abc123) or a string literal ('abc123') -- the latter is enclosed in quotation marks.Square brackets in SQL Server, backticks (
) in MySQL, and double quotes in ANSI SQL-compliant engines, signify identifiers, and you use them for when your identifiers cannot be readily distinguished from other tokens: start with a digit, have spaces or other special characters in them etc. Hence, [4aii] or "4aii"` clearly tell the parser that it's dealing with an identifier.A little dbfiddle demo.
Context
StackExchange Database Administrators Q#217424, answer score: 20
Revisions (0)
No revisions yet.