Square Brackets in SQL Server

Square brackets

Square brackets are one of the worst things that Microsoft has put into the SQL server. When you execute a query in SQL, you often have already noticed a common error when creating a table, and the table name contains a space like a Student table. It will show an error message like "Incorrect syntax near the table." It's because of the square brackets.

The solution is very simple, put the table name in square brackets. You might encounter columns named keywords. In that case, also you need to use square brackets for that particular column name. So let's look at a practical example of where to use square brackets in SQL Server. The example is developed in SQL Server using the SQL Server Management Studio.

Square Brackets can be used in a variety of situations.

Problem 1. Creating a table in SQL Server

When you create a table with the table name containing a space like in the Student table, it will show an error message like "Incorrect syntax near the table." The following creates a table script.

CREATE TABLE student table

(
            [stu_id] [int] NULL,
            [stu_name] [varchar](20) NULL,
            [marks] [int] NULL,
            [Remarks] [varchar](50) NULL
)

Now press F5 to execute it. It will show an error message.

Table-column-error-in-SQL-Server.jpg

The above error is because of square brackets. The solution is very simple, put the table name in square brackets.

CREATE TABLE [student table]

(
            [stu_id] [int] NULL,
            [stu_name] [varchar](20) NULL,
            [marks] [int] NULL,
            [Remarks] [varchar](50) NULL
)

Now press F5 to execute it.

Table-column-With-square-bracket-in-SQL-Server.jpg

Problem 2. Using columns name as keywords

You define a column name that is also a keyword. The following creates a table with a column named FROM, a keyword script. It will show an error message like "Incorrect syntax near keyword."

Create TABLE [student table]

(
            [stu_id] [int] NULL,
            [stu_name] [varchar](20) NULL,
            [marks] [int] NULL,
            [Remarks] [varchar](50) NULL,
            From  [varchar](20) NULL
)

Now Press F5 to execute it. It will show an error message.

Table-column-error-in-SQL-Server.jpg

The above error is because of square brackets. The solution is very simple, put the table name in square brackets.

Create TABLE [student table]

(
            [stu_id] [int] NULL,
            [stu_name] [varchar](20) NULL,
            [marks] [int] NULL,
            [Remarks] [varchar](50) NULL,
            [From]  [varchar](20) NULL
)

Now Press F5 to execute it.

Table-column-With-square-bracket-in-SQL-Server.jpg

Summary

This article describes the most common uses of square brackets in SQL Server with examples.


Similar Articles