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


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.

 

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!

About the Author

Author: Wim Peeters - Keskon GmbH & Co. KG

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. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform.