Create Variables and Blocks with Do / Declare in SQL

Share this video with your friends

Send Tweet

Queries can grow in size and become unreadable pretty quickly. Not to mention error-prone if we have to write out the same value multiple times. Just like in almost any other programming language, variables and blocks can be created within SQL. This gives users the ability to write variables at the top of a block and then be referenced through the following transaction.

Louis St-Amour
Louis St-Amour
~ 4 years ago

This video suggests that "Begin" and "End" are used with transactions. In this context, embedded SQL, they are not used that way:

It is important not to confuse the use of BEGIN/END for grouping statements in PL/pgSQL with the similarly-named SQL commands for transaction control. PL/pgSQL's BEGIN/END are only for grouping; they do not start or end a transaction. See Section 42.8 for information on managing transactions in PL/pgSQL. Also, a block containing an EXCEPTION clause effectively forms a subtransaction that can be rolled back without affecting the outer transaction. For more about that see Section 42.6.8.

See https://www.postgresql.org/docs/current/plpgsql-structure.html