mirror of
https://github.com/robindhole/fundamentals.git
synced 2025-03-16 19:30:11 +00:00
2.5 KiB
2.5 KiB
Sub-queries and views worksheet
Sub-queries
- Get all the students whose IQ is greater than the average IQ.
SELECT
first_name, last_name, iq
FROM
students
WHERE
iq > (SELECT
AVG(iq)
FROM
students);
- Get all the students whose IQ is greater than the highest IQ of the batch_id
2
students.
SELECT
*
FROM
students
WHERE
iq > (SELECT
MAX(iq)
FROM
students
WHERE
batch_id = 2);
- Get all the students whose IQ is greater than
all
the IQs of the batch_id2
students.
SELECT
*
FROM
students
WHERE
iq > ALL (SELECT
iq
FROM
students
WHERE
batch_id = 2);
- Find all the students who are in batches that start with the word
Jedi
(Without JOIN)
SELECT
*
FROM
students
WHERE
batch_id IN (SELECT
id
FROM
batches
WHERE
name LIKE 'Jedi%');
- Find all the students whose IQ is greater than the average IQ of their batch.
SELECT
*
FROM
students;
SELECT
first_name, last_name, batch_id, iq
FROM
students s
WHERE
s.iq > (SELECT
AVG(iq)
FROM
students e
WHERE
e.batch_id = s.batch_id);
- Get all the instructors that have at least one batch (Without using joins)
SELECT
*
FROM
instructors i
WHERE
EXISTS( SELECT
id
FROM
batches
WHERE
instructor_id = i.id);
- Print all the names, batch ID and average IQ of the batch for each student
SELECT
id,
first_name,
last_name,
iq,
batch_id,
(SELECT
AVG(iq)
FROM
students
WHERE batch_id = s.batch_id
)
FROM
students s;
Views
- Create a view that shows the students and their batches.
CREATE VIEW students_and_batches AS
SELECT
s.id,
s.first_name,
s.last_name,
s.iq,
b.name AS batch_name
FROM
students s
JOIN
batches b ON s.batch_id = b.id;
- Create a view that shows the students and their batches, but only for batches that start with the word
Jedi
.
CREATE VIEW students_and_batches AS
SELECT
s.id,
s.first_name,
s.last_name,
s.iq,
b.name AS batch_name
FROM
students s
JOIN
batches b ON s.batch_id = b.id
WHERE
b.name LIKE 'Jedi%';