What is the difference in [ ] and ( ) in SQL? - 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.

Related

Why do you only need double quotation marks in SQL for particular cases?

I have a column in my database table named UID. For some reason queries fail unless I surround the column name with double quotation marks (" "). None of the other columns require these quotation marks.
For example, this doesn't work:
SELECT user_name FROM user_table WHERE UID = '...'
But this does:
SELECT user_name FROM user_table WHERE "UID" = '...'
Is UID some kind of keyword? Why is it only happening to that column? How do I know if I need to use double quotes for other columns?
By the way, I'm running JDK 1.8_221 and using an oracle JDBC driver if that makes a difference.
Yes, it is about keywords. You can double quote everything (tables, columns) to avoid this but I can understand you don't want to do this.
To have a list of standard keywords: SQL Keywords
But you can see UID is not in this list as I assume it is a reserved keyword by your database implementation. I had the same problem with a table called "order" as it contains orders. ORDER is a keyword so I had to quote it each time.
So best is to test your statements using a SQL client tool.
Since you mention Oracle: Oracle keywords: "You can obtain a list of keywords by querying the V$RESERVED_WORDS data dictionary view."
If your create table command for user_table looks something like this:
create table user_table ("UID" varchar2(10))
then you will have to use quotes around UID in your query. This query:
select * from user_table where UID = 'somestring'
means to use the Oracle predefined UID pseudo column and your table's UID column will not be accessed.
If your table doesn't have a user-defined UID column, then using "UID" should fail.
My guess is your table does indeed have a UID column and when you say it "doesn't work" without using the quotes you probably mean it motivates an ORA-1722.
The type of failure, when using UID without quotes, depends on the content of the string 'somestring'. If the content of that string can be cast as a number then you probably won't get the rows you expect. If it cannot be cast as a number then you'll get an ORA-1722.
As an aside, if you try to execute this, then you'll get an ORA-904:
create table user_table (UID number)
Yes, it is keywords and return
UID returns an integer that uniquely identifies the session user (the
user who logged on).
By default, Oracle identifiers (table names, column names, etc.) are case-insensitive. You can make them case-sensitive by using quotes around them when creating them (eg: SELECT * FROM "My_Table" WHERE "my_field" = 1). SQL keywords (SELECT, WHERE, JOIN, etc.) are always case-insensitive.
You can use it for more information here.

Asp Classic & Firbird Sql without quotation marks

I have a script in ASP Classic that uses a Firebird database. I would like to execute a query without "quotation marks"
Now I must write this:
SQL = "SELECT ""TArticoli"".""IDArticolo"",""TArticoli"".""Desc"" FROM ""TArticoli"";"
I would write this:
SQL = "SELECT TArticles.IDArticle, TArticles.Desc FROM TArticles;"
The first one is accepted the second not, how can I do this?
You can't. DESC is a reserved word in Firebird, so to be able to use it as a column name (or any other object name for that matter), you will need to enclose it in quotes.
A second problem is that you are currently using
SELECT "TArticoli"."IDArticolo","TArticoli"."Desc" FROM "TArticoli"
And this means both your table name and the column names are case sensitive, and in that case, quoting those object names is mandatory. Unquoted object names are case insensitive, but are mapped to object names in upper case. This means that select * from TArticoli will select from a table called TARTICOLI, while select * from "TArticoli", selects from a table called TArticoli.
So unless you are going to rename or recreate all your tables or columns, you will not be able to get rid of quotes. The only thing you can do to reduce the number of quotes, is by not prefixing the columns with the table names (in the query shown it isn't necessary), or otherwise use a case insensitive alias for the table, eg
SELECT "IDArticolo", "Desc" FROM "TArticoli"
or
SELECT a."IDArticolo", a."Desc" FROM "TArticoli" AS a

SQL Select statement - The thing i am querying for has a single quotation mark

Hi everyone I am new to StackOverflow and SQL. I am not sure how to phrase the title so google was not very helpful.
I am doing a simple SELECT query:
SELECT * FROM Department WHERE DepartmentName = "Controller's Office"
I would like to return all results that has DepartmentName of "Controller's Office". The name itself has a single quotation that must not be removed(because boss said so). Using single quotation marks does not work. and returns an error:
Invalid column name 'Controller's Office'.
How can i do the query so that it works? If you are doing anything complicated please explain because i am new thanks!
Most variants of SQL (you don't specify what you are using) will let you escape single quotes using another single quote:
SELECT * FROM Department WHERE DepartmentName = 'Controller''s Office'
Double quotes (in most of the variants of SQL that I know) are used to delimit identifiers (column and table names) that contain characters that are not otherwise valid in an identifier's name.

How to write a column name with dot (".") in the SELECT clause?

I'm trying to write a column name using "." with no success
sample:
SELECT PrmTable.Value = MAX(Value)
FROM TempTable
or
SELECT MAX(Value) AS PrmTable.Value
FROM TempTable
Any idea ?
Just enclose it in square brackets, and it will work
e.g.
SELECT MAX(Value) AS [PrmTable.Value]
FROM TempTable
I would not recommend you use field names which always require you to enclose the name in brackets, it becomes a pain.
Also the period is used in SQL Server to denote schema and database name separators. Using your field name the full name for a field becomes:
[DatabaseName].[SchemaName].[TableName].[FieldName.WithPeriod]
That just looks odd and would probably confuse other DBAs. Use an underscore to separate words in your field names, it's a much more common style:
[DatabaseName].[SchemaName].[TableName].[FieldName_WithUnderscore]
SELECT [PrmTable.Value] = MAX(Value)
FROM TempTable
or
SELECT MAX(Value) AS [PrmTable.Value]

[] brackets in sql statements

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)