What is the PostgreSQL equivalent to the TSQL "go" statement?
Solution 1
The PostgreSQL equivalent would be:
DROP TABLE IF EXISTS tableName;
So the terminator is simply the SQL standard semi-colon ;
.
Solution 2
From SQL Server documentation:
GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.
The syntax permits to have a number, after the keyword go, to repeat previous lines a number of times. Syntax is:
GO [count]
It separates batch. There is not an equivalent for PostgreSQL. The semicolon ends a statement, not a batch. And it is not possible to specify a number of executions.
Go references: https://msdn.microsoft.com/it-it/library/ms188037.aspx
Solution 3
It depends. GO
is separator (delimiter) - it is special keyword that is not used in any SQL statement. PostgreSQL uses semicolon ;
as separator. In console psql you can use \g
postgres=# select 10 as a
postgres-# \g
+----+
| a |
+----+
| 10 |
+----+
(1 row)
but it is not used often. Sometimes people uses \gset
that execute SQL statement and store result to psql
local variables. PostgreSQL can use semicolon, because PostgreSQL SQL statements has not to contain this symbol - It is different against T-SQL, because T-SQL allows some procedural constructs directly in SQL - and then T-SQL requires special separator. PostgreSQL doesn't allow it - procedural code is entered as string - and it is separated by apostrophes or custom string separators. So procedural conditional drop can looks like:
DO $$BEGIN
IF EXISTS (SELECT * FROM information_schema.tables
WHERE table_name = 'someTable') -- attention CASE SENSITIVITY
THEN
DROP TABLE "someTable"; -- attention CASE SENSITIVE syntax
END IF;
END $$;
or more simply DROP TABLE IF EXISTS someTable
(case insensitive syntax). I used custom string separator $$
DO $$ -- DO command with start of string (started by custom separator)
... -- some procedural code
$$ ; -- end string by custom separator and semicolon as end of DO command
Joseph Idziorek
I lead product for Amazon DocumentDB at AWS and work across a number of our purpose-built database services.
Updated on July 22, 2022Comments
-
Joseph Idziorek almost 2 years
In T-SQL, I can state:
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'tableName') DROP TABLE [dbo].[tableName] go
What is the batch terminator equivalent (i.e. "go") for the following SQL command?
DROP TABLE IF EXISTS tableName
-
NathanAldenSr over 7 yearsI disagree that the semicolon is the equivalent of
GO
.GO
is a batch statement terminator. Several statements may be executed within a batch, andGO
terminates that batch.GO
is important because it can be used to create a single script containing normal statements and statements that must be the only statement in a batch.