Get at least x number of rows in MySQL?

MySQLMySQLi Database

<p style="">To get at least x number of rows, you need to use the LIMIT clause. Following is the syntax &minus;</p><pre class="result notranslate">select *from yourTableName order by yourColumnName DESC limit yourXNumberOfRows;</pre><p>Let us first create a table &minus;</p><pre class="result notranslate" style="">mysql&gt; create table DemoTable ( &nbsp; &nbsp;EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,EmployeeName varchar(100) ); Query OK, 0 rows affected (0.76 sec)</pre><p>Insert some records in the table using insert command &minus;</p><pre class="result notranslate">mysql&gt; insert into DemoTable(EmployeeName) values(&#39;Chris&#39;); Query OK, 1 row affected (0.17 sec) mysql&gt; insert into DemoTable(EmployeeName) values(&#39;David&#39;); Query OK, 1 row affected (0.12 sec) mysql&gt; insert into DemoTable(EmployeeName) values(&#39;Bob&#39;); Query OK, 1 row affected (0.51 sec) mysql&gt; insert into DemoTable(EmployeeName) values(&#39;Robert&#39;); Query OK, 1 row affected (0.37 sec) mysql&gt; insert into DemoTable(EmployeeName) values(&#39;Mike&#39;); Query OK, 1 row affected (0.12 sec) mysql&gt; insert into DemoTable(EmployeeName) values(&#39;Sam&#39;); Query OK, 1 row affected (0.13 sec)</pre><p>Display all records from the table using select statement &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable;</pre><p>This will produce the following output &minus;</p><pre class="result notranslate" style="">+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1 | Chris &nbsp; &nbsp; &nbsp; &nbsp;| | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 | David &nbsp; &nbsp; &nbsp; &nbsp;| | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 | Bob &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;4 | Robert | | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;5 | Mike | | &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;6 | Sam | +------------+--------------+ 6 rows in set (0.00 sec)</pre><p>Following is the query to get at least x number of rows in MySQL. Here, we are displaying only 2 rows &minus;</p><pre class="prettyprint notranslate">mysql&gt; select *from DemoTable order by EmployeeName DESC limit 2;</pre><p>This will produce the following output &minus;</p><pre class="result notranslate" style="">+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 6 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Sam | | 4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| Robert | +------------+--------------+ 2 rows in set (0.02 sec)</pre>
raja
Updated on 22-Aug-2019 11:39:50

Advertisements