Why Brackets in SQL queries with SQL Server

It’s been long time since I worked with SQL Server last time. I have been working with Oracle and there are differences for sure. This one is simple.

  1. The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)–but then you’d need to use brackets every time you referred to that column.
  2. They’re handy if your columns have the same names as SQL keywords, or have spaces in them.Example:create table test ( id int, user varchar(20) )
    Oh no! Incorrect syntax near the keyword ‘user’. But this:

    create table test ( id int, [user] varchar(20) )
    Works fine.

  3. Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft’s newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired….Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.

Source: http://stackoverflow.com/questions/52898/what-is-the-use-of-the-square-brackets-in-sql-statements

This entry was posted in Databases, MSSQL, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s