0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[OracleDB]ROWNUMについて

Posted at

LIMIT句の代わりに使われる、ROWNUM句

以下のような挙動をする

5件取りたい


SELECT * FROM user WHERE ROWNUM <= 5
  • 問題なく動く。5件取得する

SELECT * FROM user WHERE ROWNUM between 0 and 5
  • これも問題なく動く。betweenの範囲指定はOK

6件目以降を取りたい

SELECT * FROM user WHERE ROWNUM >= 6
  • エラーは吐かないが、 結果は0件 になる

SELECT * FROM user WHERE ROWNUM between 6 and 10
  • これも同じく、エラーなしの0件
なぜ?

ROWNUMは、 1を含む検索しか許容しない という仕様を持つ。そのため、6件目移行を取得したい場合は1件目を取得していないため結果が帰ってこない。

対応したい場合、副問い合わせを使うしかない。

SELECT *
(
  SELECT
    * ,
    rownum as tmp_rownum
  FROM user
)
WHERE tmp_rownum between 6 and 10

これだと動く。
order by と組み合わせたい場合なども副問い合わせが必要になるため、ROWNUMを柔軟に使いたい場合必要になると考えた方が良さそう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?