Your question is Refactor SQL to Reduce Debt. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
A Spotify business analytics report joins listen_events (tens of billions of rows) against users, tracks and artists to find US premium listeners' top plays for January 2024. The query technically works, but the team wants five concrete ways to refactor it to reduce technical debt before anyone else has to touch it again.
CREATE TABLE users (
user_id BIGINT PRIMARY KEY,
country VARCHAR(2),
plan_type VARCHAR(20)
);
CREATE TABLE artists (
artist_id BIGINT PRIMARY KEY,
artist_name VARCHAR(300)
);
CREATE TABLE tracks (
track_id BIGINT PRIMARY KEY,
track_name VARCHAR(300),
artist_id BIGINT REFERENCES artists(artist_id)
);
-- listen_events has tens of billions of rows across all users
CREATE TABLE listen_events (
event_id BIGINT PRIMARY KEY,
user_id BIGINT REFERENCES users(user_id),
track_id BIGINT REFERENCES tracks(track_id),
listened_at TIMESTAMP,
ms_played INT
);
SELECT *
FROM listen_events le, tracks t, artists a, users u
WHERE le.track_id = t.track_id
AND t.artist_id = a.artist_id
AND le.user_id = u.user_id
AND u.country = 'US'
AND le.ms_played > 30000
AND (SELECT plan_type FROM users u2 WHERE u2.user_id = le.user_id) = 'premium'
AND le.listened_at BETWEEN '2024-01-01' AND '2024-01-31 23:59:59'
ORDER BY 5 DESC
LIMIT 9999999;
Please find five ways to refactor this SQL code to reduce technical debt. For each one, name the specific line or pattern, explain the risk it creates for the team that maintains this query, and describe your fix.