In this section, we are going to understand the working of the PostgreSQL LIMIT clause, which is used to get a subset of rows produced by a command.
Syntax of PostgreSQL LIMIT Clause
The basic syntax of the PostgreSQL LIMIT clause is as follows:
In the above syntax, Limit clause returns row_count rows created by the command.
And the offset clause comes after the LIMIT clause as we can see in the below command:
Note: It is an elective clause of the SELECT command, which makes the several rows returned by the query.
If we use the ORDER BY clause to have the row order with the LIMIT clause. Or if we do not use the ORDER BY clause, we may get an output with the unnamed order of rows.
Examples of PostgreSQL LIMIT
Let us see some examples to understand the working of the PostgreSQL LIMIT clause.
Here we are creating one new table called CAR with the help of the CREATE table command, and inserting some values into the CAR table using the INSERT command.
After executing the above command, we will get the below message window, and the CAR table has been created successfully.
After that, we are going to insert some values into the CAR table with the help of below command:
After executing the above command, we will get the below message window, the values have been inserted successfully into the CAR table.
Example of constraining the number of returned rows using PostgreSQL LIMIT
In the below example, we will fetch the first SIX CAR details sorted by Car_id with the help of the LIMIT clause.
After implementing the above command, we will get the below output, which displays the first six -car details into the CAR table.
Example of getting the top and bottom rows using PostgreSQL LIMIT Clause
For selecting the rows with the maximum or minimum values from a table, we often use the LIMIT clause.
For example, if we want to sort the top five most expensive cars in terms of their price, we sort them by their Car price in descending order.
In the following command, we are using the LIMIT clause to get the most expensive cars into the CAR table:
After executing the above command, we will get the below output:
Example of OFFSET using PostgreSQL LIMIT clause
In this example, we will use LIMIT and OFFSET clauses to get five cars starting from the fifth one ordered by Car_id with the help of below command:
After implementing the above command, we will get the below output, which displays cars from the Car_id =1003 as we put the offset values is 2, and Limit value is 5 into the CAR table.
Next TopicPostgreSQL Fetch Clause