Advanced SQL Objectives

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.

Learning Objectives

1. Aggregate a Query Using GROUP BY and HAVING

The GROUP BY clause groups rows with the same values in specified columns into summary rows. Use HAVING to filter these grouped results.

Example:

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;
    

Result:

breed                total_weight
Miniature Schnauzer   43
German Shepherd       65
    

2. Aggregate a Query Using MAX, MIN, and COUNT

Aggregate functions like MAX, MIN, and COUNT perform calculations on a set of values and return a single value.

Examples:

3. Order a Query by an Aggregate

You can sort query results based on aggregate values using the ORDER BY clause.

Example:

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;
    

Result:

breed                total_weight
German Shepherd       65
Miniature Schnauzer   43
    

4. Convert a JOIN Query into a Subquery

A subquery is a query nested inside another query. It can be used in place of a JOIN to simplify or optimize queries.

Example:

Find all puppies owned by "Jamie Anderson":

Using JOIN:

SELECT puppies.name
  FROM puppies
  JOIN owners ON puppies.owner_id = owners.id
  WHERE owners.first_name = 'Jamie' AND owners.last_name = 'Anderson';
    

Using Subquery:

SELECT name
  FROM puppies
  WHERE owner_id = (
    SELECT id 
    FROM owners 
    WHERE first_name = 'Jamie' AND last_name = 'Anderson'
  );
    

5. Use a Subquery Inside an INSERT for Dynamic Seeding

Subqueries can dynamically provide values for an INSERT statement.

Example:

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'
));
    

What You Learned

In this lesson, you learned how to:

Real-World Applications

These advanced SQL techniques are invaluable for:

With these tools, you’re ready to tackle advanced data management and analysis tasks in SQL!