How Can we use MySQL DISTINCT clause with WHERE and LIMIT clause?

MySQLMySQLi Database

By using the WHERE clause with a DISTINCT clause in MySQL queries, we are putting a condition on the basis of which MySQL returns the unique rows of the result set. By using the LIMIT clause with a DISTINCT clause in MySQL queries, we are actually providing a perimeter to the server about a maximum number of unique rows of the result set to be returned.

Example

We can use WHERE and LIMIT clause with DISTINCT as follows on the table named ‘testing’ −

mysql> Select * from testing;
+------+---------+---------+
| id   | fname   | Lname   |
+------+---------+---------+
|  200 | Raman   | Kumar   |
|  201 | Sahil   | Bhalla  |
|  202 | Gaurav  | NULL    |
|  203 | Aarav   | NULL    |
|  204 | Harshit | Khurana |
|  205 | Rahul   | NULL    |
|  206 | Piyush  | Kohli   |
|  207 | Lovkesh | NULL    |
|  208 | Gaurav  | Kumar   |
|  209 | Raman  | Kumar    |
+------+---------+---------+
10 rows in set (0.00 sec)

mysql> Select DISTINCT Lname from testing where Lname IS NOT NULL limit 3;
+---------+
| Lname   |
+---------+
| Kumar   |
| Bhalla  |
| Khurana |
+---------+
3 rows in set (0.00 sec)
raja
Published on 22-Feb-2018 11:55:30
Advertisements