Explain Limit Keyword and ORDER BY Keyword in SQL

Share

SQL LIMIT Keyword

LIMIT keyword in SQL is often used for defining the range of data to be selected and could also specify the number of rows you want to get from the table as well as from the DBMS.

Mainly, it’s used for optimization. it helps you to select a particular range of rows from the table rather than the entire row.

Syntax: SELECT * FROM table_name LIMIT Required_rows;

Usage of LIMIT Keyword:

1.  Defining a limit with a single value would keep fetching records from the table until it reached to a specified number of rows.

For example: Let say you need first 3 records from the table. To get the result the query would be.

SELECT * FROM coder LIMIT 3;

Explanation:- In above example, first three rows had been selected from the table as it is mention to LIMIT keyword.

2. Specifying limit with two values that is Connected by a comma. The first value specifies the initial row or point (use the index which starts from O, not from 1) and other value mentions the number of record required.

For example: Suppose there is table called user details and lets say you need data starting from 3rd raw and consecutively needed  2 records from database.

Actual Table:

SELECT * FROM coder LIMIT 3,2;

Explanation: In above example, the limit had started from 4 as initial point specified 3 (that is from 4th row) and kept going till the number of rows reached to 2.

ORDER BY Keyword to sort data in SQL for Sorting table

In SQL, One can retrieve columns or fields in increasing or decreasing order from a table. for this ORDER BY keyword is used to sort a record in a particular order.

 

You can sort  more than one column at a time . If the field is numeric then it would sort in numerical order (1,2,3..) and if the field is not numeric then it would sort the field in Alphabetical order(A,B,C,D).

Syntax:
SELECT column1,column2…. FROM Table_Name ORDER BY column1,column2… ASC/DESC;

Explanation:
Above syntax describes, SELECT one column or more than one column FROM table named xyz in order of increasing order(ASC) or decreasing order(DESC) as per the column.

– To retrieve a record in increasing or ascending order. Suppose you want to fetch a field named customer_name in increasing order from a table named customer. this will be  the syntax

SELECT * FROM `customer` ORDER BY customer_name ASC;

SELECT customer_name FROM `customer` ORDER BY customer_name ASC;

– To retrieve a column from table in decreasing or descending order. Now Suppose you need to fetch a field named customer_name in decreasing order from a table named customer.  this is the syntax

SELECT * FROM `customer` ORDER BY customer_name DESC;

SELECT customer_name FROM `customer` ORDER BY customer_name DESC;

This post was last modified on December 14, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: Explain Limit Keyword and ORDER BY Keyword in SQL limit LIMIT Keyword order by sql SQL LIMIT Keyword Usage of LIMIT Keyword