To return only the first row that matches your SELECT
query, you need to add the LIMIT
clause to your SELECT
statement.
The LIMIT
clause is used to control the number of rows returned by your query. When you add LIMIT 1
to the SELECT
statement, then only one row will be returned.
Here’s an example of a SELECT
query with the LIMIT
clause:
SELECT * FROM example_database LIMIT 1;
The LIMIT
clause accepts two parameters:
- The
number
of offsets before returning the row (optional) - The
number
of rows to return (required)
Because the offset is optional, you can pass only one argument to the clause to simply limit the returned row count.
For example, suppose you have a students
table with the following data:
+----+---------+---------+-------+--------+
| id | name | subject | score | gender |
+----+---------+---------+-------+--------+
| 1 | Mark | Math | 7 | male |
| 2 | Natalia | Math | 8 | female |
| 3 | Gary | Math | NULL | male |
| 4 | Joe | English | 8 | male |
| 5 | Sarah | Math | NULL | female |
| 6 | Peter | English | 6 | male |
| 7 | Nathan | English | 8 | male |
+----+---------+---------+-------+--------+
To return only the first row, you need to execute the following SQL query:
SELECT * FROM students LIMIT 1;
The returned result set will be as shown below:
+----+------+---------+-------+--------+
| id | name | subject | score | gender |
+----+------+---------+-------+--------+
| 1 | Mark | Math | 7 | male |
+----+------+---------+-------+--------+
1 row in set (0.00 sec)
And that’s how you can SELECT
only the first row using MySQL.
Next, let’s see how you can add a custom order to change the order of the rows.
MySQL select first row from a custom order
The first row returned by the SELECT
statement will always follow the internal table order created by MySQL.
Usually, the rows in your table were ordered by the time they are inserted into the table.
You can change the order of the rows returned by the SELECT
statement by adding the ORDER BY
clause.
The ORDER BY
clause allows you to sort the returned result set by the value of a column in an ascending (ASC
) or descending (DESC
) order.
For example, the following SQL statement will sort the result using the id
column in descending order:
SELECT * FROM students ORDER BY id DESC;
Add the LIMIT
clause after the ORDER BY
clause to return only the first row as follows:
SELECT * FROM students ORDER BY id DESC LIMIT 1;
+----+--------+---------+-------+--------+
| id | name | subject | score | gender |
+----+--------+---------+-------+--------+
| 7 | Nathan | English | 8 | male |
+----+--------+---------+-------+--------+
1 row in set (0.00 sec)
And that’s how you can define a custom order and SELECT
only the first row from that order using the LIMIT
keyword.
You may change the ORDER BY
clause to fit your requirements.