Getting Every Nth Row from a Table (Enhanced)

In a previous Vertica Quick Tip we learned how to query every Nth row from a table when we had a unique ID column having…

OpenText profile picture
OpenText

October 20, 20201 minute read

In a previous Vertica Quick Tip we learned how to query every Nth row from a table when we had a unique ID column having sequential values (that is, from a sequence).

What if we don’t have a key like that in our table? No problem thanks to the ROW_NUMBER() Analytic Function!

Say I have this data in a table named TAB:

dbadmin=> SELECT * FROM tab;
c1     |    c2
-----------+-----------
GTMIJYZTB | EYEAVFTAO
IHAMDNYOO | ARBJXZHNN
IMCTCCEMB | KIHTTXSVY
JXAPTMKMT | HAXAWTUYM
OHSNIRKBS | LALXUSOXY
QSBCDXCUH | PEEWGUHNV
SDXUXNBSK | BSBQMHLDA
UNCMJPNRM | IBWDYLYAR
UWYBZMDTG | QGDHAUQDF
VJCYYNAVB | TTFPVTOLG
(10 rows)

I can get every second row by running the following query:

dbadmin=> SELECT * FROM (SELECT *, row_number() over() rn FROM tab) foo WHERE foo.rn % 2 = 0;
c1     |    c2     | rn
-----------+-----------+----
IHAMDNYOO | ARBJXZHNN |  2
JXAPTMKMT | HAXAWTUYM |  4
QSBCDXCUH | PEEWGUHNV |  6
UNCMJPNRM | IBWDYLYAR |  8
VJCYYNAVB | TTFPVTOLG | 10
(5 rows)

Or for every third row, I’d run this query:

dbadmin=> SELECT * FROM (SELECT *, row_number() over() rn FROM tab) foo WHERE foo.rn % 3 = 0;
c1     |    c2     | rn
-----------+-----------+----
IMCTCCEMB | KIHTTXSVY |  3
QSBCDXCUH | PEEWGUHNV |  6
UWYBZMDTG | QGDHAUQDF |  9
(3 rows)

Have fun!

Share this post

Share this post to x. Share to linkedin. Mail to
OpenText avatar image

OpenText

OpenText, The Information Company, enables organizations to gain insight through market-leading information management solutions, powered by OpenText Cloud Editions.

See all posts

More from the author

Manutan combines digital services with the human touch to delight customers

Manutan combines digital services with the human touch to delight customers

At Manutan, we equip businesses and communities with the products and services they require to succeed. Headquartered in France, our company has three divisions, serving…

4 minute read

Reaching new markets in Europe and beyond

Reaching new markets in Europe and beyond

How information management specialists at One Fox slashed time to market for innovative products with OpenText Cloud Platform Services At One Fox, we’ve driven some…

4 minute read

SoluSoft helps government agencies tackle fraud faster

SoluSoft helps government agencies tackle fraud faster

Fraud, in all its forms, is a pervasive problem, spanning industries and preying on vulnerabilities in federal and state government systems. Each year in the…

3 minute read

Stay in the loop!

Get our most popular content delivered monthly to your inbox.