T-SQL 101: #31 Understanding batches, scripts, and GO

The image below shows a T-SQL script.

It's an example of contents of a file that you could have on your disk so the entire thing could be called MyProgram.sql. Inside this script file, we've got a few different types of things happening here.

The word script applies to all of the contents of the file.

You can see the word GO there a number of times. It's a special word that's not actually a T-SQL keyword. It's a batch separator. It only has meaning to the tool you're using to execute queries, like SQL Server Management Studio or Azure Data Studio.

When you execute a script, it might look like it's all sent to the server at once, but that's not what happens. SSMS finds the word GO, breaks the script up into batches, and sends them to the server, individually.

So, in this case, the following four batches are sent, one batch at a time:

  1. USE master;
  2. CREATE DATABASE Interesting;
  3. USE Interesting;
  4. CREATE TABLE dbo.Information
    ( InformationID int,
    Thoughts varchar(20)
    );
    INSERT INTO dbo.Information
    VALUES (1, 'Hello');

We describe Batch 4 as having two statements, the CREATE TABLE statement, and the INSERT statement.

What is GO really?

I mentioned that GO is a batch separator. You could actually use almost anything instead of GO. In the Tools>Options>Query Execution>SQL Server section in SSMS, you could change it to something else.

I'd suggest that you avoid changing it because you want your scripts to run on other machines and programs as well, and GO is the standard batch separator.

I have a Star Trek friend. All his scripts have the word ENGAGE instead of GO.

And of course a nasty trick for new DBAs is to change it to the word SELECT and watch them try to work out what's wrong.

Learning T-SQL

It's worth your while becoming proficient in SQL. If you'd like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

Leave a Reply

Your email address will not be published.