This question already has answers here:
What is the use of the square brackets [] in sql statements?
(10 answers)
Closed 7 years ago.
I have a copy of an existing database with existing records. when i was playing around with the table designer and noticed some of the column names have [] around them. they all seem to be arbitrary typed (float, datetime, netext, nvarchar etc) and there is nothing in column properties that gets rid of the []. I tried to rename delete the [] but it reappaears as soon as I exit edit.
according to this post, it is a keyword column for xml columns? but none of those columns are xml columns. Would someone kindly explain the purpose of this to a ms-sql newbie? thanks
The square brackets [] are used to delimit identifiers. This is necessary if the column name is a reserved keyword or contains special characters such as a space or hyphen.
Some users also like to use square brackets even when they are not necessary.
From MSDN:
Delimited identifiers
Are enclosed in double quotation marks (") or brackets ([ ]). Identifiers that comply with the rules for the format of identifiers may or may not be delimited.
SELECT *
FROM [TableX] --Delimiter is optional.
WHERE [KeyCol] = 124 --Delimiter is optional.
Identifiers that do not comply with all of the rules for identifiers must be delimited in a Transact-SQL statement.
SELECT *
FROM [My Table] --Identifier contains a space and uses a reserved keyword.
WHERE [order] = 10 --Identifier is a reserved keyword.
Square brackets may be placed around objects (e.g. views, databases, columns etc)
Their primary purpose is, as Mark mentioned, to encapsulate the objects so that special characters such as a space or period do not interfere with your syntax.
Many applications by default use the bracketed notation, to further reduce risk of syntax errors or anything of that sort.
It's typically good practice to not include any spaces
Database_Name < GOOD PRACTICE
Database Name < GENERALLY TRY TO AVOID
In any case, if the latter is used, you may use square brackets i.e.
select * from [Database Name]
the brackets are special characters in sql server that are used to explicitly delimit information.
they can be used in xml as per the article, they can also be used to specify meta names (column, table, etc.) that have spaces or other key words.
declare my column nvarchar(50)
would be invalid syntax, but you could do
declare [my column] nvarchar(50)
just think of them as explicit delimiters.
Related
I put together an Access Database for a department. They've been using it frequently for the past few months with no hiccups.
However, they changed one of the field names of a linked Excel File, which forces me to go into Access and update the query a bit.
The field name has gone from "PacU" to "Mr. Cooper"
Original:
SELECT Round(BidTemplate.[PacU],6) AS PacU
New:
SELECT Round(BidTemplate.[Mr. Cooper],6) AS [Mr. Cooper]
I am receing an error as follows "Invalid bracketing of the name 'BidTeample.[Mr.Cooper]'.
I'm sure the issue is driven off of the period that is now included in the field. But shouldn't the brackets take care of this?
What am I missing?
Field names cannot contain a period.
From the MS Access Documentation:
Names of fields, controls, and objects in Microsoft Access desktop databases:
Can be up to 64 characters long.
Can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation point (!), an
accent grave (`), and brackets ([ ]).
Can't begin with leading spaces.
Can't include control characters (ASCII values 0 through 31).
Can't include a double quotation mark (") in table, view, or stored procedure names in a Microsoft Access project.
remove extra space
SELECT Round(BidTemplate.[Mr Cooper],6) AS [Mr Cooper]
Unfortunately I have to take an Excel file that contains a column name => endOfWork [4]
I then want to export it using a SQL query. I rename my columns and can not put brackets as requested:
TMP_TBL_Sedex_modif.Champ98 AS startOfWork [23]
How to put square brackets in my SQL query?
Square brackets are used in SQL Server as characters to delimit Delimited Identifiers, which are allowed to contain characters not allowed in Regular Identifiers (and are also allowed to be SQL keywords).
If you wish to use square brackets within the name, you have to escape one of them:
select 1 as [startOfWork [23]]]
Alternatively, assuming the default settings, you can use double-quotes as the delimiter instead:
select 1 as "startOfWork [23]"
If some one does right click on a given Table in a Database using SQL Server management Studio from Microsoft and create script table to query window, it displays the create table code in the window. I notice something like the following
CREATE TABLE [dbo].[Login](
[UserId] [int] NOT NULL,
[LoginName] nvarchar COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
etc
)
Is this how it appears in other DBMS too ?
Is this something specific to DBMS used ?
Is it just a fancy view only ?
Why are "[ ]" used around column names and table names. Simple TSQL definition would look something like
CREATE TABLE table_name (
Column#1 Datatype NOT NULL,
Column#2 Datatype NOT NULL UNIQUE,
-- etc...
)
Please dont mind my silly questions.
Thanks in advance,
Balaji S
Those are identifier quotes. They mark the contents as a database identifier (column name, table name, etc) and allow spaces, special characters, and reserved words to be used as identifiers. Usually none of those appear in identifiers so the ID quotes are, strictly speaking, unnecessary. When the text cannot be parsed because of special characters or reserved words, the ID quotes are required.
It's easier for automated tools to simply always use the ID quotes than figure out when you could get away without them.
Different database products use different characters for ID quotes. You often see the back-tick (`) used for this.
Just to add to Larry Lustig's excellent answer, SQL Server's 'create script' function spits out SQL code whose first priority is to be parser-friendly and that's why it always uses its preferred delimited identifier characters being square brackets, rather than say the double quotes used by the SQL-92 standard (SQL Server code can support the Standard delimited identifier by the use of SET QUOTED_IDENTIFIER ON but I don't think this can be specified as an option for output). Being easy on the human eye (use of whitespace, line breaks, etc) is merely a secondary consideration.
Square brackets allow you to use names for columns or aliases that contain characters not permitted for column names or aliases.
a) I’ve noticed that lots of times table and column names are enclosed inside square brackets, even though their names consist of perfectly legal characters. Why is that?
b) As far as I know, square brackets enclosing object’s name aren’t actually a part of that name. Thus, if we create a table named [A]:
CREATE TABLE [A] ( … )
we can later reference it without using brackets:
SELECT * FROM A
But why isn’t the same true when I try to reference a column KEY from a table returned by CONTAINSTABLE function? Namely, if I omit the brackets enclosing column name, I get an error:
SELECT ct.KEY
FROM CONTAINSTABLE(fullText,*,'some_string') as ct
thanx
KEY is a reserved word in SQL so requires the brackets to use it as a column name.
I think lots of the time you see superfluous square brackets may well be code generated by a tool. Management Studio puts them on when generating some scripts.
Brackets are not just for legal characters but to allow the use of otherwise reserved words for column names, etc.
What is the difference between single quotes and double quotes in SQL?
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.
Stick to using single quotes.
That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id would be more readable as product_id, so you use either of the following:
SELECT PRODUCT.id AS product_id
SELECT PRODUCT.id 'product_id'
Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.
You do have to use single quotes when the column alias includes a space character, e.g., product id, but it's not recommended practice for a column alias to be more than one word.
A simple rule for us to remember what to use in which case:
[S]ingle quotes are for [S]trings Literals (date literals are also strings);
[D]ouble quotes are for [D]atabase Identifiers;
Examples:
INSERT INTO "USERS" ("LOGIN", "PASSWORD", "DT_BIRTH") VALUES ('EDUARDO', '12345678', '1980-09-06');
In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. And note that you can't use " for literal strings when your SQL_MODE has ANSI_QUOTES enabled.
Single quotes delimit a string constant or a date/time constant.
Double quotes delimit identifiers for e.g. table names or column names. This is generally only necessary when your identifier doesn't fit the rules for simple identifiers.
See also:
Do different databases use different name quote?
You can make MySQL use double-quotes per the ANSI standard:
SET GLOBAL SQL_MODE=ANSI_QUOTES
You can make Microsoft SQL Server use double-quotes per the ANSI standard:
SET QUOTED_IDENTIFIER ON
In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).
Single quotes are for strings.
However, MySQL is oblivious to the standard (unless its SQL_MODE is changed) and allows them to be used interchangably for strings.
Moreover, Sybase and Microsoft also use square brackets for identifier quoting.
So it's a bit vendor specific.
Other databases such as Postgres and IBM actually adhere to the ansi standard :)
I use this mnemonic:
Single quotes are for strings (one thing)
Double quotes are for tables names and column names (two things)
This is not 100% correct according to the specs, but this mnemonic helps me (human being).
Two Things To Remember :
Single Qutoes(') : String Or Text
select * from employees where room_name = 'RobinCapRed';
where RobinCapRed is a string or a text.
Double Quotes(") : Column Names or Table Names
select "first_name" from "employees";
where first_Name is a column name from employees table
The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.
When you want to use an alias that has space in between then you can use double quotes to refer to that alias.
For example
(select account_id,count(*) "count of" from orders group by 1)sub
Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.
Now let's write an outer query to display the rows where "count of" is greater than 20.
select "count of" from
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;
You can apply the same case to Common Table expressions also.