SQL Queries
SQL | MySQL
The following SQL queries were created for a database of a competitive swimming organization. The database contains information about swimmers, their caretakers, their participation in events and meets, and their history of performance levels. The queries demonstrate various SQL concepts such as JOINs, GROUP BY, HAVING, CTEs, and EXCEPT.
Query to obtain the names of all primary and secondary caretakers of every swimmer.
SELECT CONCAT(s.fname, ' ', s.lname) AS swimmer, CONCAT(c.fname, ' ', c.lname) AS caretaker, 'primary' AS `type`
FROM swimmer AS s LEFT JOIN caretaker AS c ON (c.CT_Id = s.Main_CT_Id)
UNION
SELECT CONCAT(s.fname, ' ', s.lname) AS swimmer, CONCAT(c.fname, ' ', c.lname) AS caretaker, 'secondary' AS `type`
FROM caretaker AS c RIGHT JOIN othercaretaker AS o USING (CT_Id) LEFT JOIN swimmer AS s USING (SwimmerId)
ORDER BY swimmer;
Query to obtain the names of swimmers who have committed to participating in both a '50M Butterfly' and a '100M Butterfly' event.
WITH t1 AS (SELECT CONCAT(s.FName, ' ', s.LName) AS swimmer, e.Title
FROM swimmer AS s INNER JOIN participation AS p USING(swimmerId) INNER JOIN event AS e USING(eventId)
WHERE p.`Committed` = 1 AND e.Title = '100M Butterfly'),
t2 AS (SELECT CONCAT(s.FName, ' ', s.LName) AS swimmer, e.Title
FROM swimmer AS s INNER JOIN participation AS p USING(swimmerId) INNER JOIN event AS e USING(eventId)
WHERE p.`Committed` = 1 AND e.Title = '50M Butterfly')
SELECT DISTINCT t1.swimmer
FROM t1 INNER JOIN t2 USING (swimmer);
Query to obtain the names of all swimmers who do not have the last name 'Khan' and have participated in three or more events. Include the total numbers of events they each have participated in.
WITH t1 AS (SELECT CONCAT(s.FName, ' ', s.LName) AS Swimmer, s.SwimmerId FROM swimmer AS s WHERE s.lname != 'Khan' )
SELECT t1.Swimmer, COUNT(p.EventId) AS `Number of Events`
FROM participation AS p, t1
WHERE p.SwimmerId = t1.SwimmerId
GROUP BY Swimmer
HAVING COUNT(p.EventId) >= 4;
Query to obtain a list of all swimmers who have participated in three or more events, including a '50M Butterfly' event but not a '200M Freestyle' event.
WITH T1 AS (SELECT CONCAT(s.FName, ' ', s.LName) AS Swimmer, s.SwimmerId, COUNT(p.EventId) AS `Number of Events` FROM participation AS p INNER JOIN swimmer AS s USING (SwimmerId) GROUP BY swimmer HAVING COUNT(p.EventId) >= 3),
T2 AS (SELECT DISTINCT p.SwimmerId, e.Title FROM participation AS p INNER JOIN event AS e USING (EventId) WHERE e.Title = '50M Butterfly'),
T3 AS (SELECT DISTINCT p.SwimmerId, e.Title FROM participation AS p INNER JOIN event AS e USING (EventId) WHERE e.Title = '200M Freestyle')
SELECT DISTINCT T1.Swimmer, T1.`Number of Events` FROM T1 INNER JOIN T2 USING (SwimmerId)
EXCEPT
SELECT DISTINCT T1.Swimmer, T1.`Number of Events` FROM T1 INNER JOIN T3 USING (SwimmerId);
Return to Top