To get at least x number of rows, you need to use the LIMIT clause. Following is the syntax −
select *from yourTableName order by yourColumnName DESC limit yourXNumberOfRows;
Let us first create a table −
mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,EmployeeName varchar(100) ); Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(EmployeeName) values('Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(EmployeeName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(EmployeeName) values('Bob'); Query OK, 1 row affected (0.51 sec) mysql> insert into DemoTable(EmployeeName) values('Robert'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable(EmployeeName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(EmployeeName) values('Sam'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Chris | | 2 | David | | 3 | Bob | | 4 | Robert | | 5 | Mike | | 6 | Sam | +------------+--------------+ 6 rows in set (0.00 sec)
Following is the query to get at least x number of rows in MySQL. Here, we are displaying only 2 rows −
mysql> select *from DemoTable order by EmployeeName DESC limit 2;
This will produce the following output −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 6 | Sam | | 4 | Robert | +------------+--------------+ 2 rows in set (0.02 sec)