Stored Procedures: A Data Access API
Learn about stored procedures using coding examples.
We'll cover the following...
When using PostgreSQL, it’s also possible to create server-side functions. Those SQL objects store code and then execute it when called.
How to create stored procedures?
In this section, you’ll learn how to create stored procedures.
The naïve way
The naïve way to create a server-side stored procedure from our current example would be the following:
But giving the name of the artist rather than it’s artistid means that the function won’t be efficient to use and for no good reason.
The improved version
So, instead, we’re going to define a better version that works with an artist ID:
This function is written in PL/SQL, so it’s basically a SQL query that accepts parameters. To run it, simply use the following query:
Of course, if we only have the name of the artist we’re interested in, we don’t need to first do another query.
Using nested query
We can directly fetch the artistid from a subquery:
As we can see, the ...