[] brackets in sql statements - sql

What do the brackets do in a sql statement?
For example, in the statement:
insert into table1 ([columnname1], columnname2) values (val1, val2)
Also, what does it do if the table name is in brackets?

The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:
select [Order qty] from [Client sales]
They are also to escape reserved keywords used as identifiers

This is Microsoft SQL Server nonstandard syntax for "delimited identifiers." SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following:
SQL reserved words: "Order"
Words containing spaces: "Order qty"
Words containing punctuation:
"Order-qty"
Words containing international
characters
Column names that are
case-sensitive: "Order" vs. "order"
Microsoft SQL Server uses the square brackets, but this is not the syntax standard SQL uses for delimited identifiers. Standardly, double-quotes should be used for delimiters.
In Microsoft SQL Server, you can enable a mode to use standard double-quotes for delimiters as follows:
SET QUOTED_IDENTIFIER ON;

They are meant to escape reserved keywords or invalid column identifiers.
CREATE TABLE test
(
[select] varchar(15)
)
INSERT INTO test VALUES('abc')
SELECT [select] FROM test

They allow you to use keywords (such as date) in the name of the column, table, etc...
Since this is a bad practice to begin with, they are generally not included. The only place you should see them being used is by people starting out with sql queries that don't know any better. Other than that they just clutter up your query.

Anything inside the brackets is considered a single identifier (e.g. [test machine]. This can be used to enclose names with spaces or to escape reserve words (e.g. [order], [select], [group]).

if you use any column name which is same as any reserved keyword in sql, in that case you can put the column name in square bracket to distinguish between your custom column name and existing reserved keyword.

When having table names or filenames with spaces or dashes (-) etc... you can receive "Systax error in FROM clause".
Use [] brackets to solve this.
See: https://msdn.microsoft.com/en-us/library/ms175874.aspx

They are simply delimiters that allow you to put special characters (like spaces) in the column or table name
e.g.
insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)

Related

How can I include strings which contain special characters in my WHERE clause?

