LKBEN11032: Howto select only a limited list of results from a query with postgresql?


This article has not been checked!

LKB | Created: 02/04/2020 | Version: 0 | Language: EN | Rating: 0 | Outdated: False | Marked for deletion: False

Author: Wim Peeters - Keskon GmbH & Co. KG


Symptom

You have a postgres database and only want to select a few rows from a query

Cause

This can be usefull to view what kind of data a certain table holds

Solution

To retrieve only a few rows, you can use the word "LIMIT" in your query.

This example only lists the first 10 rows:

select users from articles limit 10;

If you have an index matching for the search you can also use an "ORDER BY" so the entire query does not have to be executed. This is an advantage for big databases.

select users, name from articles order by name limit 10;

The following will select 10 random rows from the query.

select users, name from articles order by random() limit 10;

In case you do not know how many numbers of rows you would like to get at select time, use a CURSOR and FETCH.

 

About the Author

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux in different European countries and different European languages. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform where he is one of the most important contributors and the main developer.

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!