SQLite3 (or general SQL) retrieve nth row of a query result

前端 未结 3 391
别那么骄傲
别那么骄傲 2020-12-16 13:35

Quicky question on SQLite3 (may as well be general SQLite)

How can one retrieve the n-th row of a query result?

row_id (

相关标签:
3条回答
  • 2020-12-16 14:13

    add LIMIT 1 and OFFSET <n> to the query
    example SELECT * FROM users LIMIT 1 OFFSET 5132;

    0 讨论(0)
  • 2020-12-16 14:17

    But I may need to quickly retrieve, say, rows 2 & 5 of the results.

    In scenario when you need non-continuous rows you could use ROW_NUMBER():

    WITH cte AS (
      SELECT *, ROW_NUMBER() OVER() AS rn --OVER(ORDER BY ...) --if specific order is required
      FROM t
    )
    SELECT c 
    FROM cte
    WHERE rn IN (2,5);  -- row nums
    

    db<>fiddle demo

    0 讨论(0)
  • 2020-12-16 14:24

    The general approach is that, if you want only the nth row of m rows, use an appropriate where condition to only get that row.

    If you need to get to a row and can't because no where criteria can get you there, your database has a serious design issue. It fails the first normal form, which states that "There's no top-to-bottom ordering to the rows."

    0 讨论(0)
提交回复
热议问题