Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is text [] in SQL?

TEXT is a variable width character string data type that supports non-Unicode data in the code page of a SQL database server and with a maximum string length of 2,147,483,647. This data type is used for storing large pieces of string data values.

What do brackets do in SQL Server?

Brackets allow you to delimit names in SQL Server. This allows you to do such things as use keywords [count] or include spaces [my column name].

Do you need square brackets in SQL?

1) If you have SQL keyword, space or any other illegal characters then you need to use square brackets. 2) SQL server parse and compiler much more easy to validate and compile code. 3) code search tools easy to find table names or column names only.


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.


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.