About the GO Command in SQL Server

If you’ve used T-SQL you will probably be familiar with the GO command. This command is often placed at the end of a batch of statements.

For example:

CREATE DATABASE Books;
GO

However, the GO command is not actually part of T-SQL. It can’t even occupy the same line as a T-SQL statement.

GO is one of the commands that are recognised by the sqlcmd and osql utilities, as well as SQL Server Management Studio Code Editor to facilitate the readability and execution of batches and scripts. The GO command signals the end of a batch of T-SQL statements to the SQL Server utilities.

SQL Server utilities interpret GO as a signal that they should send the current batch of T-SQL statements to an instance of SQL Server. The current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO.

The GO command can be handy when writing larger scripts. When writing larger scripts, you may sometimes get an error, due to certain parts of the script requiring earlier parts to have been executed first. You can place GO at strategic places within the script so that such parts are executed first.

Here’s an example of a script that creates a partitioned table. It has the GO command placed at various places within the script to ensure that each section is executed before the next section.

ALTER DATABASE Test
ADD FILEGROUP MoviesFg1;
GO  
ALTER DATABASE Test  
ADD FILEGROUP MoviesFg2;  
GO  
ALTER DATABASE Test  
ADD FILEGROUP MoviesFg3;  
GO  
ALTER DATABASE Test  
ADD FILEGROUP MoviesFg4;   

ALTER DATABASE Test   
ADD FILE   
(  
    NAME = MoviesFg1dat,  
    FILENAME = '/var/opt/mssql/data/MoviesFg1dat.ndf',  
    SIZE = 5MB,  
    MAXSIZE = 100MB,  
    FILEGROWTH = 5MB  
)  
TO FILEGROUP MoviesFg1;  
ALTER DATABASE Test   
ADD FILE   
(  
    NAME = MoviesFg2dat,  
    FILENAME = '/var/opt/mssql/data/MoviesFg2dat.ndf',  
    SIZE = 5MB,  
    MAXSIZE = 100MB,  
    FILEGROWTH = 5MB  
)  
TO FILEGROUP MoviesFg2;  
GO  
ALTER DATABASE Test   
ADD FILE   
(  
    NAME = MoviesFg3dat,  
    FILENAME = '/var/opt/mssql/data/MoviesFg3dat.ndf',  
    SIZE = 5MB,  
    MAXSIZE = 100MB,  
    FILEGROWTH = 5MB  
)  
TO FILEGROUP MoviesFg3;  
GO  
ALTER DATABASE Test   
ADD FILE   
(  
    NAME = MoviesFg4dat,  
    FILENAME = '/var/opt/mssql/data/MoviesFg4dat.ndf',  
    SIZE = 5MB,  
    MAXSIZE = 100MB,  
    FILEGROWTH = 5MB  
)  
TO FILEGROUP MoviesFg4;  
GO