Oracle 9i SQL优化快速手册V1.00
- 格式:doc
- 大小:138.00 KB
- 文档页数:5
Oracle SQL的优化标签:oraclesql优化date数据库subquery2009-10-14 21:18 18149人阅读评论(21) 收藏举报分类:Oracle Basic Knowledge(208)SQL的优化应该从5个方面进行调整:1.去掉不必要的大型表的全表扫描2.缓存小型表的全表扫描3.检验优化索引的使用4.检验优化的连接技术5.尽可能减少执行计划的CostSQL语句:是对数据库(数据)进行操作的惟一途径;消耗了70%~90%的数据库资源;独立于程序设计逻辑,相对于对程序源代码的优化,对SQL语句的优化在时间成本和风险上的代价都很低;可以有不同的写法;易学,难精通。
SQL优化:固定的SQL书写习惯,相同的查询尽量保持相同,存储过程的效率较高。
应该编写与其格式一致的语句,包括字母的大小写、标点符号、换行的位置等都要一致ORACLE优化器:在任何可能的时候都会对表达式进行评估,并且把特定的语法结构转换成等价的结构,这么做的原因是要么结果表达式能够比源表达式具有更快的速度要么源表达式只是结果表达式的一个等价语义结构不同的SQL结构有时具有同样的操作(例如:= ANY (subquery) and IN (subquery)),ORACLE会把他们映射到一个单一的语义结构。
1 常量优化:常量的计算是在语句被优化时一次性完成,而不是在每次执行时。
下面是检索月薪大于2000的的表达式:sal > 24000/12sal > 2000sal*12 > 24000如果SQL语句包括第一种情况,优化器会简单地把它转变成第二种。
优化器不会简化跨越比较符的表达式,例如第三条语句,鉴于此,应尽量写用常量跟字段比较检索的表达式,而不要将字段置于表达式当中。
否则没有办法优化,比如如果sal上有索引,第一和第二就可以使用,第三就难以使用。
2 操作符优化:优化器把使用LIKE操作符和一个没有通配符的表达式组成的检索表达式转换为一个“=”操作符表达式。
Oracle 9i 和10g 高性能调优介绍让我们从安装所需要的检查的事物开始来讨论oracle的优化。
调优环境调优的环境是什么?是一个你的调优努力能起作用的一种环境。
调整oralce数据库的所必需的东西⏹好多软件工具⏹训练有素的人⏹分段的测试环境⏹生产环境的一个副本○真实的和期望的生产环境。
在成长快速或者需求改变时,这些环境是经常不同的。
○经可能的使得数据库的大小/内容一致。
在不能完全满足这样的要求时,至少开发和测试数据库应该同生产数据库成比例○统计表是一样的吗?统计表可以拷贝,或者同生产数据库使用同样的时间间隔执行可用工具调整和监控数据库的优秀软件很多。
OEM有很多非常有用的小组件。
Spotlight擅长于对繁忙系统的视频和信息进行实时监控。
两者对调整数据库物理和SQL代码的性能分析都是非常有用的。
也有许多其他的工具可用。
在调整过程中最重要的工具是developer和administrators。
那是为什么你读这本书的原因。
最好的软件工具也意味着是最昂贵的,当然这也不是说较为便宜的工具是无用的了。
通常,越贵的软件为你所做的事情越多。
然而,有时候自动为你做了某些工作,你不理解其内部机制。
你的工具集未必比经过良好训练,经验丰富的数据库管理员和开发人员作得更好。
训练有素的人好的训练有其恰当的地方。
作为系统管理员或者开发者,数据库管理员趋向于有root权限。
每一种训练都有其优缺点。
开发者除了编码SQL,创建数据模块之外,所了解的知识越来越多。
系统管理员对unix之类的操作系统知识具有广泛的了解,关注的是oracle数据库的物理存储的调优。
开发者关注的是数据库模型和创建更为高效的SQL代码方面的优化。
幸的是,事情不总是如此。
有时候开发者趋向于把调优SQL代码和数据模型负担看着是数据库管理的负责范围。
这样就会导致混乱。
分段的环境你需要尽可能多的实验环境。
作为DBA,你不能期望在一个在线的生产数据库上进行调优工作。
Step-by-Step Cookbook for Identifying and Tuning SQL ProblemsAshish Agrawal - Consulting Product Manager, Oracle Baki Şahin- Database Operation Supervisor, AveA TurkeySafe Harbor StatementThe following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.This document in any form, software or printed matter, contains proprietary information that is the exclusive property of Oracle. Your access to and use of this confidential material is subject to the terms and conditions of your Oracle Software License and Service Agreement, which has been executed and with which you agree to comply. This document and information contained herein may not be disclosed, copied, reproduced or distributed to anyone outside Oracle without prior written consent of Oracle. This document is not part of your license agreement nor can it be incorporated into any contractual agreement with Oracle or its subsidiaries or affiliates.▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, Korea▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, KoreaWhy SQL statements regress?3 Broad CategoriesOptimizerApplicationResource and contentionIssuesWhy SQL statements regress? Optimizer-relatedStale/Missing statisticsOverly general statistics or incorrect histogramsImproper optimizer configurationUpgraded database: new optimizerChanging statistics (refresh)Changing data (plans do not scale with data)Bind-sensitive SQL with bind peekingNot parallelized (no scaling to large data)Improperly parallelized (skews, RAC, etc.)Application-relatedMissing access structures Poorly written SQL statementsLiteral usage Bad execution plans - Full table scans- Cartesian joinResource and Contention Issues-relatedHardware resource crunch- CPU, Memory, IO, NetworkData fragmentationLogical Contention- Row lock contention- Block update contention Example:-enq: TX - allocate ITL entry enq: TX - contention enq: TX - index contention enq: US - contentionConsumes high CPU, buffer gets, I/O, PGA memory▪Long running SQL or significantly different runtimes▪High I/O, CPU, memory, network waits▪TX Enqueue Waits, Row Lock Contention▪Plan regression▪SQL appear in- Top Activity Page- ASH Analytics Page- ADDM Report, AWR Report, ASH reportsSub-optimal SQL performance: Symptoms SymptomsProgram Agenda▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, KoreaHow to identify these SQL performance problems?Identify SQL performance problems using: ADDM and ASH Analytics SQLs consuming high DB timeReal-time SQL Monitoring & Database Operations Monitoring Long running SQLs and operationsSQL Performance Analyzer (proactive)SQLs with execution plan changesIdentify expensive SQL (Excessive DB time): ADDM and ASH Analytics•Analyze current database performance ADDMthrough ADDM runsASH Analytics•Next generation Top Activity PageIdentify expensive SQL: ADDM SQL consuming too much DB timeADDMThroughput centric: Goal is toreduce ‘DB time’Identifies top SQLShows SQL impactFrequency of occurrencePinpoints root causeIdentify expensive SQL: ASH AnalyticsFlexible Time PickerFlexible Activity ChartFlexible Top Chart Flexible Top ChartASH Analytics Active Reports DemoIdentify expensive SQL: ASH AnalyticsActive Reports Demo Click on SaveIdentify long running SQL: Real-Time SQL MonitoringAutomatically monitors instances of long running SQL, PL/SQL executionsEnabled out-of-the-box withnoperformanceoverheadObviates needto traceindividual SQLShows globalPL/SQL andSQL levelstatisticsGuides tuningeffortsDatabase monitoring ofapplication jobs▪Grouping of SQLs, sessionsfor the application jobs▪Key scenarios: ETLoperations, Quarter End ClosejobsDriven by applicationspecified tagging▪Oracle Data Pump jobs automatically monitored ▪Tagging ability in PL/SQL,OCI, JDBC Identify long running Database operations: Real-Time Database Operations Monitoring New inVisibility into top sql statements▪Tests and predicts impact of system changes on SQL query performance▪Analyzes overall performance impact including improvements or regressions▪Common plan change scenarios▪Database parameter, schema changes▪Statistics gathering refresh▪I/O subsystem changes, Exadata▪Database upgrades or patchesIdentify SQL plan changes: SPA SPAProgram Agenda▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, Korea•Multitenant database-aware•All SQL’s are tuned across all PDB’s where it has executed before. •Empowers the CDBA to tune across PDBs in one clickSQL ProfilingStatistics Analysis Access Path Analysis SQL Restructure Analysis Alternative Plan AnalysisParallel Query AnalysisAutomatic Tuning OptimizerAdministratorComprehensive SQL Tuning RecommendationsGather Missing or Stale StatisticsCreate a SQL Profile Add Missing Access StructuresModify SQL ConstructsAdopt Alternative Execution Plan (11.2) Create Parallel SQL Profile (11.2)SQL Tuning AdvisorNew inAutomatic Tuning Optimizer verifies andadjusts its own cardinality estimatesOptimizer provides additional informationto generate execution planTest executes the recommendedexecution plan for performanceReviews execution historyIdeal when cardinality estimates are wrong, collection ofstatistics on objects or creation of new indexes is requiredTuning SQL: SQL Plan Baselines Some optimizer related change inthe environment results in a newplan being generatedNew plan is not the same as thebaseline – new plan is notexecuted but marked for verificationExecute known plan baseline - plan performance is “verify by history”Verifying the new plan1) DBA can verify plan at any time2) Adaptive SPM, SPM Evolve Advisorruns daily in the scheduledmaintenance window.Ideal when you need to preserve and use good, known and verified execution plansTuning SQL: SQL Access AdvisorRecommendations•B-tree indexes •Bitmap indexes•Function-based indexesIndexes •Fast refreshable•Full refreshable MVsMaterialized views and view logs• Local, Range, Hash typePartition indexIdeal when you need advice for creation of indexes, mviewsand partition for your entire workload•Range, Interval, Hash, Range-Hash, Range-List type, List •New partitioning schemes on already partitioned tablesPartition tableTuning SQL: Real-time SQL Monitoring Case StudyI enabled parallel query, yet this query is taking so long. What’s going on?Parallel server downgrades?•Uncontrolled parallel execution•Parallel Server availability•Object level settings•Session level settingsIdeal when you need to tune long running SQLs, complex queries with big executionplans, parallel queries, DML and DDL statements, Exadata smart scans, cases of a poor indexing strategiesTuning SQL: Real-time SQL Monitoring Insert executed with parallel hintTuning SQL: Real-time SQL Monitoring Parallel Tab•Parallel Coordinator busy for the entire duration!!Tuning SQL: Real-Time SQL Monitoring Solution: Enabled Parallel DMLParallel Slaves busy for the entire durationProgram Agenda▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, KoreaPreventing SQL problems:Finding Regressed SQL statements proactively using SPA Copyright © 2011, Oracle and/or its affiliates. All rights reserved. |Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 of the corporate presentation template32 SPA ChallengesProduction DatabaseTest Database DBATest System: Safe But… ▪Requires separate HW ▪Data in test system should besame as production ▪Lengthy, error-prone taskProduction System: Easier but… ▪Could be resource intensive and impact production performance ▪Changes needs to be manually scoped to private session ▪Could take a long time to finish▪No resource control by defaultRunning SPA on:SPA Quick CheckNew in EM 12c Database Plug-in 12.1.0.5•Optimizer Gather Statistics •Init.ora parameter changes •Index creation•Support for DB Release 11g and aboveSupports routine production change use cases•Uses pre-selected STS that represents workload to be tested •Default SPA settingsSimplifies precise identification of plan regressions •Optimal Trial or Explain Plan Mode•Per SQL Time Limit, Resource Consumer Group•Limits testing scope to private sessionDesigned and optimized for production usePer SQL Time Limits, Resource Consumer GroupProduction DatabaseSPA Quick CheckOptimizedControlledScopedOptimal Trial ModeLimits testing scope to private sessionPre-selected STS and default SPA settingsSPA Quick Check Optimal Trial ModeIdentifies subset SQL workload with planchanges first Test-executes onlySQLs with planchangesMinimizes use ofproduction resourcesdramatically•In general, resourceconsumption reduced in therange of 10x or moreSPA Quick Check: Setup Minimal use of production resources Per-SQL Time Limit - preventsany runaway SQLsDisables Multiple ExecutionsUses Resource Consumer Group Executes only the query part ofthe DML without modifying dataSPA Quick CheckLaunch SPA in-line with Gather Optimizer Statistics workflowSPA Quick CheckWorkflow for validating Gather Optimizer StatisticsOptimizer statistics gathering option PUBLISH set to FALSE temporarily during the processFour trials automatically executed, compared and reports generatedSPA Quick CheckWorkflow for Validating Gather Optimizer Statistics Providesactionable recommendations on the reportPublish thepending statisticsCreate SQL TuningSet for regressedSQLsOffers two optionsto fix regressedSQL resulting fromplan changesCreate SQL PlanBaselinesExplore alternateexecution plansusing SQL TuningAdvisorCopyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 38SPA Quick CheckGather Optimizer Statistics – SPA ReportSPA Reportwithout anyregressionPreventing SQL problems: SPA Quick CheckInit.ora changes: Validate optimizer related init parameter changeNote: Applies to optimizer related changes and session parameters onlyFirst trial with current parameter valuesParameter change only effective in private sessionSecond trial with changed values Generates comparison reportProvides actionable recommendations on the report (buttons)Preventing SQL problems: SPA Quick Check New index creation: Use SPA Quick Check to find any plan changes Note: Indexes are only visible in a scoped manner to the session, uses optimizer_use_invisible_indexes=true in private sessionFirst trial with current environment Create index in invisible mode Second trial with index invisible Generatescomparison report Provides actionable recommendations on the report (buttons)Program Agenda▪Why SQL statements regress?▪Identifying problematic SQL▪Tuning SQL▪Preventing SQL problems▪Real-World Customer Experiences - AveA, Turkey- S. Corporation, Korea42Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1211g Upgrade Project using Oracle Real Application TestingBaki ŞahinDatabase OperationSupervisorAVEAAvea is the youngest GSM operator of Turkey with its 13.6 million customers. • The only GSM 1800 mobile operator of Turkey• Founded in 2004 merged of 2 GSM Operators (Aria & Aycell)• Nationwide customer base of 13.6 million• Provide GSM service 98% of the population in Turkey AVEA• Around 3000 people work for Avea• Certified as an R&D company in 2010Prepaid History Workload Description Application•All transaction related to prepaid customers except bonus •Store last 6 months traffic•Business rules for post-sales processes. (Rule engine)•Configuration of subscriber servicesDatabase•Database size is ~2.5Tb•Workload can roughly be classified into 2 parts:❑OLTP transactions is done during business hours❑Batch processing is done after business hoursOverview of Configuration10.2 11g Database UpgradeCompare PerformanceRegressed SQL StatementsPlans unchanged•Majority of plans unchanged•Unlock statistics collections for tables•Collects optimizer statistics again using 11g database•Run SPA againPlans changed – fixing regressions•Create Baselines•Work with developers•Indexes created or dropped•Run SPA againConclusion Benefits for usRisk reduction❑Replays All SQL❑Real Bind ValuesTest production SQL workload before upgrade Tune regressed SQL statementsNo surprises when upgraded to 11.2.0.3Report what will happen before upgrade To be more safeReusable processReduced resource requirements ❑1 team against 4 teamsFully proven recommendations ❑Easier to convince business。
Oracle sql 优化一.培训目地数据库参数进行优化所获得地性能提升全部加起来只占数据库应用系统性能提升地40%左右,其余60%地系统性能提升全部来自对应用程序地优化.许多优化专家甚至认为对应用程序地优化可以得到80%地系统性能提升.因此可以肯定,通过优化应用程序来对数据库系统进行优化能获得更大地收益.对应用程序地优化通常可分为两个方面: 源代码地优化和SQL语句地优化.由于涉及到对程序逻辑地改变,源代码地优化在时间成本和风险上代价很高(尤其是对正在使用中地系统进行优化) .另一方面,源代码地优化对数据库系统性能地提升收效有限,因为应用程序对数据库地操作最终要表现为SQL语句对数据库地操作.对SQL语句进行优化有以下一些直接原因:1. SQL语句是对数据库(数据) 进行操作地惟一途径,应用程序地执行最终要归结为SQL语句地执行,SQL语句地效率对数据库系统地性能起到了决定性地作用.2. SQL语句消耗了70%~90%地数据库资源.3. SQL语句独立于程序设计逻辑,对SQL语句进行优化不会影响程序逻辑,相对于对程序源代码地优化,对SQL语句地优化在时间成本和风险上地代价都很低.4. SQL语句可以有不同地写法,不同地写法在性能上地差异可能很大.5. SQL语句易学,难精通.SQL语句地性能往往同实际运行系统地数据库结构、记录数量等有关,不存在普遍适用地规律来提升性能.二.优化数据库地思想:1、关键字段建立索引.2、使用存储过程,它使SQL变得更加灵活和高效.3、备份数据库和清除垃圾数据.4、SQL语句语法地优化.5、清理删除日志.三.SQL语句优化地原则:3.1 ORACLE地优化器优化器有时也被称为查询优化器,这是因为查询是影响数据库性能最主要地部分,不要以为只有SELECT语句是查询.实际上,带有任何WHERE条件地 DML(INSERT、UPDATE、DELETE)语句中都包含查询要求,在后面地文章中,当说到查询时,不一定只是指SELECT语句,也有可能指DML语句中地查询部分.优化器是所有关系数据库引擎中地最神秘、最富挑战性地部件之一,从性能地角度看也是最重要地部分,它性能地高低直接关系到数据库性能地好坏.我们知道,SQL语句同其它语言(如C语言)地语句不一样,它是非过程化(non-procedural)地语句,即当你要取数据时,不需要告诉数据库通过何种途径去取数据,如到底是通过索引取数据,还是应该将表中地每行数据都取出来,然后再通过一一比较地方式取数据(即全表扫描),这是由数据库地优化器决定地,这就是非过程化地含义,也就是说,如何取数据是由优化器决定,而不是应用开发者通过编程决定.在处理SQL地SELECT、UPDATE、 INSERT或DELETE语句时,Oracle 必须访问语句所涉及地数据,Oracle地优化器部分用来决定访问数据地有效路径,使得语句执行所需地I/O和处理时间最小.为了实现一个查询,内核必须为每个查询定制一个查询策略,或为取出符合条件地数据生成一个执行计划(execution plan).典型地,对于同一个查询,可能有几个执行计划都符合要求,都能得到符合条件地数据.例如,参与连接地表可以有多种不同地连接方法,这取决于连接条件和优化器采用地连接方法.为了在多个执行计划中选择最优地执行计划,优化器必须使用一些实际地指标来衡量每个执行计划使用地资源(I/0次数、 CPU等),这些资源也就是我们所说地代价(cost).如果一个执行计划使用地资源多,我们就说使用执行计划地代价大.以执行计划地代价大小作为衡量标准,优化器选择代价最小地执行计划作为真正执行该查询地执行计划,并抛弃其它地执行计划.在ORACLE地发展过程中,一共开发过2种类型地优化器:基于规则地优化器和基于代价地优化器.这2种优化器地不同之处关键在于:取得代价地方法与衡量代价地大小不同.现对每种优化器做一下简单地介绍:基于规则地优化器 -- Rule Based (Heuristic) Optimization(简称RBO):在ORACLE7之前,主要是使用基于规则地优化器.ORACLE在基于规则地优化器中采用启发式地方法(Heuristic Approach)或规则(Rules)来生成执行计划.例如,如果一个查询地where条件(where clause)包含一个谓词(predicate,其实就是一个判断条件,如”=”, “>”, ”<”等),而且该谓词上引用地列上有有效索引,那么优化器将使用索引访问这个表,而不考虑其它因素,如表中数据地多少、表中数据地易变性、索引地可选择性等.此时数据库中没有关于表与索引数据地统计性描述,如表中有多上行,每行地可选择性等.优化器也不考虑实例参数,如multi block i/o、可用排序内存地大小等,所以优化器有时就选择了次优化地计划作为真正地执行计划,导致系统性能不高.如,对于select * from emp where deptno = 10。
Oracle 9i 整体性能优化概述草稿之一:调整争用2.1 优化维护 42.2 诊断LATCH竞争 42.2.1 概念 42.2.2 是否存在latch争用 52.2.3 检查Latch是否主要竞争 52.2.4 DBA关注的latch内容 52.3 诊断FREE LIST竞争 62.3.1 概念 62.3.2 是否存在free list争用 62.3.3 确定free list 争用的段 72.3.4 优化free list争用 72.4 诊断LOCK竞争 82.4.1 概念 82.4.2 可能引起lock contention的原因 82.4.3 锁解决办法 92.4.4 死锁 92 调整争用争用:每当一个Oracle 进程试图访问一个Oracle结构,但由于该结构正由另一个进程结构使用而未能成功访问到它时,就发生对Oracle资源的争用。
常见的有latch、Free List 、lock争用。
主要维护的争用有:Latch(锁存器):可作为内存性能的指标,说明内存需要调整。
λFreeλ List:会导致繁忙表上的DML操作性能很差。
Lock:会遇到彻底的暂停,产生巨大的性能影响。
λ2.1优化维护维护时,主要通过检查,判断存在的latch和free list争用是否合理,不合理,则启动相应的优化工作。
而lock,在遇到问题的时候,可作为维护参考,平时不进行太多的维护(或从应用上考虑优化)。
(除了定期去$ORACLE_HOME/admin/$ORACLE_SID/udump查看死锁情况外)2.2诊断latch竞争2.2.1概念Latch是简单的、低层次的序列化技术,用以保护SGA中的共享数据结构,比如并发用户列表和buffer cache里的blocks信息。
一个服务器进程或后台进程在开始操作或寻找一个共享数据结构之前必须获得对应的latch,在完成以后释放latch。
不必对latch本身进行优化,如果latch存在竞争,表明SGA的一部分正在经历不正常的资源使用。
oraclesql效率优化第一掌避免对列的操作任何对列的操作都可能导致全表扫描,这里所谓的操作包括数据库函数、计算表达式等等,查询时要尽可能将操作移至等式的右边,甚至去掉函数。
例1:下列SQL条件语句中的列都建有恰当的索引,但30万行数据情况下执行速度却非常慢:select * from record where substrb(CardNo,1,4)='5378'(13秒)select * from record where amount/30< 1000(11秒)select * from record where to_char(ActionTime,'yyyymmdd')='19991201'(10秒)由于where子句中对列的任何操作结果都是在SQL运行时逐行计算得到的,因此它不得不进行表扫描,而没有使用该列上面的索引;如果这些结果在查询编译时就能得到,那么就可以被SQL 优化器优化,使用索引,避免表扫描,因此将SQL重写如下:select * from record where CardNo like '5378%'(< 1秒)select * from record where amount < 1000*30(< 1秒)select * from record where ActionTime= to_date ('19991201' ,'yyyymmdd')(< 1秒)差别是很明显的!第二掌避免不必要的类型转换需要注意的是,尽量避免潜在的数据类型转换。
如将字符型数据与数值型数据比较,ORACLE 会自动将字符型用to_number()函数进行转换,从而导致全表扫描。
例2:表tab1中的列col1是字符型(char),则以下语句存在类型转换:select col1,col2 from tab1 where col1>10,应该写为: select col1,col2 from tab1 where col1>'10'。
Oracle sql 性能优化调整一、前言Oracle SQL是众多企业使用较多的关系型数据库之一,因其高效稳定的性能,以及其提供的强大功能,逐渐成为了广大企业进行信息系统开发、实施和数据管理的首选。
然而,在大数据时代,普通的SQL查询已经不能支撑企业的业务需求,尤其是在数据量庞大的情况下,SQL查询的效率和性能将会受到严重的制约。
本文旨在介绍Oracle SQL的性能优化调整方法,以提高企业的数据处理的效率和性能。
二、排查问题SQL性能优化的第一步是排查问题,需要对慢查询做出明确的定位。
首先需要对SQL进行分析,寻找哪个部分影响了SQL性能,包括:1.查询语句的风格是否规范。
2.SQL语句是否能够使用索引优化查询。
3.数据库的表大小是否合适。
4.缓存的大小是否合适。
5.应用响应时间是否过长。
在分析完成后,才能通过性能优化来解决问题。
三、优化处理1.优化SQL查询语句SQL查询最主要的性能瓶颈是IO瓶颈。
当表的大小超过1万条时,应该对查询语句进行合理的检索,即避免全表扫描。
对大于1万条的表,应该创建索引,以便提高SQL的效率。
2.优化SQL查询计划查询计划优化是SQL调优的关键。
因为优化查询计划是确定整个查询需要的资源和查询的优化路径。
优化查询计划意味着查询应该从哪些索引开始,除了哪些索引以外,以及使用哪些操作符等等。
这些优化计划将明显影响查询性能。
3.优化表结构和索引优化表结构和索引也是常用的Oracle SQL优化方法。
表结构的优化主要是考虑数据库表的设计是否符合0NF、1NF、3NF等规范,是否有多列重复,是否存在无用列,是否存在大型BLOB/CLOB列等问题。
对于索引优化,可以使用多个单列索引代替多列复合索引以提高查询更新效率。
此外,还可以考虑使用等值连接或外连接改变查询本身,以便减少查询的数据量。
4.优化服务器硬件和操作系统软件硬件和操作系统软件的优化也很重要,因为数据库运行的效率和性能取决于服务器硬件和操作系统软件是否能够同时支持PMI和CPU等高性能功能。
Oracle数据库编程调优手册目录前言 (3)一、ORACLE数据加载优化(SQLLoader) (3)二、UPDATE优化 (4)1、对全表的Update操作 (4)2、有条件的Update操作 (5)3、多表连接Update操作 (7)4、两张表关联Update 的三种方式 (13)5、用视图代替对表的Update操作 (16)三、DELETE优化 (19)1、通过分拆表,避免DELETE操作 (19)2、通过中间表,用INSERT代替DELETE操作 (20)四、DBA级别优化提示 (21)五、其它优化提示 (24)前言本文根据最近一段时间,技术部与6.0项目组共同在做系统优化过程中,最常用的做法做一个总结。
目前只收录最近优化时的一些做法,供各项目组参考。
各个项目组在实际开发过程中,如有其它优化SQL的技巧,也请提交技术部,形成技术文档,供各项目组参考。
性能优化的几个原则:1.简化业务流程是提高性能的最可靠的方法------它可以给你的性能带来成倍的提升。
2.不要把希望寄托在DBA得身上,它不可能给你的性能带来成倍的提升。
3.尽量少用或者不用Update和Delete语句。
一、ORACLE数据加载优化(SQLLoader)用于外部数据加载的表应该尽量简单,尽量不要创建主键、字段的Default值以及其它约束。
这样可以充分利用Oracle数据库的直接路径加载(Direct=y)、并行加载(PARALLEL=true)提高数据加载性能。
[示例]用SQL Loader加载数据时使用直接路径加载(Direct Path Loads)参数Direct=y(或者DIRECT=true),可以使用下列方法:方法:sqlldr scott/tiger control=ldr.ctl direct=y二、UPDATE优化Oracle数据库中对大表(通常更新的记录数在1万条以上)进行Update操作的代价是非常高的,但是对表的INSERT、SELECT操作则相对较快。
Oracle 9i SQL优化快速手册
——蒋红腥
1概述
《Oracle 9i数据库SQL优化快速手册》并不全面讲解Oracle9i SQL优化技术,也不具体分析各种优化方法的原理,旨在通过简单明显有效的调整方法,帮助程序员或维护人员在开发、维护过程中,针对执行速度极慢的Oracle数据库开发操作,快速取得更快、更好的执行效果。
此时优化的结果并不是最优的,但我们的目标是能快速满足我们操作数据库的需求即可。
若想取得更多的SQL优化效果,请参考附件《Oracle 9i SQL语句调整》。
若要取得尽可能多的优化效果,则需要参考有关书籍,从Oracle服务器级优化、网络级优化、内存级优化以及优化器-SQL 优化等等入手进行综合优化。
下文中使用的方法,并不是完全规范的,合理的,但为求简单、方便快速的满足一般应用,一些设置采用了推荐设置、默认设置,直接按照说明操作,即可获得大多数的明显的优化结果。
2简易优化过程
根据执行计划,通过添加索引,使用CBO提示等优化方式,调整执行计划,达到满足需求。
前提条件:
已知那些执行语句慢。
2.1第一步:准备优化调试环境
⏹使用windows自带的command,打开2个窗口登陆到数据库服务器。
⏹设置查看“执行计划环境command窗口”。
在其中一个以$sqlplus “/as sysdba”方式登陆的
SQL提示符下执行如下命令:
SQL>set autotrace traceonly explain
SQL>
⏹设置“调试SQL语句窗口”。
在另一个command窗口使用执行该语句的用户登陆;执行该
语句,记录执行时间。
如:
$sqlplus perf/perf@omcdb
SQL> set timing on ---设置SQL执行时间记录返回--- 照着执行
SQL>alter session set optimizer_index_cost_adj=30; --- 照着执行
SQL>alter session set optimizer_index_caching=40; --- 照着执行
SQL>
执行返回的时间格式说明,如:
已用时间: 00: 00: 00.04 小时:分:秒.微秒
2.2第二步:查看SQL语句执行计划
在“执行计划环境command窗口”中,执行被调试的SQL语句,此时会输出该语句的执行计划,如下所示:(在from table的table表名前,添加该表的所属用户名)
如上图所示,兰色部分为我们输入的需要执行计划提示的命令和我们需要调试的SQL语句,红色部分为该语句在数据库中将使用的执行计划。
我们可以看到语句
TABLE ACCESS (FULL) OF 'TERRITORY'和TABLE ACCESS (FULL) OF 'C_PERF_MSC_TEMP'关键字FULL 表示,会对表c_unicom.territory和表c_perf.c_perf_msc_temp执行全表扫描,不会使用索引。
关键字Optimizer=CHOOSE,表示使用的是RBO优化器。
(Oracle两种优化器为RBO和CBO,数据库默认为CHOOSE,此时如果做了表分析,则强制使用CBO,不然默认为RBO)。
2.3第三步:创建索引,提高执行效率
执行如下命令,创建索引,并再次执行该SQL语句观察执行计划:
此时观察执行计划,表c_perf.c_perf_msc_temp已使用了刚创建的索引
IDX_C_PERF_MSC_TEMP,只有表c_unicom.territory还是全表扫描FULL。
由于c_unicom.territory是小表,所以我们可把他固定放入内存。
⏹此时在”调试SQL语句窗口”,执行该语句,记录执行时间。
执行时间是否满意?不满意继续往下优化,满意则优化结束。
2.4第四步:小表固定放入内存
我们执行select count(*) from c_unicom.territory ; 可发现,该表为小表。
(少于100行的,我们都可认为是小表),执行如下命令,即可把表c_unicom.territory放入内存。
SQL>alter table c_unicom.territory cache;
可使用sys用户执行,也可使用c_unicom用户登陆执行。
⏹此时在”调试SQL语句窗口”,执行该语句,记录执行时间。
执行时间是否满意?不满意继续往下优化,满意则优化结束。
2.5第五步:选择使用CBO或RBO
到当前为止,我们还是使用了数据库默认的CHOOSE,即为RBO,这是一种基于规则的优化器,执行效率并不高,我们可改用CBO进行优化。
使用CBO需要注意几件事情:
1)初始时,需要进行一次表分析。
2)修改表结构或创建、修改索引的时候,需要进行表分析。
3)表数据变化较大时,需要进行表分析。
同时,使用CBO,我们可以根据不同的需要选择不同的SQL提示,常用的有
/*+ first_rows */ 最快速度返回所选择的数据。
游标、GUI、WEB等推荐使用。
/*+ all_rows */ 以数据库自己计算成本,以最快的速度综合运算,统一返回结果。
PL/SQL里,或后台运算推荐使用。
/*+ rule */ 强制使用RBO。
/*+ table=xxx index=xxx */ 强制对某表使用某索引。
(一些提示可混合使用,由于提示是使用注释的方法,所以使用了错误的提示格式等,Oracle会当做注释不执行,不会对数据库查询操作有什么影响)
此时再执行该语句,查看执行时间,完全没优化时的执行时间与RBO优化时的执行时间比较,及与使用CBO优化后的执行时间比较。
就能发现执行速度已得到很大的改观。
此时在”调试SQL语句窗口”,执行该语句,记录执行时间。
执行时间是否满意?不满意请寻求数据库组协助或多方查资料进行优化,满意则优化结束。
3SQL_TRACE
查看生成的跟踪文件位置SQL:
select d.value||'/'||lower(rtrim(i.instance,
chr(0)))||'_ora_'||p.spid||'.trc' trace_file_name from(select p.spid from v$mystat m,v$session s,v$process p where m.statistic#=1and s.sid =m.sid and p.addr = s.paddr) p,
(select t.instance from v$thread t,v$parameter v where ='thread'and (v.value =0or t.thread#= to_number(v.value))) i,
(select value from v$parameter where name ='user_dump_dest') d
tkprof转换成别的格式的文件
$tkprof ora00001.trc out.txt。