Stored Procedures: A Data Access API
Learn about stored procedures using coding examples.
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:
create or replace function get_all_albums(in name text,out album text,out duration interval)returns setof recordlanguage sqlas $$select album.title as album,sum(milliseconds) * interval '1 ms' as durationfrom albumjoin artist using(artistid)left join track using(albumid)where artist.name = get_all_albums.namegroup by albumorder by album;$$;
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:
create or replace function get_all_albums(in artistid bigint,out album text,out duration interval)returns setof recordlanguage sqlas $$select album.title as album,sum(milliseconds) * interval '1 ms' as durationfrom albumjoin artist using(artistid)left join track using(albumid)where artist.artistid = get_all_albums.artistidgroup by albumorder by album;$$;
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:
select * from get_all_albums(127);
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:
select *from get_all_albums((select artistidfrom artistwhere name = 'Audioslave'));
As we can see, the ...