Home > Software engineering >  Beginner SQL question - use of square bracket?
Beginner SQL question - use of square bracket?

Time:11-03

I'm getting different return values when using square bracket and was wondering what the bracket is for in this scenario?

SELECT COUNT (distinct customer_id), customer_type
FROM Customers
GROUP BY customer_type

VS

SELECT COUNT (distinct([customer_id])), customer_type
FROM Customers
GROUP BY customer_type

Thanks

I ran the query and it was showing two different results - I'm trying to find out what the bracket does in this situation.

CodePudding user response:

If you utilise special characters or keywords in the column names or identifiers, brackets must be used. You could call a column [First Name] (with a space), but then every time you mentioned that column, you would also need to use brackets.

The more recent tools include them everywhere for consistency or just in case.

CodePudding user response:

They come in handy if the names of your columns coincide with SQL keywords or contain spaces. Placing brackets around column names at all times avoids the query execution engine from becoming confused by characters and reserved words that may be present in the names of the columns. I suppose it's simpler than looking for problems and then fixing them.

Example:

CREATE TABLE SchemaName.TableName (

This would actually create a table by the name SchemaName.TableName under default dbo schema even though the intention might be to create the table inside the SchemaName schema.

The correct way would be the following:

CREATE TABLE [SchemaName].[TableName] (
  • Related