What is the use of the square brackets [] in sql statements? - sql-server

I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.
Example:
Visual Studio:
SELECT [column1], [column2] etc...
My own way:
SELECT column1, column2 etc...

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.
The newer tools add them everywhere just in case or for consistency.

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.

They are useful if you are (for some reason) using column names with certain characters for example.
Select First Name From People
would not work, but putting square brackets around the column name would work
Select [First Name] From People
In short, it's a way of explicitly declaring a object name; column, table, database, user or server.

During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.
So it keeps forward compatibility.
And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.

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.

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

The brackets can be used when column names are reserved words.
If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.

In addition
Some Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly.

They are useful to identify each elements in SQL.
For example:
CREATE TABLE SchemaName.TableName (
This would actually create a table by the name SchemaName.TableName under default dbo schema even though the intention might be to create the table inside the SchemaName schema.
The correct way would be the following:
CREATE TABLE [SchemaName].[TableName] (
Now it it knows what is the table name and in which schema should it be created in (rightly in the SchemaName schema and not in the default dbo schema)

I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.

Related

Incorrect syntax near 'Case'. Expecting ID, QUOTED_ID, or '.' Error in SQL Server

I multiple tables in my database. All of my tables are showing output using select query instead of only 1 table "case". it also have data and columns but when I use it in my query it shows syntax error. I have also attached picture which have list of table and a simple query. This code is not developed by me so I am not sure why it is showing error. Is there any kind of restriction we can set so that it cannot be used in queries?
CASE is a reserved keyword in SQL Server. Therefore, you must escape it in double brackets:
SELECT * FROM dbo.[Case];
But best naming practice dictates that we should avoid naming database objects using reserved keywords. So, don't name your tables CASE.
Reserved words are not recommended for use as a database, table, column, variable, or other object names. If you desire to use a reserved word is used as an object name in ANSI standard syntax, it must be enclosed in double-quotes OR "[]" to allow the Relational Engine (whichever that one is) that the word is being used as an object and not as a keyword in the given context. Here is the sample code.
SELECT * FROM dbo."Case"
Or
SELECT * FROM dbo.[Case]

Table name containing special characters '[' and ']'

I want to create table in sql server with using [ ] in the name.it's mean [ ] symbol is a part of table name.how can i do it?i use sql server 2008 r2
You can use ] if you enclose the table name in double quotes:
create table "[Mu]Ha[Ha]" (id int);
Note that using irregular identifiers is an invitation for trouble down the road. Not all client libraries will deal with them correctly, and your code will become harder to read for other developers.
you can create a table(or column names) using [ ] in it, but it is considered a bad practice.
CREATE TABLE "tabl[eO]ne" (ID int NOT NULL)
the above will work, but is considered bad practice, because it makes the code harder to read and understand, not only for you but also for other developers working on the database after you.
in SQL people use brackets around a table/column name if the name contains spaces or certain special character, like the example below:
CREATE TABLE [Table One]
CREATE TABLE [Table-One]
CREATE TABLE [Table_One]
CREATE TABLE [Table*One]
...
This still isn't a good practice but it follows the "best practice" guidelines.
Best practice of all :
Avoid using special characters, numbers or spaces in a table/column name at all.
Enclose within square brackets.
But its Not a good practice
["name[a]abc"]
You can overcome this by using double bracket. see below:
CREATE TABLE dbo.[[tbl]]](id INT)

