Here's a preview from my zine, Become a SELECT Star! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
get the zine!
read the transcript!
ORDER BY and LIMIT
ORDER BY and LIMIT happen at the end and affect the final output of the query.
ORDER BY lets you sort by anything you want!
The syntax is:
ORDER BY [expression] ASC or DESC
(ASC stands for ascending)
For example, this query sorts cats by the length of their name (shortest first):
SELECT * FROM cats
ORDER BY LENGTH(name) ASC
cats:
| owner | name |
|---|---|
| 1 | daisy |
| 1 | dragonsnap |
| 3 | buttercup |
| 4 | rose |
results of query:
| owner | name |
|---|---|
| 4 | rose |
| 1 | daisy |
| 3 | buttercup |
| 1 | dragonsnap |
LIMIT lets you limit the number of rows output.
The syntax is:
LIMIT [integer]
For example, this is the same as the previous query, but it limits to only the 2 cats with the shortest names:
SELECT * FROM cats
ORDER BY LENGTH(name) ASC
LIMIT 2
cats:
| owner | name |
|---|---|
| 1 | daisy |
| 1 | dragonsnap |
| 3 | buttercup |
| 4 | rose |
results of query:
| owner | name |
|---|---|
| 4 | rose |
| 1 | daisy |