I am using SQL Server 2014 and I am faced with the following problem in the WHERE clause of my T-SQL query.
My WHERE clause will list the names of towns. However some of the names contain characters like an apostrophe in them. Example: ST JULIEN D'HOTMAN
My T-SQL looks as follows:
SELECT
...
FROM [TownList]
WHERE [townName] IN
(
...,
...,
'ST JULIEN D'HOTMAN',
...,
)
The above does not work because one or more of the [townName] contains an apostrophe.
From the solution given here (How to insert a value that contains an apostrophe (single quote)?, I need to re-write that value as 'ST JULIEN D''HOTMAN'
This is fine if you have a couple of Names that follow this principle. You can manually correct the way the values need to written. However, more than 200 to 300 names in my list have these issues.
Is there an alternative solution to approaching this problem?
I would use a table or temp table to carry with your data before filtering the data
if you don't want to modify each [townName] there is another way you can try to SET QUOTED_IDENTIFIER OFF then use double quotation be the string Identify.
Causes SQL Server to follow the ISO rules regarding quotation mark delimiting identifiers and literal strings. Identifiers delimited by double quotation marks can be either Transact-SQL reserved keywords or can contain characters not generally allowed by the Transact-SQL syntax rules for identifiers.
SET QUOTED_IDENTIFIER OFF;
SELECT
...
FROM [TownList]
WHERE [townName] IN
(
...,
...,
"ST JULIEN D'HOTMAN",
...,
)
SET QUOTED_IDENTIFIER ON;

Apache derby - SELECT * FROM tablename dont work

When i execute SELECT * FROM tablename generate that erorr :
java.sql.SQLSyntaxErrorException: Table/View 'tablename' does not exist.
but if i run that sql command
SELECT * FROM "tablename" the sql run without problems why.
This is an aspect of the SQL standard known as "delimited identifiers".
Table names, column names, and other objects are things that you can give names to in your database.
The SQL standard says that, if you aren't particular about the upper/lower case of your object names, you can just specify the names without quotation marks, and your database will process them in a case-insensitive manner (typically, by converting an unquoted object name into the all-upper-case version of that name).
CREATE TABLE mytable(c1 INT, c2 CHAR(10));
INSERT INTO MyTable (C1, C2) VALUES (42, 'Bryan');
SELECT c2 FROM MYTABLE;
Since you didn't specify any object names in quotation marks, all of these examples work fine, because mytable, MyTable, and MYTABLE are all the same, when they aren't in quotation marks.
But if you specify your object names in quotation marks, then you have to get things exactly right:
CREATE TABLE "MyCaseSensitiveTable" (c1 int, c2 char(10));
INSERT INTO MyCaseInsensitiveTable (c1, c2) values (64, 'a nice age');
In this case, your INSERT statement will be rejected, because "MyCaseSensitiveTable" is different than MyCaseSensitiveTable.
Delimited identifiers bring other advantages:
You can use otherwise-reserved keywords from the SQL language as table names, so you can create a table named "TABLE" if you want.
You can use various special characters in your database object names.
Personally, I try never to use delimited identifiers, because I think they make my programs hard to read. But they are a completely legitimate part of the SQL standard and they are widely used.
But, the bottom line is: if you're going to put your database object names in quotation marks, you have to put them in quotation marks all the time, and you have to give the name exactly the same each time, but if you don't use quotation marks for your database object names, they will be treated in a case-insensitive manner.

Variable names in SQL Server

Can I declare name of SQL Server variable in a table with spaces?
create table test(
record name, float, not null
.....
The above query when executed gives me an error. Is there any way to declare the variable as
variable name with a space..??
Yes, escape these names using []:
[record name] ....
These names are called Delimited identifiers:
Are enclosed in double quotation marks (") or brackets ([ ]).
But it is not recommended, use legal names instead or regular identifiers.
Try using square brackets:
create table test(
[record name] float not null)
use [square brackets] around your column names with spaces and you should be fine.
It would be advisable in the long term to avoid spaces all together if you can, it will save you hours of stress in the future.

What is the difference in [ ] and ( ) in SQL?

I've seen both used but I can't seem to understand when to use each?
To me is seems like you enter the name of the table you are referring from in the ( ) and the field name in the [ ]?
Could anyone explain?
The square brackets are used In Microsoft products to specify that what's within them is an identifier (the standard quoted identifiers are double quotes " ", which Microsoft SQL Sever also supports). This is used when you have a database name, user name, table name, field name, view name, procedure name (et.c.) that happens to be the same as a keyword, or contains characters that would break the syntax. This is often used in generated code to safeguard against identifiers that can't otherwise be used in the code. A generated query could look like this:
select [Id], [Name], [Password hint]
from [dbo].[MyDataBase].[User]
Here the field name Password hint would break the syntax if used without brackets, and the table name User could conflict with the keyword User.
Parentheses are used to group items, for example as part of the syntax of some clauses, for example an insert:
insert into someTable (field1, field2) values ('value1', 'value2')
They can also be used in expressions:
select Price * (Quantity + FreeItems) from Articles
They can also be used around queries to make subqueries:
select o.Name
from (select Name, Age from Persons where City = 'Oslo') as o
where o.Age > 18
() are used for passing parameters to functions and stored proceedures etc. [] are used to encapsulate field name (etc.) which include punctuation (spaces and special characters as per the comment above). [] are useful sometimes to name fields for display
SELECT FFgg AS [Some field discription] FROM table1;
Hope this helps.

How to INSERT to a column whose name is a sql keyword

I need a table that stores key-value pairs, so I created one with a column called "Key" and a column called "Value".
This fails:
insert into mykeyvalues (Key,Value) values ('FooKey', 'FooValue')
"Incorrect syntax near the keyword 'key'."
Maybe I shouldn't call it "Key", but I just wonder if it is possible to work with a column whose name is a sql keyword?
Thanks
You can surround column names like that with [ ] brackets. Therefore:
insert into mykeyvalues ([Key],[Value]) values ('FooKey', 'FooValue')
Use either backticks (`) or double quotes (") around the identifiers in your query. For example:
INSERT INTO mykeyvalues ("Key", "Value") values ('FooKey', 'FooValue')
But in the long-run, this just reduces portability. It's easier to use a different name.