降序索引应用在Top N问题上的应用

本文介绍了在Oracle数据库中如何创建降序索引,并通过实际案例展示了如何利用降序索引来提高查询效率,特别是针对特定条件下的前N条记录查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL> create table test_desc (id number not null,name varchar2(16)) tablespace users;

Table created.

SQL> create index test_id_desc_idx on test_desc(id desc) tablespace idx;

Index created.

Oracle默认情况下是升序索引,这里定义了降序索引。

[@more@]

我们看一下select会怎么样

SQL> select * from test_desc where id<10;

ID NAME
---------- ----------------
9 d
8 d
7 d
6 d
5 d
4 d
3 d
2 d
1 d

下面我们求id小于100的前5条记录

SQL> l
1 select * from
2* (select id,name,rownum rnk from test_desc where id<101) where rnk<6
SQL> /

ID NAME RNK
---------- ---------------- ----------
100 d 1
99 d 2
98 d 3
97 d 4
96 d 5


Execution Plan
----------------------------------------------------------
Plan hash value: 328368902

--------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 100 | 3600 | 2 (0)| 00:00:01 |
|* 1 | VIEW | | 100 | 3600 | 2 (0)| 00:00:01 |
| 2 | COUNT | | | | | |
| 3 | TABLE ACCESS BY INDEX ROWID| TEST_DESC | 100 | 2300 | 2 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN | TEST_ID_DESC_IDX | 1 | | 2 (0)| 00:00:01 |
--------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

1 - filter("RNK"<6)
4 - access(SYS_OP_DESCEND("ID")>HEXTORAW('3DFDFDFF') )
filter(SYS_OP_UNDESCEND(SYS_OP_DESCEND("ID"))<101)

Note
-----
- dynamic sampling used for this statement


Statistics
----------------------------------------------------------
0 recursive calls
0 db block gets
5 consistent gets
0 physical reads
0 redo size
592 bytes sent via SQL*Net to client
385 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
5 rows processed
可以看到执行计划避免了不必要的排序

当我们查询salary小于5000的前10人时可以应用降序索引解决问题.

为emp(salary)创建降序索引

select * from (

select xxx,rownum rnk from emp where salary<5000)

where rnk<11;

即可.

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/76065/viewspace-831997/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/76065/viewspace-831997/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值