Back to all posts

Understanding Data Types and Variables in MSSQL vs PostgreSQL

📊 Data Types Comparison Table 🚩 Category 🟦 MSSQL 🟨 PostgreSQL Integer Types INT , BIGINT , SMALLINT INTEGER , BIGINT , SMALLINT , SERIAL Decimal Types …


📊 Data Types Comparison Table

🚩 Category🟦 MSSQL🟨 PostgreSQL
Integer TypesINT, BIGINT, SMALLINTINTEGER, BIGINT, SMALLINT, SERIAL
Decimal TypesDECIMAL, NUMERIC, FLOATNUMERIC, REAL, DOUBLE PRECISION
String TypesVARCHAR, NVARCHAR, TEXTVARCHAR, TEXT, CHARACTER
Date/TimeDATETIME, DATE, TIMETIMESTAMP, DATE, TIME, INTERVAL
BooleanBIT (0/1)BOOLEAN (true, false)
BinaryBINARY, VARBINARY, IMAGEBYTEA
Unique IDUNIQUEIDENTIFIERUUID
JSON / Array❌ Not NativeJSON, JSONB, ARRAY

🧮 How to Declare and Use Variables

🟦 MSSQL

SQL
DECLARE @Name VARCHAR(100);
SET @Name = 'Himanshu';

-- OR
SELECT @Name = 'Himanshu';

🟨 PostgreSQL

SQL
-- Start an anonymous code block using DO and dollar-quoting $$
DO $$
-- Declare the variable section
DECLARE
    -- 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 VariableDECLARE @var inside procedures/functionsDECLARE var in DO $$ or function block
Global Variable❌ Not supported directly❌ Not supported directly
WorkaroundUse 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)

VariableDescription
@@VERSIONSQL Server version
@@ROWCOUNTRows affected by last statement
@@IDENTITYLast inserted ID in session
@@ERRORError number of last statement
@@TRANCOUNTCurrent 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;

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.