Skip to content

T-SQL in PostgreSQL?

Having worked w/ Microsoft SQL Server for the vast majority of my professional career, my first encounter w/ PostgreSQL was one where I assumed I could write T-SQL to update some tables based on some fairly straightforward logic, just like I had been doing for years working w/ SQL Server. But T-SQL doesn’t exist in PostgreSQL and while it does have plpgsql, its usage is not as straightforward as T-SQL (in my biased opinion).

Enter PostgreSQL anonymous functions. Anonymous functions allow you to execute transient code one time using DO. I showed this in a post I did about testing for empty record variables in PostgreSQL here. The basic syntax is as follows:

DO $$
    -- declare variables here
    -- run your logic here

To run this anonymous code block, simply highlight it in pgAdmin or whichever database management tool you use, and execute it. The official documentation can be found here.

Published inTips & Tricks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *