This lesson introduces advanced SQL techniques to enhance your querying capabilities. By mastering these objectives, you'll be able to aggregate data, order results, use subqueries effectively, and dynamically seed data.
GROUP BY and HAVING.MAX, MIN, and COUNT.JOIN query into a subquery.INSERT for dynamic seeding.
The GROUP BY clause groups rows with the same values in specified columns into summary rows. Use HAVING to filter these grouped results.
Find the total weight of puppies by breed, but only include breeds with a total weight exceeding 50 lbs:
SELECT breed, SUM(weight_lbs) AS total_weight
FROM puppies
GROUP BY breed
HAVING SUM(weight_lbs) > 50;
breed total_weight
Miniature Schnauzer 43
German Shepherd 65
Aggregate functions like MAX, MIN, and COUNT perform calculations on a set of values and return a single value.
SELECT MAX(weight_lbs) AS max_weight
FROM puppies;
SELECT MIN(age_yrs) AS min_age
FROM puppies;
SELECT COUNT(*) AS total_puppies
FROM puppies;
You can sort query results based on aggregate values using the ORDER BY clause.
List breeds by their total weight in descending order:
SELECT breed, SUM(weight_lbs) AS total_weight
FROM puppies
GROUP BY breed
ORDER BY total_weight DESC;
breed total_weight
German Shepherd 65
Miniature Schnauzer 43
A subquery is a query nested inside another query. It can be used in place of a JOIN to simplify or optimize queries.
Find all puppies owned by "Jamie Anderson":
SELECT puppies.name
FROM puppies
JOIN owners ON puppies.owner_id = owners.id
WHERE owners.first_name = 'Jamie' AND owners.last_name = 'Anderson';
SELECT name
FROM puppies
WHERE owner_id = (
SELECT id
FROM owners
WHERE first_name = 'Jamie' AND last_name = 'Anderson'
);
Subqueries can dynamically provide values for an INSERT statement.
Assign a new puppy to the owner "Linda Long":
INSERT INTO puppies (name, age_yrs, breed, weight_lbs, microchipped, owner_id)
VALUES ('Buddy', 0.5, 'Golden Retriever', 20, 1, (
SELECT id
FROM owners
WHERE first_name = 'Linda' AND last_name = 'Long'
));
In this lesson, you learned how to:
GROUP BY and HAVING to aggregate and filter grouped data.MAX, MIN, and COUNT.ORDER BY.INSERT statements.These advanced SQL techniques are invaluable for:
With these tools, you’re ready to tackle advanced data management and analysis tasks in SQL!