2

I am maintaining a database created by another person in SQL Server. In one table I found a column whose name is between square brackets. The name of the field is desc and it is stored in the table as [desc]. The other fields are stored without square brackets. Is there any special reason/convention behind this choice?

The applications built on top of the Database are developed either in C# or VB.NET.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CiccioMiami
  • 8,028
  • 32
  • 90
  • 151
  • A terminology quibble: when you say 'it is stored in the table as `[desc]`, are you sure? What tool is telling you that? If you've used (say) SQL Mgmt Studio to make a `CREATE` script, it will be making *runnable* T-SQL, which needs `[]` around this reserved word - but the *name* of the column (not "field") is `desc`, as can be seen by querying `sys.columns`. – AakashM Sep 27 '11 at 13:50

3 Answers3

7

The brackets (or other identifiers in other database engines) are just an explicit way of telling the query engine that this term is an identifier for an object in the database. Common reasons include:

  1. Object names which contain spaces would otherwise fail to parse as part of the query unless they're wrapped in brackets.
  2. Object names which are reserved words can fail to parse (or, worse, correctly parse and do unexpected things).

(I suppose it's also possible that there may be an ever-so-slight performance improvement since the engine doesn't need to try to identify what that item means, it's been explicitly told that it's an object. It still needs to validate that, of course, but it may be a small help in the inner workings.)

David
  • 208,112
  • 36
  • 198
  • 279
  • 2
    It could also be considered good practice to do so as you will never have any problems with the points you mentioned, plus you're making the intent clear. – Vala Sep 27 '11 at 13:57
  • @Thor84no: Definitely. It's worth noting that every code-generation tool I've ever seen create database queries (LINQ2SQL and EF being prime examples) uses these. A few extra bytes are a small price to pay for a clearer and more explicit piece of code. – David Sep 27 '11 at 13:59
4

If your names contains either a reserved word (such as SELECT) or spaces, then you need to surround the name with [].

In your example, you have [desc], which is short for DESCENDING.

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
3

For example if you have a field that is a keyword e.g [Date] or [Select] or in this case [desc]

Daniel Elliott
  • 22,647
  • 10
  • 64
  • 82