In this lab ⌄
Before you start
This page is an English adaptation covering every task and the SQL queries, with concise explanations. The downloadable 49-page manual contains the full Italian commentary. Table names and values remain those of the original exercise.
The original setup scripts, assignment, teacher’s solutions and accompanying Oracle/APEX document are now available below. Use an empty, dedicated lab database.
The assignment is by Professor Moscato, as identified by the author. Antonio Ferone curated the explanatory material. This is a personal study resource.
Prepare the database
For the course workflow use Oracle Database XE 21c and SQL Developer. In a default local lab the connection uses host
localhost
, port
1521
and service name
XEPDB1
. Check these values against your installation and select Service name rather than SID.
Create a dedicated user
Using a database administrator connected to XEPDB1, create UNINA if it does not already exist. Replace the password placeholder first. If UNINA already contains objects, inspect them rather than deleting or reinitialising it.
Scroll horizontally to read the complete lines. ↔
CREATE USER unina
IDENTIFIED BY "INSERISCI_UNA_PASSWORD_PERSONALE"
QUOTA 100M ON USERS;
GRANT CREATE SESSION, CREATE TABLE,
CREATE VIEW, CREATE SEQUENCE TO unina;
Load the original setup script
Create a connection for UNINA, open
unina_spotify_setup_oracle.sql
and run the script with F5. Work in an empty lab schema: the script creates tables and data and does not reset an existing exercise. Run individual SELECT statements with Ctrl+Enter.
Check the data
Scroll code ↔
SELECT 'ARTISTI' AS tabella, COUNT(*) AS righe FROM ARTISTI
UNION ALL SELECT 'STUDENTI', COUNT(*) FROM STUDENTI
UNION ALL SELECT 'BRANI', COUNT(*) FROM BRANI
UNION ALL SELECT 'ASCOLTI', COUNT(*) FROM ASCOLTI;
Expected counts: ARTISTI 6, STUDENTI 11, BRANI 18, ASCOLTI 72. APEX, ORDS and Tomcat belong to the separate web application setup. Explore the Oracle/APEX environment resource .
Download the complete study pack ↓
Original materials and downloads
Original materials are kept separate from my commentary. Course PDFs are in Italian. Attempt the assignment first, then compare your reasoning with the solutions.
Understand the tables
| Table | One row represents | Key |
|---|---|---|
| ARTISTI | An artist or band | id_artista |
| STUDENTI | A student | id_studente |
| BRANI | A catalogue track | id_brano |
| ASCOLTI | A listening event | id_ascolto |
The manual describes 6 artists, 11 students, 18 tracks and 72 listening events. Follow the keys before deciding which joins or aggregates you need.
BRANI.artista = ARTISTI.id_artista
ASCOLTI.brano = BRANI.id_brano
ASCOLTI.studente = STUDENTI.id_studente
The original assignment before the solutions
The following is the original assignment in Italian, transcribed from the provided course document. English task descriptions and explanations follow in the worked exercises. Task 17 contains two queries.
Original task 1
Trovare titolo, nome dell'artista e durata dei brani di genere 'Rock progressivo' oppure 'Hard rock' più lunghi di 240 secondi, dal più lungo al più breve.
Original task 2
Trovare nickname e titolo del brano per tutti gli ascolti completi (secondi ascoltati pari alla durata del brano) fatti dagli studenti del corso 'Data Science', ordinati per nickname e poi per titolo.
Original task 3
Trovare nickname dello studente, titolo del brano, nome dell'artista e data e ora di tutti gli ascolti effettuati nel mese di aprile 2026, in ordine cronologico.
Original task 4
Per ogni genere, trovare il numero di brani e la durata media in secondi (con un decimale). Ordinare dal genere con più brani; a parità di numero, in ordine alfabetico di genere.
Original task 5
Per ogni artista di tipo 'GRUPPO' ascoltato da più di 5 studenti distinti, trovare il nome, il numero di studenti distinti che lo hanno ascoltato e il totale dei secondi ascoltati. Ordinare dal totale più alto.
Original task 6
Per ogni brano, calcolare la percentuale media di ascolto, cioè i secondi ascoltati rispetto alla durata del brano, espressa in percentuale con un decimale. Mostrare solo i brani con una percentuale media inferiore al 90%, dalla più bassa. Suggerimento: il calcolo ha la forma ROUND(AVG(A.secondi_ascoltati / B.durata_secondi) * 100, 1).
Original task 7
Trovare il titolo di tutti i brani con il numero di ascolti ricevuti, compresi i brani mai ascoltati (che devono comparire con 0). Ordinare dal meno ascoltato al più ascoltato; a parità, in ordine alfabetico di titolo.
Original task 8
Per ogni corso di studi, trovare il numero di studenti iscritti e il numero complessivo di ascolti, anche per i corsi in cui nessuno ha ascoltato niente. Ordinare dal corso con più ascolti.
Original task 9
Trovare titolo, nome dell'artista e durata del brano più lungo.
Original task 10
Trovare il titolo del brano con il maggior numero di ascolti, con il numero di ascolti.
Original task 11
Trovare il nickname degli studenti con il maggior numero di ascolti, con il numero di ascolti.
Original task 12
Trovare il nickname degli studenti che hanno ascoltato almeno un brano di un artista italiano, in ordine alfabetico.
Original task 13
Trovare i brani (titolo, genere, durata) più lunghi della durata media dei brani dello stesso genere. Ordinare per genere e, dentro ogni genere, per durata decrescente.
Original task 14
Trovare il nickname degli studenti che non hanno mai ascoltato un brano di genere 'Rap', in ordine alfabetico.
Original task 15
Trovare il nickname degli studenti che hanno ascoltato tutti i brani dei Pink Floyd, in ordine alfabetico.
Original task 16
Creare una vista V_ASCOLTI_DETTAGLIO con nickname, corso di studi, titolo, genere, nome dell'artista, data e ora e secondi ascoltati di ogni ascolto. Usare la vista per trovare, per ogni artista ascoltato dagli studenti del corso 'Data Science', il numero di ascolti e il totale dei secondi ascoltati, dal più ascoltato (a parità, ordine alfabetico).
Original task 17
Trovare il nickname degli studenti che hanno ascoltato i Pink Floyd ma non i Queen. Poi trovare il nickname di chi ha ascoltato sia i Queen sia gli AC/DC.
Original task 18
Trovare il numero di ascolti per ciascun mese dell'anno (da 1 a 12), compresi i mesi senza ascolti, che devono comparire con 0.
The exercises
Choose a task or follow the sequence from basic filtering to joins, aggregates, subqueries and set operations.
- 1. Rock tracks longer than 240 seconds
- 2. Complete listens by Data Science students
- 3. Listens in April 2026
- 4. Track count and mean duration by genre
- 5. Bands heard by more than five students
- 6. Mean listening percentage below 90%
- 7. All tracks, including tracks with no listens
- 8. Students and listening events by degree programme
- 9. The longest track
- 10. The most-played track
- 11. Students with the most listens
- 12. Students who have heard Italian artists
- 13. Tracks longer than their genre average
- 14. Students who have never listened to Rap
- 15. Students who have heard every Pink Floyd track
- 16. A detail view and Data Science summary
- 17a. Pink Floyd but not Queen
- 17b. Both Queen and AC/DC
- 18. Listening counts for all months of 2026
1. Rock tracks longer than 240 seconds
Show the title, artist and duration of Progressive rock or Hard rock tracks longer than 240 seconds, longest first.
Scroll code ↔
SELECT B.titolo, AR.nome AS artista, B.durata_secondi
FROM BRANI B
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE B.genere IN ('Rock progressivo', 'Hard rock')
AND B.durata_secondi > 240
ORDER BY B.durata_secondi DESC;
How to reason about it
Join BRANI to ARTISTI through the artist key. IN groups the two permitted genres; AND applies the duration threshold to both. ORDER BY sorts tracks without aggregating them.
Common pitfall
Do not omit parentheses when replacing IN with OR: AND has higher precedence. A track lasting exactly 240 seconds is excluded.
2. Complete listens by Data Science students
List the nickname and track title for each complete listen by a Data Science student, ordered by nickname and title.
SELECT S.nickname, B.titolo
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
JOIN BRANI B ON B.id_brano = A.brano
WHERE S.corso_studio = 'Data Science'
AND A.secondi_ascoltati = B.durata_secondi
ORDER BY S.nickname, B.titolo;
How to reason about it
Start from listening events, join the student and track, then compare seconds listened with the track duration. Each output row represents an event, even when nickname and title are repeated.
Common pitfall
DISTINCT or GROUP BY would remove legitimate repeated events. A complete listen here means equality, following the exercise definition.
3. Listens in April 2026
Show the student, track, artist and timestamp of listens in April 2026, in chronological order.
Scroll code ↔
SELECT S.nickname, B.titolo, AR.nome AS artista, A.data_ora
FROM ASCOLTI A
JOIN STUDENTI S ON S.id_studente = A.studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE A.data_ora >= TIMESTAMP '2026-04-01 00:00:00'
AND A.data_ora < TIMESTAMP '2026-05-01 00:00:00'
ORDER BY A.data_ora;
How to reason about it
Use an inclusive lower bound at 1 April and an exclusive upper bound at 1 May. Typed TIMESTAMP literals avoid depending on session date formats and preserve the time component.
Common pitfall
Filtering only the month mixes different years. BETWEEN including 1 May would admit an event outside April.
4. Track count and mean duration by genre
For each genre, count tracks and calculate mean duration rounded to one decimal place. Sort by count descending, then genre.
Scroll code ↔
SELECT genere, COUNT(*) AS num_brani,
ROUND(AVG(durata_secondi), 1) AS durata_media
FROM BRANI
GROUP BY genere
ORDER BY num_brani DESC, genere;
How to reason about it
BRANI already contains every required column. GROUP BY changes the output grain from one track to one genre. COUNT(*) counts tracks and AVG calculates their mean duration.
Common pitfall
Joining listening events would weight frequently played tracks more heavily. COUNT(DISTINCT genere) inside a genre group does not count its tracks.
5. Bands heard by more than five students
For bands heard by more than five distinct students, show the band, student count and total seconds listened.
Scroll code ↔
SELECT AR.nome AS artista,
COUNT(DISTINCT A.studente) AS num_studenti,
SUM(A.secondi_ascoltati) AS secondi_totali
FROM ARTISTI AR
JOIN BRANI B ON B.artista = AR.id_artista
JOIN ASCOLTI A ON A.brano = B.id_brano
WHERE AR.tipo_artista = 'GRUPPO'
GROUP BY AR.id_artista, AR.nome
HAVING COUNT(DISTINCT A.studente) > 5
ORDER BY secondi_totali DESC;
How to reason about it
Follow ARTISTI to BRANI to ASCOLTI. WHERE selects bands before grouping; COUNT(DISTINCT A.studente) counts people once per artist. SUM includes every listening event and HAVING applies the group threshold.
Common pitfall
SUM(DISTINCT seconds) would discard unrelated events with the same duration. The threshold is strictly greater than five.
6. Mean listening percentage below 90%
Find tracks whose average listening percentage is below 90%, following the formula in the query.
Scroll code ↔
SELECT B.titolo,
ROUND(AVG(A.secondi_ascoltati / B.durata_secondi) * 100, 1) AS perc_media
FROM BRANI B
JOIN ASCOLTI A ON A.brano = B.id_brano
GROUP BY B.id_brano, B.titolo
HAVING AVG(A.secondi_ascoltati / B.durata_secondi) < 0.9
ORDER BY perc_media, B.titolo;
How to reason about it
Join each listening event to its track and divide listened seconds by track duration before averaging. GROUP BY creates one result per track; HAVING filters the resulting average.
Common pitfall
The average of percentages is not interchangeable with an unrelated total or mean. Check the denominator and handle zero-duration tracks if the dataset rules change.
7. All tracks, including tracks with no listens
Show every track and its listening count, retaining tracks that have never been played.
Scroll code ↔
SELECT B.titolo, COUNT(A.id_ascolto) AS num_ascolti
FROM BRANI B
LEFT JOIN ASCOLTI A ON A.brano = B.id_brano
GROUP BY B.id_brano, B.titolo
ORDER BY num_ascolti, B.titolo;
How to reason about it
Start from the complete track catalogue and LEFT JOIN listening events. COUNT of the event key counts only matching events, giving zero for tracks without a match.
Common pitfall
COUNT(*) also counts the preserved outer-join row and would report one instead of zero. An inner join removes unplayed tracks.
8. Students and listening events by degree programme
Summarise students and listening events by degree programme, retaining students without listens.
Scroll code ↔
SELECT S.corso_studio,
COUNT(DISTINCT S.id_studente) AS num_studenti,
COUNT(A.id_ascolto) AS num_ascolti
FROM STUDENTI S
LEFT JOIN ASCOLTI A ON A.studente = S.id_studente
GROUP BY S.corso_studio
ORDER BY num_ascolti DESC, S.corso_studio;
How to reason about it
Start from STUDENTI and preserve students with a LEFT JOIN. A student can match multiple events, so count distinct students separately from non-null event identifiers.
Common pitfall
COUNT(*) measures joined rows, not necessarily people. Decide which entity each aggregate must count.
9. The longest track
Find the longest track or tracks, including ties.
Scroll code ↔
SELECT B.titolo, AR.nome AS artista, B.durata_secondi
FROM BRANI B
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE B.durata_secondi = (SELECT MAX(durata_secondi) FROM BRANI)
ORDER BY B.titolo;
How to reason about it
Compare duration with a scalar MAX over the track catalogue. Every row with the maximum duration qualifies, preserving ties naturally.
Common pitfall
An arbitrary first row may hide ties. Empty catalogues and NULL durations must be considered if the data assumptions change.
10. The most-played track
Find the track or tracks with the greatest listening count, preserving ties.
Scroll code ↔
SELECT B.titolo, COUNT(*) AS num_ascolti
FROM BRANI B
JOIN ASCOLTI A ON A.brano = B.id_brano
GROUP BY B.id_brano, B.titolo
HAVING COUNT(*) = (
SELECT MAX(num_ascolti)
FROM (SELECT COUNT(*) AS num_ascolti FROM ASCOLTI GROUP BY brano)
)
ORDER BY B.titolo;
How to reason about it
Aggregate events by track before comparing counts. The maximum must be calculated at the same grain as the result: one track, rather than one individual event.
Common pitfall
Sorting and taking a single row can silently discard tied winners. Whether zero-listen tracks must be considered depends on the definition and starting relation.
11. Students with the most listens
Find the student or students with the highest number of listening events.
Scroll code ↔
SELECT S.nickname, COUNT(*) AS num_ascolti
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
GROUP BY S.id_studente, S.nickname
HAVING COUNT(*) = (
SELECT MAX(num_ascolti)
FROM (SELECT COUNT(*) AS num_ascolti FROM ASCOLTI GROUP BY studente)
)
ORDER BY S.nickname;
How to reason about it
Count listening events per student, then retain every group whose count equals the maximum group count. Distinguish the student identifier from a displayed nickname.
Common pitfall
Repeated listens remain separate events. A solution using one arbitrary top row does not preserve ties.
12. Students who have heard Italian artists
Find students with at least one listening event for an Italian artist.
Scroll code ↔
SELECT S.nickname
FROM STUDENTI S
WHERE EXISTS (
SELECT 1
FROM ASCOLTI A
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE A.studente = S.id_studente AND AR.paese = 'Italia'
)
ORDER BY S.nickname;
How to reason about it
Follow the keys from student to event, track and artist. A correlated EXISTS answers a presence question without multiplying the outer student row.
Common pitfall
Several qualifying events should not create several copies of the same student. Filter nationality using the exact values defined in the source dataset.
13. Tracks longer than their genre average
Find tracks whose duration exceeds the average duration of tracks in the same genre.
SELECT B.titolo, B.genere, B.durata_secondi
FROM BRANI B
WHERE B.durata_secondi > (
SELECT AVG(B2.durata_secondi)
FROM BRANI B2
WHERE B2.genere = B.genere
)
ORDER BY B.genere, B.durata_secondi DESC;
How to reason about it
Correlate the average to the outer track genre. The subquery builds a separate comparison group for each genre; the outer query retains individual tracks.
Common pitfall
A global average asks a different question. Greater than excludes tracks exactly equal to their genre average.
14. Students who have never listened to Rap
Find students without any Rap listening events, including students with no events at all.
Scroll code ↔
SELECT S.nickname
FROM STUDENTI S
WHERE NOT EXISTS (
SELECT 1
FROM ASCOLTI A
JOIN BRANI B ON B.id_brano = A.brano
WHERE A.studente = S.id_studente AND B.genere = 'Rap'
)
ORDER BY S.nickname;
How to reason about it
For each student, the correlated subquery searches for a Rap event. NOT EXISTS accepts the student only when that search returns no rows.
Common pitfall
A non-Rap event does not prove the absence of Rap events. An initial inner join would discard students who have no listening history.
15. Students who have heard every Pink Floyd track
Find students who have listened to every Pink Floyd track in the catalogue.
Scroll code ↔
SELECT S.nickname
FROM STUDENTI S
WHERE NOT EXISTS (
SELECT 1
FROM BRANI B
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE AR.nome = 'Pink Floyd'
AND NOT EXISTS (
SELECT 1 FROM ASCOLTI A
WHERE A.studente = S.id_studente AND A.brano = B.id_brano
)
)
ORDER BY S.nickname;
How to reason about it
The inner NOT EXISTS detects a required track missing from the student's history. The outer NOT EXISTS accepts only students for whom no required track is missing.
Common pitfall
Repeated plays cannot compensate for a missing track. If the required track set is empty, this logical form accepts every student; the intended empty-set rule must be explicit.
16. A detail view and Data Science summary
Create a view of listening details, then use it to summarise Data Science listening events and total seconds per artist.
Scroll code ↔
CREATE OR REPLACE VIEW V_ASCOLTI_DETTAGLIO AS
SELECT S.nickname, S.corso_studio, B.titolo, B.genere,
AR.nome AS artista, A.data_ora, A.secondi_ascoltati
FROM ASCOLTI A
JOIN STUDENTI S ON S.id_studente = A.studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista;
SELECT artista, COUNT(*) AS num_ascolti,
SUM(secondi_ascoltati) AS secondi_totali
FROM V_ASCOLTI_DETTAGLIO
WHERE corso_studio = 'Data Science'
GROUP BY artista
ORDER BY num_ascolti DESC, artista;
How to reason about it
Create the view first in the schema that owns the tables and has CREATE VIEW permission. The view describes individual events; the final query filters the programme and aggregates by artist.
Common pitfall
An ordinary view stores a query definition, not a separate snapshot of the events. Presentation order belongs in the final SELECT.
17a. Pink Floyd but not Queen
Find students who have listened to Pink Floyd but have never listened to Queen.
SELECT S.nickname
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE AR.nome = 'Pink Floyd'
MINUS
SELECT S.nickname
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE AR.nome = 'Queen'
ORDER BY 1;
How to reason about it
The first SELECT builds the Pink Floyd listener set. MINUS subtracts the Queen listener set, using compatible output columns. ORDER BY applies to the final difference.
Common pitfall
Reversing the SELECT blocks changes the question. Filtering a single artist row with <> Queen does not rule out Queen listens elsewhere.
17b. Both Queen and AC/DC
Find students who have listened to at least one Queen track and at least one AC/DC track.
SELECT S.nickname
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE AR.nome = 'Queen'
INTERSECT
SELECT S.nickname
FROM STUDENTI S
JOIN ASCOLTI A ON A.studente = S.id_studente
JOIN BRANI B ON B.id_brano = A.brano
JOIN ARTISTI AR ON AR.id_artista = B.artista
WHERE AR.nome = 'AC/DC'
ORDER BY 1;
How to reason about it
INTERSECT keeps nicknames shared by the two listener sets and removes repeated rows. The two qualifying listening events can be different events on different dates.
Common pitfall
A single artist row cannot have both names at once. UNION means either set, while counting two events alone does not establish two different artists.
18. Listening counts for all months of 2026
Show listening counts for all twelve months of 2026, returning zero for months with no events.
Scroll code ↔
WITH mesi AS (
SELECT LEVEL AS mese FROM dual CONNECT BY LEVEL <= 12
)
SELECT M.mese, COUNT(A.id_ascolto) AS num_ascolti
FROM mesi M
LEFT JOIN ASCOLTI A
ON EXTRACT(MONTH FROM A.data_ora) = M.mese
AND A.data_ora >= TIMESTAMP '2026-01-01 00:00:00'
AND A.data_ora < TIMESTAMP '2027-01-01 00:00:00'
GROUP BY M.mese
ORDER BY M.mese;
How to reason about it
Generate months independently with LEVEL and CONNECT BY. LEFT JOIN events using both month and year bounds in ON, then count non-null event keys and group by month.
Common pitfall
A WHERE condition on the right-side timestamp would remove unmatched months. COALESCE cannot generate absent month rows, and COUNT(*) counts the preserved row.
Compare with the teacher’s solutions
1. Comma joins and explicit JOIN
The teacher joins BRANI and ARTISTI through WHERE; this guide uses JOIN ... ON. Here they express the same relationship; explicit JOIN separates relationships from filters.
3. EXTRACT and a time interval
The teacher uses EXTRACT on year and month. The guide uses inclusive start and exclusive end for April 2026. Both express that month; performance requires indexes and an execution plan.
12. IN and EXISTS
The teacher uses IN while the guide uses correlated EXISTS. For this task both test for at least one qualifying event without repeating the student for each event.
18. Calendar generation and year scope
The teacher generates months with a recursive CTE and matches the month number. The guide uses CONNECT BY and limits events to 2026. They agree on the provided 2026 data; with multiple years the year filter changes the meaning and must be explicit.
Run the exercises with SQLite
The SQLite setup creates the same exercise in a new database. Oracle queries cannot all be copied unchanged: MINUS becomes EXCEPT, date functions and calendar generation change, and the view uses CREATE VIEW.
The percentage in task 6
AVG(1.0 * A.secondi_ascoltati / B.durata_secondi)
The 1.0 factor preserves the fractional part: in SQLite integer division can truncate it before the average is computed. The adapted file includes this and the other dialect changes.
Check your reasoning
For each query, state what one result row represents. Check join keys, repeated events, missing rows, NULL values and ties. Then explain an alternative form and a counterexample to a plausible wrong solution.
For this update I loaded the SQLite script into a local in-memory database, checked counts and foreign keys, and ran all 19 adapted blocks. Oracle checks remain those reported in the manual; Oracle execution and APEX installation were not repeated for this update.
Sources and attribution
Original assignment: Professor Moscato, identified by Antonio Ferone as his Database course lecturer. Reasoned guide and editorial adaptation: Antonio Ferone. Source documents named in the manual: Esercitazione SQL.pdf, Esercitazione SQL soluzioni.pdf and unina_spotify_setup_oracle.sql.
For collaborative exam preparation, explore ComeSiSupera , an IEEE Student Branch project supported by Antonio.
Original course files are available in Materials. The Oracle/APEX document accompanied the exercise; the linked environment resource explains its context and versions.