Which approach can fetch alternate rows from a table?

Prepare for the DDR Data Science Interview Test. Access flashcards and multiple choice questions, each with detailed hints and explanations. Enhance your readiness for the interview!

Multiple Choice

Which approach can fetch alternate rows from a table?

Explanation:
To fetch alternate rows reliably, you need a stable, per-row sequence in a defined order. ROW_NUMBER() provides that by assigning a unique, consecutive number to every row according to your ORDER BY clause. Once every row has a unique index, you can simply filter where the index modulo 2 is 0 (or 1) to get every other row. Why this works best: ROW_NUMBER() guarantees a strict 1, 2, 3, ... sequence with no ties, so the alternation pattern is predictable and reproducible. Other approaches can introduce ties or groupings that break a clean alternation: RANK() and DENSE_RANK() assign the same value to tied rows, which means several rows can share a rank and the sequence isn’t strictly alternating. NTILE() divides the result into a fixed number of groups rather than giving a per-row linear index, so filtering by group number won’t produce a simple alternating pattern in the overall order. So, using ROW_NUMBER() with a modulo filter on its result is the straightforward, reliable way to fetch alternate rows, as long as you define a deterministic order in the window.

To fetch alternate rows reliably, you need a stable, per-row sequence in a defined order. ROW_NUMBER() provides that by assigning a unique, consecutive number to every row according to your ORDER BY clause. Once every row has a unique index, you can simply filter where the index modulo 2 is 0 (or 1) to get every other row.

Why this works best: ROW_NUMBER() guarantees a strict 1, 2, 3, ... sequence with no ties, so the alternation pattern is predictable and reproducible. Other approaches can introduce ties or groupings that break a clean alternation: RANK() and DENSE_RANK() assign the same value to tied rows, which means several rows can share a rank and the sequence isn’t strictly alternating. NTILE() divides the result into a fixed number of groups rather than giving a per-row linear index, so filtering by group number won’t produce a simple alternating pattern in the overall order.

So, using ROW_NUMBER() with a modulo filter on its result is the straightforward, reliable way to fetch alternate rows, as long as you define a deterministic order in the window.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy