Member-only story
PostgreSQL + Python: An Explosive Combination with PL/Python
Sometimes standard SQL just is not enough. What if you need more complex calculations with for example real-time data analysis, or may be access to Python libraries like NumPy and Pandas — right inside your database? That’s where PL/Python comes into “play”. With this extension, you can write Python functions directly in PostgreSQL, making your database far more powerful and flexible.
Why PL/Python?
- Leverage Python Libraries: NumPy, Pandas, and other libraries become available within PostgreSQL.
- Perform Advanced Calculations: Do math, stats, and data transformations without leaving your database.
- Keep It Simple: Write Python code you already know, instead of complicated SQL for every scenario.
Step 1: Enable the Extension
To get started, enable PL/Python in your PostgreSQL:
CREATE EXTENSION plpython3u;
That’s it! Now you can create functions in Python inside your database.
Step 2: Write Your First PL/Python Function
Let’s create a function that calculates the product of all numbers in a given array. This is a simple example, but it shows you the basics.