-3

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sr90
  • 67
  • 1
  • 7
  • 2
    You should read a tutorial somewhere about SQL... – Michael Laffargue Mar 23 '12 at 08:42
  • 1
    `[]` is Microsoft non-standard way of quoting names that contain special characters. You should avoid using them (because it means you are using special characters in your names which is not really a good thing) –  Mar 23 '12 at 08:42
  • @a_horse_with_no_name: One should avoid using them in production code, perhaps. They are extremely useful in testing e.g. to return column names meaningful to the reader but would never make approval for the enterprise's data dictionary :) – onedaywhen Mar 23 '12 at 09:53
  • @onedaywhen: it's OK for an alias but not for a real column name. And I still prefer the standard ANSI quoting style using `"`. –  Mar 23 '12 at 10:09

2 Answers2

2

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
onedaywhen
  • 55,269
  • 12
  • 100
  • 138
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

() 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.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277