What is the difference between ";" and "GO" in T-SQL?
A semicolon ;
is a statement separator marking the end of individual T-SQL statements. Useful when crafting complex statements or combining multiple queries in a single line.
Conversely, GO
instructs SQL Server Management Studio (SSMS) or SQLCMD utility to ship the current batch of T-SQL statements for execution. It's not recognized by SQL Server and can't be parsed as valid T-SQL—yet it proves critical in managing "batches" of statements.
Example with ;
:
Example with GO
:
Taking a deeper dive into ";" and "GO"
Unpacking the ";" in T-SQL
The semicolon ;
is like a small whistle, bringing a single T-SQL statement to a halt. It's used predominantly for clarity, especially when statements are complex or multiple queries reside on one line. For instance:
Indeed, it's not yet mandatory to use semicolons in SQL Server, but it's a good habit to cultivate. They can prevent certain types of errors from cropping up in the future.
The big role of "GO" in batching commands
The GO
command is like a traffic light, managing the flow of your SQL script. It's not part of T-SQL—rather, it's a signal for client tools like SSMS or sqlcmd. "GO" informs them to submit the batch of T-SQL statements accumulated so far to SQL Server.
We can also make coding fun by asking "GO" to repeat the batch of commands a specific number of times:
Navigating DDL operations: the critical role of "GO"
If you've decided to create or alter schema objects like tables and stored procedures, remember the GO
command comes to the rescue. It splits the SQL script into manageable units and ensures all preceding commands are properly executed and committed:
Without GO
between CREATE
and ALTER
, SQL Server might throw an error because it interprets the entire script as a single batch.
Pitstop: How "GO" affects transactions
Contrary to some beliefs, GO
does not commit open transactions. It's merely a signal to SSMS or SQLCMD to send the completed batch to SQL Server.
In this example, GO
ends up causing an error because you aren't allowed to split a transaction between batches.
Touring through multiple result sets
"GO" allows your SQL script to produce multiple result sets, and each is handled as a separate unit by the client application:
Traveling with clients: ADO.NET and "GO"
Remember, if your journey includes client-side tools like ADO.NET, they don't speak the language of "GO". It's a term understood only by SQL Server-centric tools like SSMS and sqlcmd.
Was this article helpful?