I have SQL Server 2008 Express Edition installed and is my first time running a SQL query. I noticed that if I select to display the top 1000 rows that the query places brackets [] around the name of the database and its respective columns.
- Why are there brackets around the name of the database and columns?
- Is there a need to have these and if so when?
I just posted this answer on dba.stack.
They escape names that are not “friendly” – they can be useful if your database names contain special characters (such as spaces, dots or dashes) or represent SQL keywords (such as
USEorDATABASE:-)). Without the square brackets, a query like this will fail:However if you write the query this way, the keywords are ignored:
When building scripts or writing solutions that generate scripts from metadata (e.g. generating a script of all tables or all indexes), I always wrap entity names in square brackets so that they will work regardless of what kind of wonky names have been implemented (I am not always doing this for systems I control). You can do this easily using
QUOTENAMEfunction, e.g.:Results:
If you search my answers here for
QUOTENAMEyou will find that I use it in a lot of scripts where I’m helping folks automate script generation or building dynamic SQL. Without the square brackets, a lot of people would run into issues running the scripts.