Brackets are required if your table or column names:
- contain a space:
SELECT [column name] FROM table;
- contain a bracket:
SELECT [wt[f]
, orSELECT [wt]]f]
- contain a non-alphanumeric symbol like
^
or!
(yes, they can contain those symbols!) - are reserved keywords like
KEY
,STATE
,RULE
, ...
Obviously, if you have control over the schema then avoid using names like these. However, in some cases the best name is a reserved one (like
KEY
for the key column in a generic key-value table) so it's up to you to decide how badly you want to use it (and thus have to quote it everywhere).I also use brackets to suppress the blue highlighting that SSMS and VS give some keywords like
DESCRIPTION
that aren't reserved by SQL Server but are otherwise special to those tools.- contain a space:
Definitely use brackets when dynamically generating SQL. The easy way to do so is by calling
QUOTENAME()
on the objects you are dynamically referencing (e.g.SELECT QUOTENAME(name) FROM sys.databases;
).sp_MSforeachdb
, for example, doesn't do thisdoesn't do this.