user1282637
user1282637

Reputation: 1867

Finding the 3 smallest numbers in a column

I have a table like this:

| songtitle  | songlength  | 
|------------|-------------|
| 1          |      3:42   |
| 2          |      1:32   |
| 3          |      2:44   |
| 4          |      5:00   |
| 5          |      1:19   |
| 6          |      2:54   |

And I want to get the 3 shortest songs (sorted shortest to longest).

I figure I will need something like LIMIT but I'm not positive. Thanks

Upvotes: 0

Views: 58

Answers (2)

Pawan Kartik
Pawan Kartik

Reputation: 34

Use the "SORT" function to sort them natively in MySQL.

Upvotes: 0

Barranka
Barranka

Reputation: 21047

Sort the data and limit the number of rows you want to retreive:

select *
from your_table
order by songlength
limit 3;

If you'd like to get the 3 longest songs, simply order the data in descending order:

select *
from your_table
order by songlength desc
limit 3;

Addressing Dwza's comment, quoting from MySQL Reference Manual:

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. [...] To sort in reverse order, add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.

Upvotes: 3

Related Questions