Prev: getting-ready-to-read-this-book Next: a-small-application
How much business logic should we put in the database?
Let’s query the chinook database for an artist’s albums and total duration of each album:
select album.title as album
sum(milliseconds) * interval '1ms' as duration
from album
join artist using(artistid)
left join track using (albumid)
where artist.name = 'Red Hot Chili Peppers'
group by album
order by album;
There are four isolation levels in Postgres:
BEGIN
to COMMIT
.
This means that even if a transaction is going on in the background, it
won’t affect this query.We can create a function that will allow us to do the same query but with the artist_id.
create or replace function get_all_albums
(in artistid bigint,
out album text,
out duration interval
);record
returns setof
language sqlas $$
select album.title as album,
sum(milliseconds) * interval '1 ms' as duration
from album
join artist using(artistid)
left join track using(albumid)
where artist.artistid = get_all_albums.artistid
group by album
order by album;
$$
try to use SQL only instead of PLpgSQL, although you can do that if necessary.
Prev: getting-ready-to-read-this-book Next: a-small-application