How can I check if a word is a reserved keyword in Sybase (can't be used as column name)?

Question:
How can I (programmatically) obtain a complete list of reserved keywords in Sybase?
Specifically, ones that can not be a column name in a table.
Alternately, how can I check whether a specific identifier is a reserved keyword in Sybase?
Background:
I have a process which takes a comma separated file with headers and loads into a temp table in Sybase.
The goal is to have the temp table column names match the file column names.
This will fail if the file has a column named after a reserved keyword.
I'd like to catch that scenario BEFORE the CREATE TABLE statement fails.
Notes:
I am looking for a Sybase-version-independent solution.
Therefore "copy all the words in Sybase Reference Manual (e.g. this for v.12.5) is NOT a valid answer. I'm perfectly aware I can do that. But it will not work in Sybase 15 without changing the keyword list by hand.
If the solution exists but not available in earlier Sybase versions, I need something compatible with Sybase 12.5 and later
I'm also perfectly aware of how to do this by creating a table with any words I have, trapping CREATE TABLE failure, and reading which word failed. I'm looking for a more elegant solution if available.
Found a way after more Googling!
select name from master..spt_values where type="W"
First, turn on "quoted_identifier" in your config (set quoted_identifier on). Then escape all your column names with double quotes.
That way you don't need to catch which ones are reserved words, and all columns will have the names you expect them to have.

Is there any reason to write a database column between square brackets?

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
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:
Object names which contain spaces would otherwise fail to parse as part of the query unless they're wrapped in brackets.
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.)
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.
For example if you have a field that is a keyword e.g [Date] or [Select] or in this case [desc]

Referencing tables

In SQL Server, why is this:
[dbo].[table_name]
preferable to this:
dbo.table_name
And along those lines, why even list the dbo at all if there's only one schema?
If the table name contains key words, you will have to enclose it inside [ ]. Most of the tools (like ORM) use this technique to avoid any errors or for consistency.
It's just in case you have a keyword as a tablename like [user]
It allows keywords or punctuation in a table name.
It's often used by code generators for all names, so they don't have to figure out if it actually needed.
These usually come up in generated code - because it's easier to make the code generation produce fully-qualified and escaped references than to deduce what escaping/qualification is required when.
If there is only one schema then prefixing the table name is not necessary or useful I think. Using the brackets [] is useful when you have an identifier that is a reserved word in sql server. If, for instance, you have a table named Select you can refernce it as SELECT * FROM [Select] but not as SELECT * FROM Select.
I don't use the brackets, which are only necessary if you use keywords as schemas or table names, which you shouldn't.
But I would recommend against dropping the dbo at the front. The reason is that eventually you might want to start organizing your code into schemas, and then you will need the prefix. If you get in the habit of using the schema.table format, it will be a lot easier to search your code for places where the tables are used.
Let's say you have a table called dbo.user, and you decide to move it to another schema. If you have to search through a bunch of stored procedures or dynamic sql for "user", you will likely get a ton of false positives. You can't be totally sure that you made all the changes you needed to. Searching for "dbo.user" is a lot more concise.
The [] are only required if the object name contains characters like spaces or if it is a keyword. It is generally regarded as best practice not to use any of these as object names so you should never need the []. Having said that they also do no harm, if it is generated code and includes the brackets then you may as well leave them.
Using dbo is a good idea becuase
Performance is better (see here for some figures)
dbo is required in some cases, like calling user defined functions. I think it is tidyer to always include it.
Not qualifying the object name could lead to bugs in the future if you do create multiple schemas.
Doesn't this allow you to have whatever 'bad' items you desire in there?
Keywords, spaces, etc...
I would prefer to avoid using punctuation and reserved words in table and column names, and not use the square brackets. This makes the SQL far easier to read.
Apart from spaces, reserved keywords, and system functions in an identifier name, an identifier can also contain some characters that are not allowed in regular identifiers, an it has to be separated with square brackets.
You can find a detailed explanation and rules for regular and delimited identifiers in this article.
From the article:
For example, delimited identifiers can contain spaces, any characters
valid for regular identifiers, and any one of the following
characters:
tilde (~) hyphen, (-) exclamation point (!), left brace ({), percent (%),
right brace (}), caret (^), apostrophe ('), ampersand (&), period (.), left
parenthesis ((), backslash (), right parenthesis ()), accent grave (`),
Using two name qualifying convention may improve performance (avoid name resolutions) and avoid ambiguity in cases when you have e.g. the same table name in two or more schema. In that case SQL Server will search your object in dbo and if it isn't there it will stop searching.
Also if you later want to use that object with the SCHEMABINDING option it doesn't allow unqualified object names.
Hope this helps

Resources