tags:

views:

4413

answers:

7

What do the brackets do in a sql statement?

For example, in the statement:

insert into table1 ([columnname1], columnname2) values (val1, val2)

Also, what does it do if the table name is in brackets?

+4  A: 

They are meant to escape reserved keywords or invalid column identifiers.

CREATE TABLE test
(
  [select] varchar(15)
)

INSERT INTO test VALUES('abc')

SELECT [select] FROM test
smink
+17  A: 

The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:

select [Order qty] from [Client sales]

They are also to escape reserved keywords used as identifiers

AlbertEin
A: 

They are simply delimiters that allow you to put special characters (like spaces) in the column or table name e.g.

insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)
Darrel Miller
A: 

Duplicate question: http://stackoverflow.com/questions/52898/sql-syntax-curiousity

bdukes
Better title on this one though. Who, upon encountering brackets for the first time, would search for "curiousity"?
Shog9
Especially since "curiousity" isn't even a word.
Justin Bennett
HA! Crazy canuks and their superfluous 'u's. :-p
Shog9
+1  A: 

Anything inside the brackets is considered a single identifier (e.g. [test machine]. This can be used to enclose names with spaces or to escape reserve words (e.g. [order], [select], [group]).

Orion Adrian
+1  A: 

They allow you to use keywords (such as date) in the name of the column, table, etc...

Since this is a bad practice to begin with, they are generally not included. The only place you should see them being used is by people starting out with sql queries that don't know any better. Other than that they just clutter up your query.

Ty
+6  A: 

This is Microsoft SQL Server nonstandard syntax for "delimited identifiers." SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following:

  • SQL reserved words: "Order"
  • Words containing spaces: "Order qty"
  • Words containing punctuation: "Order-qty"
  • Words containing international characters
  • Column names that are case-sensitive: "Order" vs. "order"

Microsoft SQL Server uses the square brackets, but this is not the syntax standard SQL uses for delimited identifiers. Standardly, double-quotes should be used for delimiters.

In Microsoft SQL Server, you can enable a mode to use standard double-quotes for delimiters as follows:

SET QUOTED_IDENTIFIER ON;
Bill Karwin
Even with quotes or brackets, names are not necessarily case-sensitive in SQL Server; it depends on the server or database collation. Also, brackets are not unique to SQL Server; they are also in Sybase.
crosstalk
Thanks, that makes sense that brackets are supported in Sybase, since it and SQL Server were once the same code base.
Bill Karwin