← Teacher guide

Put the rows in order

Students sort with ORDER BY, reverse with DESC, keep the top rows with LIMIT, and combine it with WHERE.

SQL and databases · Ask a table · about 25 minutes · Open the student lesson

Classroom resources

Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.

Students will be able to

Timing

Predict and Run 8 min · Investigate 6 min · Modify and Make 11 min

Running the lesson

  1. Predict: the 'first 3 in the table' option shows students who think the table has a built-in order.
  2. Run: delete DESC and run again so the order flips.
  3. Make: the clause order is fixed. Read the query aloud: which rows, in what order, how many.

In class

On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.

The hard part (on purpose)

The fixed order of the parts. Read the query aloud as a sentence.

When students get stuck

What you will seeA question to askThe fix
syntax error near ORDERWhich comes first, WHERE or ORDER BY?The order is SELECT, FROM, WHERE, ORDER BY, LIMIT.
The wrong end of the list.Does the order go smallest first or biggest first?Add DESC for biggest first.

Answers to the checks

  1. Predict: What will this query show?
    The 3 most played songs. DESC sorts from biggest to smallest, and LIMIT 3 keeps the first three.
  2. Which comes first?: Without DESC, which song comes first when sorted by seconds?
    The shortest song
    ORDER BY goes from smallest to biggest unless you add DESC.
  3. Newest song: You want the single newest song. What do you need?
    ORDER BY year DESC LIMIT 1
    Sort newest first with DESC, then keep one row.

Solutions

One possible solution for each task. Other correct programs are fine.

Modify

SELECT title, seconds
FROM songs
ORDER BY seconds DESC
LIMIT 1;

Make

SELECT title, plays
FROM songs
WHERE genre = 'rock'
ORDER BY plays DESC
LIMIT 3;

Stretch and support

Stretch: Sort by two columns, such as genre and then plays DESC.

Support: Give the query with ORDER BY done and ask only for LIMIT.

Exit ticket

What is the order of the parts of a query so far?

SELECT, FROM, WHERE, ORDER BY, LIMIT.

What each step is for

Where it leads

Next lesson: count and add up rows to one answer.