-- Start an anonymous code block using DO and dollar-quoting $$
DO $$
-- Declare the variable sectionDECLARE-- Declare a VARCHAR variable named 'name' and assign it a value
name VARCHAR :='Himanshu';
BEGIN-- Display the value of the variable using RAISE NOTICE (used for debugging/output)
RAISE NOTICE 'Name is %', name;
-- You can also perform other logic here (loops, conditions, etc.)END $$;
-- End of the anonymous DO block
🌍 Local vs Global Variables
🔧 Type
🟦 MSSQL
🟨 PostgreSQL
Local Variable
DECLARE @var inside procedures/functions
DECLARE var in DO $$ or function block
Global Variable
❌ Not supported directly
❌ Not supported directly
Workaround
Use temp tables or context_info()
Use pg_variables extension or SET configs
System Variables
✅ Uses @@ prefix, e.g., @@ROWCOUNT
✅ Uses SHOW, SET, or current_setting()
🔧 System/Environment Variables
🟦 MSSQL System Variables (@@ prefixed)
Variable
Description
@@VERSION
SQL Server version
@@ROWCOUNT
Rows affected by last statement
@@IDENTITY
Last inserted ID in session
@@ERROR
Error number of last statement
@@TRANCOUNT
Current open transactions
🟨 PostgreSQL Environment Access
SQL
SHOW server_version;
SELECT current_setting('server_version');
SET work_mem ='32MB';
To create pseudo-global/session-level variables:
SQL
SET my.custom_var ='hello'; -- needs custom configuration prefix
🔁 Example: Loop Using Variables
🟨 PostgreSQL
SQL
DO $$
DECLARE
counter INT :=1;
BEGIN
WHILE counter <=3 LOOP
RAISE NOTICE 'Counter = %', counter;
counter := counter +1;
END LOOP;
END $$;
✨ Real Use Case: Get Last Inserted ID
🟦 MSSQL
Java
INSERT INTO Employees(Name) VALUES ('John');
SELECT SCOPE_IDENTITY() AS LastID;
🟨 PostgreSQL
Bash
INSERT INTO Employees (Name) VALUES ('John') RETURNING id;