Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip every nth result row in PostgreSQL

Tags:

I'm looking for a way to skip rows in PostgreSQL.

Two ways I could do this are using:

SELECT * FROM table WHERE id % 5 = 0 

However I'd have to fetch sequential rows to properly skip. For instance if I fetch row (with ids) 0,3,5, it would not skip 4 out of 5 rows, but instead result in (ids) 0 and 5.

Or skip outside of SQL:

$count = 0; while($row = progres_fetch_row($result))   if ($count++ % 5 == 0)      // do something  

What is the fastest way to get every nth row from a SQL database?

like image 672
RobotRock Avatar asked Oct 25 '13 17:10

RobotRock


People also ask

How do I select every nth row in SQL?

Here's the SQL query to select every nth row in MySQL. mysql> select * from table_name where table_name.id mod n = 0; In the above query, we basically select every row whose id mod n value evaluates to zero.

What is xmin and xmax in PostgreSQL?

When a row is created, the value of xmin is set equal to the ID of the transaction that performed the INSERT command, while xmax is not filled in. When a row is deleted, the xmax value of the current version is labeled with the ID of the transaction that performed DELETE.

Can we use Rownum in PostgreSQL?

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

What is offset in PostgreSQL?

OFFSET says to skip that many rows before beginning to return rows. OFFSET 0 is the same as omitting the OFFSET clause, as is OFFSET with a NULL argument. If both OFFSET and LIMIT appear, then OFFSET rows are skipped before starting to count the LIMIT rows that are returned.


1 Answers

If you use PostgreSQL, you can use row_number():

SELECT t.* FROM (   SELECT *, row_number() OVER(ORDER BY id ASC) AS row   FROM yourtable ) t WHERE t.row % 5 = 0 
like image 113
Guillaume Poussel Avatar answered Sep 21 '22 10:09

Guillaume Poussel