oracle唯一索引失效--Oracle - 唯一索引、复合索引与函数索引,按需选择更高效 - edge-animation-slow{stroke-dasharray:9,5
大家好,欢迎来到我的技术博客! 在这里,我会分享学习笔记、实战经验与技术思考,力求用简单的方式讲清楚复杂的问题。 本文将围绕Oracle这个话题展开,希望能为你带来一些启发或实用的参考。 无论你是刚入门的新手,还是正在进阶的开发者,希望你都能有所收获!
文章目录
Oracle 唯一索引、复合索引与函数索引:按需选择更高效 一、唯一索引:不只是去重,更是性能加速器 1.1 唯一索引的本质:告诉优化器“值唯一 → 查到即停”1.2 场景实测:用户邮箱唯一性查询Java JDBC 验证代码(Spring Boot + JdbcTemplate)❌ 错误示范:用普通索引替代唯一性保障
1.3 唯一索引与 NULL 值:一个常被忽略的坑 ️
二、复合索引:列序即命运,覆盖即王道 里2.1 复合索引的 B-tree 结构:前导列决定一切2.2 场景实测:电商订单状态+时间范围查询✅ 正确复合索引设计Java 代码验证索引有效性❌ 反模式:列序颠倒的代价
2.3 复合索引进阶:覆盖索引(Covering Index)消除回表场景:订单统计报表(只查维度字段)
三、函数索引:让“计算”也能走索引 燐3.1 函数索引的本质:索引化表达式结果3.2 场景实测:不区分大小写的用户名搜索❌ 普通方案(灾难性)✅ 函数索引方案(秒级响应)Java 代码无缝对接(无需改 SQL!)
3.3 高级技巧:组合函数索引 + 覆盖查询
四、三类索引决策树:一张图看懂选哪个 五、Java 工程实践:索引变更的灰度与监控 ️5.1 索引创建的灰度策略5.2 索引效果监控:Java 端埋点5.3 索引冗余检测:自动识别“僵尸索引”
六、避坑指南:那些让索引失效的 Java 陷阱 ⚠️6.1 隐式类型转换:String vs NUMBER6.2 Like 模糊查询:前导通配符的诅咒6.3 绑定变量窥探(Bind Peeking)引发的执行计划漂移
七、总结:索引是契约,不是魔法杖 ✨
Oracle 唯一索引、复合索引与函数索引:按需选择更高效
在企业级 Java 应用与 Oracle 数据库深度协同的场景中,索引不是“加了就快”,而是“加对才快”。我们常看到这样的现象:
一个查询响应时间从 200ms 突然飙升至 8s,执行计划显示 FULL TABLE SCAN;开发同学连夜加了 CREATE INDEX idx_user_email ON users(email);,但 WHERE UPPER(email) = 'ADMIN@EXAMPLE.COM' 依然慢如蜗牛;DBA 提醒:“你这个字段上有 NOT NULL 约束,但没建唯一索引,导致优化器不敢走 INDEX UNIQUE SCAN”;还有团队为提升分页性能,在 (status, created_date) 上建了复合索引,却在 WHERE status = ? ORDER BY id DESC 中完全失效……
这些都不是玄学,而是 Oracle CBO(Cost-Based Optimizer)在索引选择逻辑上的严谨表达。本文将结合真实业务场景、Java JDBC 实战代码、可验证的执行计划分析,系统拆解 唯一索引(Unique Index)、复合索引(Composite Index)与函数索引(Function-Based Index) 的设计原理、适用边界、陷阱识别与性能验证方法。全文无抽象理论堆砌,只讲“什么情况下该选哪个”、“为什么这样选更快”、“Java 里怎么安全验证效果”。
核心观点前置: ✅ 唯一索引 ≠ 主键索引,但能触发最高效的 INDEX UNIQUE SCAN; ✅ 复合索引的列序决定其“覆盖能力”,WHERE + ORDER BY + SELECT 三重约束缺一不可; ✅ 函数索引不是“给函数加速”,而是让 非标准表达式获得索引能力——UPPER()、TRUNC(date_col)、NVL(col, 'N') 全部可索引化; ❌ 没有“万能索引”,只有“匹配访问路径的索引”。
一、唯一索引:不只是去重,更是性能加速器
1.1 唯一索引的本质:告诉优化器“值唯一 → 查到即停”
Oracle 对唯一索引的特殊优化在于:当谓词满足 =, IN, IS NULL(配合 NOT NULL 列)等精确匹配时,CBO 可直接选择 INDEX UNIQUE SCAN 访问路径。该路径的特点是:
仅读取索引块(无需回表)(若查询列全在索引中);找到第一条匹配记录后立即终止扫描(不继续找第二条,因已知唯一);IO 成本极低,通常 1~3 个逻辑读即可完成。
对比普通非唯一索引的 INDEX RANGE SCAN:即使 WHERE email = ? 且 email 上有非唯一索引,CBO 仍可能走 RANGE SCAN(需扫描索引范围,再判断是否有多行),甚至退化为 FULL TABLE SCAN(若统计信息不准或选择率高)。
✅ 正确姿势:对业务语义上“天然唯一”的字段,强制建唯一索引,而非依赖程序层校验。
1.2 场景实测:用户邮箱唯一性查询
假设业务要求 email 全局唯一,且高频查询单个用户:
-- ✅ 推荐:显式创建唯一索引(即使已有主键)
CREATE UNIQUE INDEX uk_users_email ON users(email)
TABLESPACE idx_tbs
COMPRESS 1; -- 启用前缀压缩,节省空间
⚠️ 注意:UNIQUE CONSTRAINT 会隐式创建唯一索引,但 显式 CREATE UNIQUE INDEX 更灵活(可指定表空间、压缩、并行度等),且便于后续 DROP/REBUILD 管理。
Java JDBC 验证代码(Spring Boot + JdbcTemplate)
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
// ✅ 查询单个用户(email 精确匹配)
public User findByEmail(String email) {
String sql = "SELECT id, name, email, status FROM users WHERE email = ?";
// 启用执行计划捕获(Oracle 特有 hint)
String explainSql = "EXPLAIN PLAN FOR " + sql;
jdbcTemplate.update(explainSql, email);
// 获取执行计划
List> plan = jdbcTemplate.queryForList("SELECT operation, options, object_name, cost, cardinality " +
"FROM TABLE(DBMS_XPLAN.DISPLAY()) " +
"WHERE operation LIKE '%INDEX%' OR operation = 'SELECT STATEMENT'"
);
System.out.println("Execution Plan for email='" + email + "':");
plan.forEach(row ->
System.out.printf(" %-15s %-12s %-15s Cost:%d Rows:%d%n",
row.get("OPERATION"),
row.get("OPTIONS"),
row.get("OBJECT_NAME"),
((Number) row.get("COST")).intValue(),
((Number) row.get("CARDINALITY")).intValue()
)
);
return jdbcTemplate.queryForObject(sql, new Object[]{email},
(rs, rowNum) ->new User(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email"),
rs.getString("status")
));
}
}
当 email 上存在唯一索引时,执行计划输出类似:
Execution Plan for email='test@example.com':
SELECT STATEMENT Cost:2 Rows:1 拼多多帮助力入口
INDEX UNIQUE SCAN UK_USERS_EMAIL Cost:1 Rows:1
→ INDEX UNIQUE SCAN 明确出现,Rows:1 表明优化器确信结果唯一。
❌ 错误示范:用普通索引替代唯一性保障
-- ⚠️ 危险!仅建普通索引,无法触发 UNIQUE SCAN
CREATE INDEX idx_users_email ON users(email);
此时执行相同 Java 查询,执行计划可能为:
SELECT STATEMENT Cost:4 Rows:1
TABLE ACCESS BY INDEX ROWID BATCHED USERS Cost:4 Rows:1
INDEX RANGE SCAN IDX_USERS_EMAIL Cost:3 Rows:1
虽然 Rows:1 相同,但访问路径是 INDEX RANGE SCAN + TABLE ACCESS,多一次回表(TABLE ACCESS),且 RANGE SCAN 内部仍需确认唯一性——在高并发下,这微小差异会放大为 CPU 争用与 buffer busy waits。
拓展阅读:Oracle 官方文档对 INDEX UNIQUE SCAN 的定义强调其“single-row lookup”语义,这是性能差异的底层依据。
1.3 唯一索引与 NULL 值:一个常被忽略的坑 ️
Oracle 规定:唯一索引允许任意数量的 NULL 值(因 NULL ≠ NULL)。这意味着:
CREATE UNIQUE INDEX uk_emp_ssn ON employees(ssn); —— 若 ssn 列含 NULL,则多个 NULL 行不违反唯一性;但 WHERE ssn IS NULL 无法使用该唯一索引!因为索引不存储全 NULL 键值(B-tree 索引跳过全 NULL 条目)。
✅ 解决方案:对可能为 NULL 的关键字段,用函数索引补位(见第三章),或业务层约定“NULL 用特定字符串代替”(如 'MISSING_SSN')。
-- ✅ 方案1:函数索引索引 NULL(推荐)
CREATE UNIQUE INDEX uk_emp_ssn_fn ON employees(NVL(ssn, 'NULL_SSN'));
-- ✅ 方案2:业务约束 + NOT NULL(最彻底)
ALTER TABLE employees MODIFY ssn VARCHAR2(20) NOT NULL;
-- 此时唯一索引自动支持 IS NULL?不!因为 NOT NULL 后已无 NULL,无需处理。
二、复合索引:列序即命运,覆盖即王道 里
2.1 复合索引的 B-tree 结构:前导列决定一切
Oracle 复合索引按 创建时的列顺序 构建 B-tree,其键值形如 (col1, col2, col3)。这意味着:
谓词条件是否可用索引原因WHERE col1 = ? AND col2 = ?✅ INDEX RANGE SCAN匹配前导列+次列WHERE col1 = ? AND col3 = ?⚠️ 仅 col1 有效col2 缺失 → col3 无法定位(B-tree 分支未展开)WHERE col2 = ? AND col3 = ?❌ FULL TABLE SCAN前导列 col1 未出现在 WHERE 中 → 索引无法定位起始点WHERE col1 IN (?, ?) AND col2 > ?✅ INDEX RANGE SCAN范围查询在末尾列生效
黄金法则:复合索引的列序必须严格匹配查询中最频繁、选择率最高的过滤条件顺序。没有“智能重排”,只有“精准匹配”。
2.2 场景实测:电商订单状态+时间范围查询
业务需求:后台运营需高频查询“某状态下最近 N 天的订单”,SQL 如下:
SELECT order_id, user_id, amount, status, created_time
FROM orders
WHERE status = 'SHIPPED'
AND created_time >= TRUNC(SYSDATE) - 7
ORDER BY created_time DESC;
✅ 正确复合索引设计
-- ✅ 最优:status(高选择率等值) + created_time(范围+排序)
CREATE INDEX idx_orders_status_time ON orders(status, created_time)
TABLESPACE idx_tbs
LOCAL; -- 分区表建议 LOCAL 索引
✅ 为什么这个顺序最优?
status = 'SHIPPED' 是等值查询 → 作为前导列,快速定位索引分支;created_time >= ... 是范围查询 → 放在第二位,可在 status='SHIPPED' 的子树内高效扫描;ORDER BY created_time DESC → 索引已按 created_time 排序,避免 SORT ORDER BY;查询列 order_id, user_id, amount... 虽未全在索引中,但 order_id(主键)通常被包含(若 orders 主键是 order_id,则 Oracle 自动将主键列加入索引,形成 index-organized table 或 clustered index 效果)。
Java 代码验证索引有效性
@Repository
public class OrderRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public ListfindShippedOrdersLast7Days() {
String sql = """
SELECT /*+ INDEX(o IDX_ORDERS_STATUS_TIME) */
order_id, user_id, amount, status, created_time
FROM orders o
WHERE status = ?
AND created_time >= TRUNC(SYSDATE) - ?
ORDER BY created_time DESC
""";
return jdbcTemplate.query(sql, new Object[]{"SHIPPED", 7},
(rs, rowNum) ->new Order(
rs.getLong("order_id"),
rs.getLong("user_id"),
rs.getBigDecimal("amount"),
rs.getString("status"),
rs.getTimestamp("created_time")
));
}
// 辅助方法:获取真实执行计划(含实际 IO)
public void printActualPlan(String sql, Object[] args) {
String planSql = """
SELECT * FROM TABLE(
DBMS_XPLAN.DISPLAY_CURSOR(
(SELECT sql_id FROM v$sql WHERE sql_text LIKE ? AND ROWNUM=1),
NULL,
'ALLSTATS LAST'
)
)
""";
// 实际项目中建议用 SQL_ID 绑定,此处简化
jdbcTemplate.queryForList(planSql, "%findShippedOrdersLast7Days%").forEach(System.out::println);
}
}
运行后,执行计划关键片段:
#mermaid-svg-YZHrB2vRn4trmNSf{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-YZHrB2vRn4trmNSf .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-YZHrB2vRn4trmNSf .error-icon{fill:#552222;}#mermaid-svg-YZHrB2vRn4trmNSf .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-YZHrB2vRn4trmNSf .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-YZHrB2vRn4trmNSf .marker{fill:#333333;stroke:#333333;}#mermaid-svg-YZHrB2vRn4trmNSf .marker.cross{stroke:#333333;}#mermaid-svg-YZHrB2vRn4trmNSf svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-YZHrB2vRn4trmNSf p{margin:0;}#mermaid-svg-YZHrB2vRn4trmNSf .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-YZHrB2vRn4trmNSf .cluster-label text{fill:#333;}#mermaid-svg-YZHrB2vRn4trmNSf .cluster-label span{color:#333;}#mermaid-svg-YZHrB2vRn4trmNSf .cluster-label span p{background-color:transparent;}#mermaid-svg-YZHrB2vRn4trmNSf .label text,#mermaid-svg-YZHrB2vRn4trmNSf span{fill:#333;color:#333;}#mermaid-svg-YZHrB2vRn4trmNSf .node rect,#mermaid-svg-YZHrB2vRn4trmNSf .node circle,#mermaid-svg-YZHrB2vRn4trmNSf .node ellipse,#mermaid-svg-YZHrB2vRn4trmNSf .node polygon,#mermaid-svg-YZHrB2vRn4trmNSf .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-YZHrB2vRn4trmNSf .rough-node .label text,#mermaid-svg-YZHrB2vRn4trmNSf .node .label text,#mermaid-svg-YZHrB2vRn4trmNSf .image-shape .label,#mermaid-svg-YZHrB2vRn4trmNSf .icon-shape .label{text-anchor:middle;}#mermaid-svg-YZHrB2vRn4trmNSf .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-YZHrB2vRn4trmNSf .rough-node .label,#mermaid-svg-YZHrB2vRn4trmNSf .node .label,#mermaid-svg-YZHrB2vRn4trmNSf .image-shape .label,#mermaid-svg-YZHrB2vRn4trmNSf .icon-shape .label{text-align:center;}#mermaid-svg-YZHrB2vRn4trmNSf .node.clickable{cursor:pointer;}#mermaid-svg-YZHrB2vRn4trmNSf .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-YZHrB2vRn4trmNSf .arrowheadPath{fill:#333333;}#mermaid-svg-YZHrB2vRn4trmNSf .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-YZHrB2vRn4trmNSf .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-YZHrB2vRn4trmNSf .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-YZHrB2vRn4trmNSf .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-YZHrB2vRn4trmNSf .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-YZHrB2vRn4trmNSf .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-YZHrB2vRn4trmNSf .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-YZHrB2vRn4trmNSf .cluster text{fill:#333;}#mermaid-svg-YZHrB2vRn4trmNSf .cluster span{color:#333;}#mermaid-svg-YZHrB2vRn4trmNSf div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-YZHrB2vRn4trmNSf .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-YZHrB2vRn4trmNSf rect.text{fill:none;stroke-width:0;}#mermaid-svg-YZHrB2vRn4trmNSf .icon-shape,#mermaid-svg-YZHrB2vRn4trmNSf .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-YZHrB2vRn4trmNSf .icon-shape p,#mermaid-svg-YZHrB2vRn4trmNSf .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-YZHrB2vRn4trmNSf .icon-shape .label rect,#mermaid-svg-YZHrB2vRn4trmNSf .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-YZHrB2vRn4trmNSf .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-YZHrB2vRn4trmNSf .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-YZHrB2vRn4trmNSf :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}
SELECT STATEMENT
INDEX RANGE SCANIDX_ORDERS_STATUS_TIME
TABLE ACCESS BY INDEX ROWID BATCHED ORDERS
INDEX RANGE SCAN 明确命中索引;Starts=1, E-Rows=1250, A-Rows=1247(预估与实际接近);Buffers=15(逻辑读仅 15 次,远低于全表扫描的数千次)。
❌ 反模式:列序颠倒的代价
-- ⚠️ 错误:created_time 做前导列
CREATE INDEX idx_orders_time_status ON orders(created_time, status);
此时原 SQL 执行计划变为:
#mermaid-svg-pQGM1IBHHIxPdMSv{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-pQGM1IBHHIxPdMSv .error-icon{fill:#552222;}#mermaid-svg-pQGM1IBHHIxPdMSv .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-pQGM1IBHHIxPdMSv .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-pQGM1IBHHIxPdMSv .marker{fill:#333333;stroke:#333333;}#mermaid-svg-pQGM1IBHHIxPdMSv .marker.cross{stroke:#333333;}#mermaid-svg-pQGM1IBHHIxPdMSv svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-pQGM1IBHHIxPdMSv p{margin:0;}#mermaid-svg-pQGM1IBHHIxPdMSv .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster-label text{fill:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster-label span{color:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster-label span p{background-color:transparent;}#mermaid-svg-pQGM1IBHHIxPdMSv .label text,#mermaid-svg-pQGM1IBHHIxPdMSv span{fill:#333;color:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv .node rect,#mermaid-svg-pQGM1IBHHIxPdMSv .node circle,#mermaid-svg-pQGM1IBHHIxPdMSv .node ellipse,#mermaid-svg-pQGM1IBHHIxPdMSv .node polygon,#mermaid-svg-pQGM1IBHHIxPdMSv .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-pQGM1IBHHIxPdMSv .rough-node .label text,#mermaid-svg-pQGM1IBHHIxPdMSv .node .label text,#mermaid-svg-pQGM1IBHHIxPdMSv .image-shape .label,#mermaid-svg-pQGM1IBHHIxPdMSv .icon-shape .label{text-anchor:middle;}#mermaid-svg-pQGM1IBHHIxPdMSv .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-pQGM1IBHHIxPdMSv .rough-node .label,#mermaid-svg-pQGM1IBHHIxPdMSv .node .label,#mermaid-svg-pQGM1IBHHIxPdMSv .image-shape .label,#mermaid-svg-pQGM1IBHHIxPdMSv .icon-shape .label{text-align:center;}#mermaid-svg-pQGM1IBHHIxPdMSv .node.clickable{cursor:pointer;}#mermaid-svg-pQGM1IBHHIxPdMSv .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-pQGM1IBHHIxPdMSv .arrowheadPath{fill:#333333;}#mermaid-svg-pQGM1IBHHIxPdMSv .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-pQGM1IBHHIxPdMSv .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-pQGM1IBHHIxPdMSv .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-pQGM1IBHHIxPdMSv .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-pQGM1IBHHIxPdMSv .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-pQGM1IBHHIxPdMSv .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster text{fill:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv .cluster span{color:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-pQGM1IBHHIxPdMSv .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-pQGM1IBHHIxPdMSv rect.text{fill:none;stroke-width:0;}#mermaid-svg-pQGM1IBHHIxPdMSv .icon-shape,#mermaid-svg-pQGM1IBHHIxPdMSv .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-pQGM1IBHHIxPdMSv .icon-shape p,#mermaid-svg-pQGM1IBHHIxPdMSv .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-pQGM1IBHHIxPdMSv .icon-shape .label rect,#mermaid-svg-pQGM1IBHHIxPdMSv .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-pQGM1IBHHIxPdMSv .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-pQGM1IBHHIxPdMSv .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-pQGM1IBHHIxPdMSv :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}
SELECT STATEMENT
FULL TABLE SCAN ORDERS
原因:WHERE status = ? 无法利用 created_time 前导的索引,CBO 判断全表扫描成本更低。
深入理解:Oracle 官方白皮书 Indexing Best Practices 明确指出:“The order of columns in a composite index is critical. The optimizer can use the index only if the query’s WHERE clause contains conditions on the leading column or leading columns of the index.”
2.3 复合索引进阶:覆盖索引(Covering Index)消除回表
当查询的所有列(SELECT + WHERE + JOIN)都包含在复合索引中时,Oracle 可执行 INDEX FAST FULL SCAN 或 INDEX FULL SCAN,完全避免访问表数据块,极大降低 IO。
场景:订单统计报表(只查维度字段)
-- 报表 SQL:只关心状态、日期、金额汇总,不涉及大文本字段
SELECT status, TRUNC(created_time) as day, COUNT(*), SUM(amount)
FROM orders
WHERE created_time >= DATE '2024-01-01'
GROUP BY status, TRUNC(created_time);
✅ 创建覆盖索引:
-- ✅ 覆盖索引:包含所有 GROUP BY 和聚合字段
CREATE INDEX idx_orders_covering ON orders(
created_time, -- WHERE 范围条件
status, -- GROUP BY 列
amount -- 聚合字段(SUM 需要值)
)
COMPRESS 2; -- 压缩前两列(created_time+status),节省空间
⚠️ 注意:TRUNC(created_time) 是函数,普通索引无法直接匹配。此处 WHERE created_time >= ... 是范围查询,TRUNC() 仅用于 GROUP BY,而索引中存的是原始 created_time,因此 TRUNC() 在内存中计算,不影响索引使用。
Java 中验证:
public ListgetOrderSummaryByDay() {
String sql = """
SELECT status, TRUNC(created_time) as day, COUNT(*), SUM(amount)
FROM orders
WHERE created_time >= ?
GROUP BY status, TRUNC(created_time)
ORDER BY day DESC, status
""";
return jdbcTemplate.query(sql, new Object[]{Date.valueOf("2024-01-01")},
(rs, rowNum) ->new OrderSummary(
rs.getString("status"),
rs.getDate("day"),
rs.getLong("COUNT(*)"),
rs.getBigDecimal("SUM(amount)")
));
}
执行计划中将出现:
INDEX FAST FULL SCAN IDX_ORDERS_COVERING
→ 表示 仅扫描索引块,不访问 orders 表,性能提升 3~10 倍(取决于表大小)。
三、函数索引:让“计算”也能走索引 燐
3.1 函数索引的本质:索引化表达式结果
传统索引只能加速对原始列值的查询。但业务中大量存在“计算后查询”场景:
WHERE UPPER(name) = 'JOHN DOE'WHERE TRUNC(order_date) = DATE '2024-01-01'WHERE NVL(discount_rate, 0) > 0.1WHERE SUBSTR(phone, 1, 3) = '138'
这些表达式会让 Oracle 放弃使用普通索引,因为索引中存的是原始值(如 'john doe', 2024-01-01 14:30:00),而非计算结果。
✅ 函数索引正是为此而生:它将表达式计算结果作为索引键存储,使 WHERE func(col) = ? 能直接走索引。
3.2 场景实测:不区分大小写的用户名搜索
业务要求:前端输入用户名,后台模糊匹配(不区分大小写),且需高性能。
❌ 普通方案(灾难性)
// Java 层转大写,然后查
String upperName = userName.toUpperCase();
Listusers = jdbcTemplate.query(
"SELECT * FROM users WHERE UPPER(name) = ?",
new Object[]{upperName},
userRowMapper
);
→ UPPER(name) 导致全表扫描(FUNCTION 在 WHERE 中,索引失效)。
✅ 函数索引方案(秒级响应)
-- ✅ 创建函数索引(注意:需保证函数确定性)
CREATE INDEX idx_users_upper_name ON users(UPPER(name))
TABLESPACE idx_tbs;
-- ⚠️ 关键:启用查询重写(让优化器知道 UPPER(name) 可用此索引)
ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE;
ALTER SESSION SET QUERY_REWRITE_INTEGRITY = TRUSTED;
Oracle 文档说明:Function-Based Indexes 要求函数必须是 DETERMINISTIC(确定性),UPPER()、TRUNC()、NVL() 均满足。
Java 代码无缝对接(无需改 SQL!)
@Service
public class UserService {
public ListfindUsersByNameIgnoreCase(String name) {
// ✅ 完全不变的 SQL!函数索引自动生效
String sql = "SELECT id, name, email FROM users WHERE UPPER(name) = ?";
// 强制使用函数索引(可选)
String hintedSql = "SELECT /*+ INDEX(u IDX_USERS_UPPER_NAME) */ " +
"id, name, email FROM users u WHERE UPPER(name) = ?";
return jdbcTemplate.query(hintedSql, new Object[]{name.toUpperCase()},
(rs, rowNum) ->new User(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email")
));
}
}
执行计划:
#mermaid-svg-dm6PghlfylPXT7dQ{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-dm6PghlfylPXT7dQ .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-dm6PghlfylPXT7dQ .error-icon{fill:#552222;}#mermaid-svg-dm6PghlfylPXT7dQ .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-dm6PghlfylPXT7dQ .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-dm6PghlfylPXT7dQ .marker{fill:#333333;stroke:#333333;}#mermaid-svg-dm6PghlfylPXT7dQ .marker.cross{stroke:#333333;}#mermaid-svg-dm6PghlfylPXT7dQ svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-dm6PghlfylPXT7dQ p{margin:0;}#mermaid-svg-dm6PghlfylPXT7dQ .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-dm6PghlfylPXT7dQ .cluster-label text{fill:#333;}#mermaid-svg-dm6PghlfylPXT7dQ .cluster-label span{color:#333;}#mermaid-svg-dm6PghlfylPXT7dQ .cluster-label span p{background-color:transparent;}#mermaid-svg-dm6PghlfylPXT7dQ .label text,#mermaid-svg-dm6PghlfylPXT7dQ span{fill:#333;color:#333;}#mermaid-svg-dm6PghlfylPXT7dQ .node rect,#mermaid-svg-dm6PghlfylPXT7dQ .node circle,#mermaid-svg-dm6PghlfylPXT7dQ .node ellipse,#mermaid-svg-dm6PghlfylPXT7dQ .node polygon,#mermaid-svg-dm6PghlfylPXT7dQ .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-dm6PghlfylPXT7dQ .rough-node .label text,#mermaid-svg-dm6PghlfylPXT7dQ .node .label text,#mermaid-svg-dm6PghlfylPXT7dQ .image-shape .label,#mermaid-svg-dm6PghlfylPXT7dQ .icon-shape .label{text-anchor:middle;}#mermaid-svg-dm6PghlfylPXT7dQ .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-dm6PghlfylPXT7dQ .rough-node .label,#mermaid-svg-dm6PghlfylPXT7dQ .node .label,#mermaid-svg-dm6PghlfylPXT7dQ .image-shape .label,#mermaid-svg-dm6PghlfylPXT7dQ .icon-shape .label{text-align:center;}#mermaid-svg-dm6PghlfylPXT7dQ .node.clickable{cursor:pointer;}#mermaid-svg-dm6PghlfylPXT7dQ .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-dm6PghlfylPXT7dQ .arrowheadPath{fill:#333333;}#mermaid-svg-dm6PghlfylPXT7dQ .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-dm6PghlfylPXT7dQ .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-dm6PghlfylPXT7dQ .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-dm6PghlfylPXT7dQ .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-dm6PghlfylPXT7dQ .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-dm6PghlfylPXT7dQ .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-dm6PghlfylPXT7dQ .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-dm6PghlfylPXT7dQ .cluster text{fill:#333;}#mermaid-svg-dm6PghlfylPXT7dQ .cluster span{color:#333;}#mermaid-svg-dm6PghlfylPXT7dQ div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-dm6PghlfylPXT7dQ .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-dm6PghlfylPXT7dQ rect.text{fill:none;stroke-width:0;}#mermaid-svg-dm6PghlfylPXT7dQ .icon-shape,#mermaid-svg-dm6PghlfylPXT7dQ .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-dm6PghlfylPXT7dQ .icon-shape p,#mermaid-svg-dm6PghlfylPXT7dQ .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-dm6PghlfylPXT7dQ .icon-shape .label rect,#mermaid-svg-dm6PghlfylPXT7dQ .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-dm6PghlfylPXT7dQ .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-dm6PghlfylPXT7dQ .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-dm6PghlfylPXT7dQ :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}
SELECT STATEMENT
INDEX RANGE SCANIDX_USERS_UPPER_NAME
TABLE ACCESS BY INDEX ROWID BATCHED USERS
→ UPPER(name) 谓词成功命中函数索引。
3.3 高级技巧:组合函数索引 + 覆盖查询
场景:需要按“年月”分组统计订单数,且 order_date 是 TIMESTAMP 类型。
-- 传统写法(慢)
SELECT TO_CHAR(order_date, 'YYYY-MM') as ym, COUNT(*)
FROM orders
GROUP BY TO_CHAR(order_date, 'YYYY-MM');
✅ 创建组合函数索引:
-- ✅ 索引化 TO_CHAR 结果,并覆盖 COUNT(*)
CREATE INDEX idx_orders_ym ON orders(TO_CHAR(order_date, 'YYYY-MM'))
TABLESPACE idx_tbs;
但注意:TO_CHAR(order_date, 'YYYY-MM') 返回字符串,索引可加速 WHERE TO_CHAR(...) = '2024-01',但 GROUP BY 仍需计算。更优解是 物化函数索引 + 覆盖:
-- ✅ 最佳:索引包含原始列,GROUP BY 用 TRUNC(可走索引)
CREATE INDEX idx_orders_month ON orders(TRUNC(order_date, 'MM'));
-- 然后改写 SQL:
SELECT TRUNC(order_date, 'MM') as month_start, COUNT(*)
FROM orders
GROUP BY TRUNC(order_date, 'MM');
→ TRUNC(order_date, 'MM') 是确定性函数,索引可加速 GROUP BY,且 TRUNC() 结果可直接用于分组,零计算开销。
Java 中:
public MapgetMonthlyOrderCount() {
String sql = """
SELECT TRUNC(order_date, 'MM') as month_start, COUNT(*) as cnt
FROM orders
GROUP BY TRUNC(order_date, 'MM')
ORDER BY month_start DESC
""";
return jdbcTemplate.query(sql, (rs, rowNum) ->{
LocalDate month = rs.getDate("month_start").toLocalDate();
Long count = rs.getLong("cnt");
return Map.entry(month, count);
}).stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
四、三类索引决策树:一张图看懂选哪个
面对一个新查询需求,如何快速决策?以下是经过数百个生产案例验证的 索引选型决策流程图:
#mermaid-svg-vhpw29td7Mup9uj1{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-vhpw29td7Mup9uj1 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-vhpw29td7Mup9uj1 .error-icon{fill:#552222;}#mermaid-svg-vhpw29td7Mup9uj1 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-vhpw29td7Mup9uj1 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-vhpw29td7Mup9uj1 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-vhpw29td7Mup9uj1 .marker.cross{stroke:#333333;}#mermaid-svg-vhpw29td7Mup9uj1 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-vhpw29td7Mup9uj1 p{margin:0;}#mermaid-svg-vhpw29td7Mup9uj1 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-vhpw29td7Mup9uj1 .cluster-label text{fill:#333;}#mermaid-svg-vhpw29td7Mup9uj1 .cluster-label span{color:#333;}#mermaid-svg-vhpw29td7Mup9uj1 .cluster-label span p{background-color:transparent;}#mermaid-svg-vhpw29td7Mup9uj1 .label text,#mermaid-svg-vhpw29td7Mup9uj1 span{fill:#333;color:#333;}#mermaid-svg-vhpw29td7Mup9uj1 .node rect,#mermaid-svg-vhpw29td7Mup9uj1 .node circle,#mermaid-svg-vhpw29td7Mup9uj1 .node ellipse,#mermaid-svg-vhpw29td7Mup9uj1 .node polygon,#mermaid-svg-vhpw29td7Mup9uj1 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-vhpw29td7Mup9uj1 .rough-node .label text,#mermaid-svg-vhpw29td7Mup9uj1 .node .label text,#mermaid-svg-vhpw29td7Mup9uj1 .image-shape .label,#mermaid-svg-vhpw29td7Mup9uj1 .icon-shape .label{text-anchor:middle;}#mermaid-svg-vhpw29td7Mup9uj1 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-vhpw29td7Mup9uj1 .rough-node .label,#mermaid-svg-vhpw29td7Mup9uj1 .node .label,#mermaid-svg-vhpw29td7Mup9uj1 .image-shape .label,#mermaid-svg-vhpw29td7Mup9uj1 .icon-shape .label{text-align:center;}#mermaid-svg-vhpw29td7Mup9uj1 .node.clickable{cursor:pointer;}#mermaid-svg-vhpw29td7Mup9uj1 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-vhpw29td7Mup9uj1 .arrowheadPath{fill:#333333;}#mermaid-svg-vhpw29td7Mup9uj1 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-vhpw29td7Mup9uj1 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-vhpw29td7Mup9uj1 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-vhpw29td7Mup9uj1 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-vhpw29td7Mup9uj1 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-vhpw29td7Mup9uj1 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-vhpw29td7Mup9uj1 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-vhpw29td7Mup9uj1 .cluster text{fill:#333;}#mermaid-svg-vhpw29td7Mup9uj1 .cluster span{color:#333;}#mermaid-svg-vhpw29td7Mup9uj1 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-vhpw29td7Mup9uj1 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-vhpw29td7Mup9uj1 rect.text{fill:none;stroke-width:0;}#mermaid-svg-vhpw29td7Mup9uj1 .icon-shape,#mermaid-svg-vhpw29td7Mup9uj1 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-vhpw29td7Mup9uj1 .icon-shape p,#mermaid-svg-vhpw29td7Mup9uj1 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-vhpw29td7Mup9uj1 .icon-shape .label rect,#mermaid-svg-vhpw29td7Mup9uj1 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-vhpw29td7Mup9uj1 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-vhpw29td7Mup9uj1 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-vhpw29td7Mup9uj1 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}
是
否
是
是
否
是
否
否
是
否
开始:分析 SQL 查询条件
WHERE 中是否有 = 且业务语义唯一?
✅ 优先建唯一索引例:email, phone, order_no
WHERE 中是否有多个列联合过滤?
是否满足“前导列高选择率+后续列范围/排序”?
✅ 建复合索引列序=WHERE列序+ORDER BY列
是否涉及函数计算?UPPER/ TRUNC/ NVL/ SUBSTR等
✅ 建函数索引索引表达式=WHERE中函数
❌ 检查是否遗漏索引或考虑物化视图
SELECT 列是否极少?且 WHERE 条件简单?
✅ 单列索引足够
❌ 评估是否需要覆盖索引
验证:执行计划是否 INDEX UNIQUE SCAN
验证:是否 INDEX RANGE SCAN + 无 SORT ORDER BY
验证:是否 INDEX RANGE SCAN on function-index
使用说明:
从 A 节点 开始,逐层回答问题;绿色节点(✅)表示推荐方案;红色节点(❌)表示需警惕或深入分析;所有验证步骤(M/N/O)必须通过 EXPLAIN PLAN 或 DBMS_XPLAN.DISPLAY_CURSOR 实际执行确认,切勿凭经验猜测。
五、Java 工程实践:索引变更的灰度与监控 ️
索引不是“建完就完”,而是需要 可观测、可回滚、可压测 的工程资产。
5.1 索引创建的灰度策略
在生产环境,直接 CREATE INDEX 可能锁表(尤其 ONLINE 选项未启用时)。正确姿势:
-- ✅ 建议始终加 ONLINE(Oracle 12c+ 默认,但显式声明更安全)
CREATE INDEX idx_orders_status_time_new
ON orders(status, created_time)
ONLINE
TABLESPACE idx_tbs;
-- ✅ 创建后立即收集统计信息(避免优化器用旧统计)
EXEC DBMS_STATS.GATHER_INDEX_STATS('YOUR_SCHEMA', 'IDX_ORDERS_STATUS_TIME_NEW');
Java 中封装索引管理服务(Spring Boot):
@Service
public class IndexManagementService {
@Autowired
private JdbcTemplate jdbcTemplate;
// 灰度开关:通过配置中心控制
@Value("${oracle.index.enable-new-order-index:false}")
private boolean enableNewOrderIndex;
@Transactional
public void createOrderIndexIfEnabled() {
if (!enableNewOrderIndex) {
System.out.println("❌ New order index disabled by config");
return;
}
try {
// 1. 创建索引(ONLINE)
jdbcTemplate.execute("""
CREATE INDEX idx_orders_status_time_new
ON orders(status, created_time) ONLINE
TABLESPACE idx_tbs
""");
// 2. 收集统计信息
jdbcTemplate.execute("""
BEGIN
DBMS_STATS.GATHER_INDEX_STATS(
ownname => 'YOUR_SCHEMA',
indname => 'IDX_ORDERS_STATUS_TIME_NEW'
);
END;
""");
System.out.println("✅ New index created and stats gathered");
} catch (DataAccessException e) {
// 记录告警,但不抛异常(避免阻塞主流程)
log.error("Failed to create index, proceeding without...", e);
}
}
}
5.2 索引效果监控:Java 端埋点
在关键 DAO 方法中,自动记录执行计划与耗时:
@Aspect
@Component
public class IndexMonitoringAspect {
private static final Logger log = LoggerFactory.getLogger(IndexMonitoringAspect.class);
@Around("@annotation(org.springframework.stereotype.Repository) && execution(* *(..))")
public Object monitorIndexUsage(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.nanoTime();
Object result = joinPoint.proceed();
long durationNs = System.nanoTime() - start;
double durationMs = durationNs / 1_000_000.0;
// 提取 SQL(简化版,实际用 PreparedStatementExtractor)
String sql = extractSqlFromJoinPoint(joinPoint);
if (sql.contains("orders") && (sql.contains("status") || sql.contains("UPPER"))) {
// 获取执行计划
String plan = getExecutionPlanForSql(sql);
if (plan.contains("FULL TABLE SCAN")) {
log.warn(" SLOW QUERY DETECTED: {} ms\nPlan:\n{}",
durationMs, plan.substring(0, Math.min(500, plan.length())));
// 发送告警到 Prometheus / Grafana
IndexMetrics.slowQueryCounter.labels("orders").inc();
}
}
return result;
}
}
5.3 索引冗余检测:自动识别“僵尸索引”
长期运行后,数据库易积累无用索引(从未被使用、被更优索引覆盖)。可通过 V$OBJECT_USAGE 视图检测:
-- 查询近30天未使用的索引
SELECT
io.name AS index_name,
t.name AS table_name,
io.used AS used_flag,
io.start_monitoring,
io.end_monitoring
FROM v$object_usage io
JOIN sys.obj$ o ON io.index_name = o.name
JOIN sys.obj$ t ON o.owner# = t.owner# AND o.obj# = t.obj#
WHERE io.used = 'NO'
AND io.start_monitoring < SYSDATE - 30;
Java 中定时任务清理:
@Component
public class IndexCleanupScheduler {
@Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点
public void cleanupUnusedIndexes() {
List> unused = jdbcTemplate.queryForList("SELECT index_name, table_name FROM v$object_usage " +
"WHERE used = 'NO' AND start_monitoring < SYSDATE - 30"
);
for (Mapidx : unused) {
String idxName = (String) idx.get("INDEX_NAME");
String tblName = (String) idx.get("TABLE_NAME");
try {
jdbcTemplate.execute("DROP INDEX " + idxName);
log.info("️ Dropped unused index: {}.{}", tblName, idxName);
} catch (Exception e) {
log.error("Failed to drop index {}", idxName, e);
}
}
}
}
六、避坑指南:那些让索引失效的 Java 陷阱 ⚠️
即使索引设计完美,Java 层的写法也可能让它“视而不见”。
6.1 隐式类型转换:String vs NUMBER
// ❌ 危险:Java 传 String,但数据库列是 NUMBER
jdbcTemplate.query("SELECT * FROM products WHERE price = ?",
new Object[]{"99.99"}, // String 类型
rowMapper);
// Oracle 内部执行:WHERE TO_NUMBER('99.99') = price → 函数在列上!索引失效
✅ 正确:确保类型严格匹配
jdbcTemplate.query("SELECT * FROM products WHERE price = ?",
new Object[]{new BigDecimal("99.99")}, // BigDecimal
rowMapper);
6.2 Like 模糊查询:前导通配符的诅咒
// ❌ 全表扫描:WHERE name LIKE '%john%'
jdbcTemplate.query("SELECT * FROM users WHERE name LIKE ?",
new Object[]{"%john%"}, rowMapper);
// ✅ 可走索引:WHERE name LIKE 'john%' (前导非通配符)
jdbcTemplate.query("SELECT * FROM users WHERE name LIKE ?",
new Object[]{"john%"}, rowMapper);
若必须 %john%,考虑 Oracle Text 索引或 INSTR(name, ?) > 0 + 函数索引:
CREATE INDEX idx_users_instr ON users(INSTR(name, 'X')) -- 不实用,仅示意
-- 更佳:用 CONTEXT 索引(Oracle Text)
6.3 绑定变量窥探(Bind Peeking)引发的执行计划漂移
Oracle 11g+ 默认启用绑定变量窥探,首次执行时根据绑定值生成计划,后续复用。若首次值是 status='DRAFT'(占比 90%),计划走全表扫描;后续 status='SHIPPED'(占比 1%)仍复用全表扫描计划 → 性能雪崩。
✅ 解决方案:使用 BIND_AWARE 游标或 ADAPTIVE CURSOR SHARING:
-- 在 SQL 中添加提示(临时缓解)
SELECT /*+ OPT_PARAM('_optim_peek_user_binds', 'false') */ *
FROM orders WHERE status = ?;
更根本:Java 层对不同选择率的值,使用不同 SQL 模板(如 status_drafted.sql, status_shipped.sql),由 Spring 的 @Cacheable 或配置驱动。
七、总结:索引是契约,不是魔法杖 ✨
回到本文开头的问题:
“加了索引为什么还慢?”
答案从来不是“索引不够多”,而是 “索引与查询之间缺乏精准契约”。
唯一索引 是你向 Oracle 签下的 单行承诺:我保证这个值只有一条,你查到就停 → 换来 INDEX UNIQUE SCAN 的极致效率;复合索引 是一份 列序合约:我按 status+time 顺序组织数据,你必须先问 status,再问 time → 违约即全表扫描;函数索引 是一次 表达式授权:我把 UPPER(name) 的结果存起来,你查 UPPER(name) 时请直接拿 → 让计算走入索引世界。
而 Java 工程师的角色,是这份契约的 起草者、签署者与审计员: ✍️ 起草时,用 EXPLAIN PLAN 验证每一条 SQL; ✍️ 签署时,用 ONLINE 和灰度开关敬畏生产; ✍️ 审计时,用监控和清理让索引永葆活力。
最后,请记住这条朴素真理:
最好的索引,是那个让你忘记它的索引。 它安静伫立,不抢流量,不占日志,只在查询命中的瞬间,以毫秒为单位,交付确定性的快。
现在,打开你的 IDE,挑一个慢查询,对照本文决策树,动手建一个真正“按需”的索引吧! ️
延伸学习:
Oracle Database SQL Tuning Guide — 官方权威调优手册Ask Tom: Indexing Strategies — Tom Kyte 经典问答(Oracle 索引教父)The Art of SQL Indexing — Luke Plant 的交互式索引教程(含实时执行计划演示)
感谢你读到这里! 技术之路没有捷径,但每一次阅读、思考和实践,都在悄悄拉近你与目标的距离。 如果本文对你有帮助,不妨 点赞、 收藏、 分享 给更多需要的朋友! 欢迎在评论区留下你的想法、疑问或建议,我会一一回复,我们一起交流、共同成长 关注我,不错过下一篇干货!我们下期再见!✨