Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Databases SQL Reporting by Example Day 2: Advanced Selecting Student Schedule

Noah Fields
Noah Fields
13,985 Points

My version of the answer with subqueries

Here's my version of the code, using subqueries.

    -- Generate a schedule for Rex Rios.
    INNER JOIN (CLASSES) ON CLASSES.ID = CLASS_ID --Find classes where the class ID in classes = schedule ID
    INNER JOIN SUBJECTS ON CLASSES.SUBJECT_ID = SUBJECTS.ID -- Join to subjects where the classes subject ID = Subject ID
    WHERE FIRST_NAME = 'Rex' AND LAST_NAME = 'Rios' --But only for those where the schedule's ID colum matches Rex's ID
    ORDER BY PERIOD_ID --Order by period for neatness
Chris Seals
Chris Seals
4,506 Points

There are obviously several ways to go about this. Can any of the veterans chyme in about optimizing query structure for database performance. Specifically when making a table with many joins. should I be starting with the most limiting table and joining onto that, or can that be problematic? For example Here is what I wrote prior to watching the video:

-- Generate a schedule for Rex Rios.
-- sort by period
-- period. subject. room. teacher. start time. duration.
    periods.id AS 'Period',
    subjects.name AS 'Subject',
    rooms.id AS 'Room#',
    (teachers.first_name || ' ' || teachers.last_name) AS 'Teacher',
    periods.start_time AS 'Start Time',
    periods.duration AS 'Duration (min)'
  FROM classes
    JOIN periods ON
      classes.period_id = periods.id
    JOIN subjects ON
      classes.subject_id = subjects.id
    JOIN rooms ON
      classes.room_id = rooms.id
    JOIN teachers ON
      classes.teacher_id = teachers.id
    JOIN schedule ON
      classes.id = schedule.class_id
    JOIN students ON
      schedule.student_id = students.id
    WHERE students.first_name LIKE "%Rex%"
      AND students.last_name LIKE "%Rios%"
    ORDER BY periods.id