I don’t know that you can call SQL code, but I need help debugging some of my Postgres queries that I have for a CS assignment. I am completely lost as to why it is broken like it is.
I am performing the SQL queries on the DVD rental database from www.postgresqltutorial.com.
The assignment is pretty silly and unrealistic, in my opinion, but it’s a post-secondary assignment; so why have realistic expectations.
I am supposed to generate a “real world” business report using the data already within the database and insert it into a new pair of tables: a detailed table and a summary table. The business report I am making is one in which I determine which actors’ movies were most often rented by customers. The idea is to use the count function to determine how many rows in the rental table are associated with each actor_id in the actor table. I was thinking that the broken query is the following:
-- Detailed Table --
INSERT INTO detailed
SELECT a.actor_id, get_actor_name(a.actor_id) as actor_name, COUNT(DISTINCT r.rental_id) AS rental_count
FROM actor AS a
JOIN film_actor AS fa ON a.actor_id = fa.actor_id
JOIN film AS f ON fa.film_id = f.film_id
JOIN inventory AS i ON f.film_id = i.film_id
JOIN rental AS r ON i.inventory_id = r.inventory_id
GROUP BY a.actor_id
ORDER BY rental_count DESC;
However, I am beginning to think that this is not the case. (get_actor_name()
just concatenates the actor_name using the built-in CONCAT()
function. It was one of the assignment’s sillier requirements). The real problem comes down to this:
CREATE OR REPLACE FUNCTION refresh_count_data()
RETURNS TRIGGER
LANGUAGE plpgsql
AS
$$
BEGIN
DELETE FROM detailed;
DELETE FROM summary;
INSERT INTO detailed
SELECT a.actor_id, get_actor_name(a.actor_id), COUNT(f.film_id) AS rental_count
FROM actor AS a
JOIN film_actor AS fa ON a.actor_id = fa.actor_id
JOIN film AS f ON fa.film_id = f.film_id
JOIN inventory AS i ON f.film_id = i.film_id
JOIN rental AS r ON i.inventory_id = r.inventory_id
GROUP BY a.actor_id
ORDER BY rental_count DESC;
INSERT INTO summary (actor_name, rental_count)
SELECT actor_name,rental_count FROM detailed LIMIT 15;
RETURN NULL;
END;
$$;
CREATE TRIGGER refresh_on_new_rental
AFTER INSERT
ON public.rental
FOR EACH STATEMENT
EXECUTE PROCEDURE refresh_count_data();
So I created that trigger and stored procedure, then I performed some queries to insert some fake data into the rental table. I use the summary table to check things. Nothing changed; although, I am fairly certain the trigger is being triggered.
P.S. I don’t know why we cannot just use an UPDATE query in the stored procedure, but I wasted like an hour forming that stored procedure before I realized that the instructions explicitly state that I must delete the data and repopulate it completely. One of the more unrealistic requirements…