SlideShare a Scribd company logo
Jonah H. Harris myYearbook.com Session #399 The Life of a Query (Oracle Edition)
Speaker Qualifications Currently the Sr. DBA at myYearbook.com Oracle DBA/developer starting with Oracle V7 Database Internals Software Architect for 3 years Hobby is Researching Oracle Internals Speaker for IOUG, VOUG, NYOUG, SEOUC Technical Reviewer for IOUG SELECT & several O'Reilly books on SQL Blog about Oracle technology http://www.oracle-internals.com/ Developed patches for open-source databases: PostgreSQL, InnoDB, SAP DB, Firebird
Disclaimer This is my hobby I’ve never been an Oracle insider The material in this presentation has been based on years of researching Oracle internals as well as analyzing network traffic and trace files. Do your own research! Use at your own risk!
What’s in this for me? Get a better idea of what's happening behind-the-scenes. Use this information to help troubleshoot issues Use this information to help optimize queries or the system itself.
Oracle Architecture
Oracle Architecture It has layers! Each layer depends on the layer beneath it Developed primarily in the C programming language with platform-specific optimizations in assembly language Controls all facets of query execution, utility processes, etc.
Oracle Kernel Layers
Connection Client requests a connection to a server SQL*Plus (OCI/UPI->NL [Network Layer]) Network Naming (NN layer) resolves the network address/port to connect to (TNSNAMES, etc.) and determines which Network Transport (NT layer) adapter to use (TCP/IP, SDB/IP, ...) Oracle Client software configures itself to perform communication using the Transparent Network Substrate (NS layer) protocol on the selected transport. The transport itself uses operating system dependent (OSD layer) code to handle portability differences between OSes like Windows, Linux, and various UNIX flavors. Client connects to the listener
Listener Communication The Listener accepts the connection request and validates that the service requested by the client is available and that the client has access to it (via host-based access control) The Listener tells the client to reconnect to a different port or resend the request. The Listener creates another Oracle process/thread and passes the connection information to it.
Handshaking The new process/thread accepts the client request for service and begins to perform handshaking Client and Server negotiate Additional Network Options (ANO) such as authentication, encryption, data integrity, etc. Client and server negotiate a common version of the protocol to use; if none are compatible, you'll generally see things like ORA-03134: Connections to this server version are no longer supported
Authentication Client sends User Name, Terminal Name, Machine Name, Program Name, ... Server responds with challenge/response Server sends client an encrypted key via AUTH_SESSKEY Client decrypts AUTH_SESSKEY using the user's password, and then uses the secret to encrypt and hash the user's password and sends the result back to the server as AUTH_PASSWORD Server confirms valid/invalid password and proceeds accordingly.
Session Creation After successful authentication, finish session creation and perform relevant actions Add session to global internal structures Execute AFTER LOGON triggers Once session creation is complete, the server process waits for input from the client.
Client Sends a Query User issues a query UPDATE mytable SET foo = 'baz' WHERE foo = 'bar'; Oracle Client packages up the query text into a specific Two-Task Interface (TTI) subpacket (OALL*) with relevant flags set Oracle Client encapsulates the subpacket into a TNS data packet Client sends packet to the server.
Server Receives the Query Server receives TNS data packet Server checks to see if data contains a subpacket Server parses the subpacket Server performs the Oracle Programmatic Interface (OPI) function actions based on the subpacket Parse Execute Fetch (about 170+ others)
Parse the Query Oracle performs a hash based on the query text and performs a lookup in the Library Cache If Oracle has already parsed the query and has a plan for it, re-use the plan (generally) If no plan is found, perform a "hard" parse Tokenize the query Parse the query using a recursive descent parser Started by Bob Miner and still contains a little of his code Build a parse tree representation of the statement Includes objects referenced in the query Perform some type checking and data type coercion Does the query make sense syntactically? Does the query make sense semantically?
Optimize the Query Goal is to determine how to best execute the query Query optimization is mathematical Discrete Math (Set Theory, Logic, Graph Theory, ...) Application of Relational Algebra Plan costs are based on weighted graph calculations Best plan is defined as having the lowest cost calculation Optimization Process is Query Rewrite Cost-based Query Optimization Execution Plan Generation
Rewrite the Query Transform to canonical form Perform some basic optimizations Constant folding Transitive Closure Determine whether the query (in whole or in part) can be optimized to use Materialized Views
Determine Access Paths Are there any indexes for columns specified in the predicate? If there are multiple indexes, build a plan for each If we are using an index, can we use that to optimize our join algorithm (hash, nested loop, external, ...)
Perform Cost-Based Optimization The goal is to determine Which access methods to use (Index, FTS, etc.) Optimal Join Order Uses a branch-and-bound algorithm to build plans by: Performing join permutation (Join Ordering) Determining which joins are not needed (Join Elimination) Applying partitioning rules (Partition Elimination/Pruning) Attempting to push down selection in joins (to reduce the number of rows at each step) Determining which indexes are available for use in the plan and whether that changes the join algorithm (hash, nested loop, ...) Calculate the I/O and CPU costs for each step of the plan Choose plan with the best overall graph weight.
Join Permutation Build graphs for joins in different orders Join R S = (R, S) = (S, R) Join R S T = ((R, S), T) = (R, (S, T)) Join is a binary Relational Algebra operation Follows mathematical rules for associativity and commutativity
Join Elimination Generally follows the process If a table is joined but none of its attributes (fields) are projected (in the select-list), consider it for join removal If the table being joined is redundant due to PK/FK integrity constraints, is can be considered for removal. If the table being joined is redundant due to unique constraints, it can be considered for removal. If all conditions are met, it can be removed from the query plan
Partition Elimination Based on the concept of constraint exclusion Drops (prunes) all partitions which could not possibly be used in our plan If you have range-based partitions for Q1, Q2, Q3, and Q4 and query data BETWEEN '01-JAN-09' AND '15-JAN-09', the optimizer knows that the data could not exist in partitions Q2, Q3, and Q4 by excluding them based on their constraint (Q2>='2009-03-31' and Q2 < '2009-07-01', ...)
Selection Pushdown To try reduce the cost of a join, see if the number of rows in R or S can be reduced prior to the join by pushing down parts of the predicate to those individual tables prior to the join. One area where this is beneficial is in nested loop joins, whose basic cost is determined by cardinality(R) * cardinality(S) Another area where this is beneficial is in hash joins, where the server can reduce the cardinality of one of the tables significantly.  This results in less CPU and memory required to build the hash table.
Build an Execution Plan Based on the best query plan, transform the plan into an execution plan for executing the query.
Execute the Plan For each node in the execution plan, perform the respective operation. Table Scan Index Scan Join Qualification ...
Execute the Plan (Index Node) Find all rows in the index on mytable.foo where foo = 'bar'. Open the index Perform a search on the B*Tree Once the index entry is found, locate the data in the heap (table data) using the ROWID.
Perform B*Tree Search FUNCTION btree_search (x, k)   i := 1   WHILE i <= n[x] AND k > key i [x]   DO i := i + 1   IF i <= n[x] AND k = key i [x] THEN   RETURN (x, i);   IF leaf[x] THEN   RETURN NIL   ELSE   kcbget(c i [x]);   RETURN btree_search(c i [x], k);   END IF;
Retrieving a Block (kcbg*()) Check the Buffer Cache If the block isn't in the buffer cache, read it from disk (sfrfb()-System File Read File Block) If the block is in the buffer cache, and no one has altered it without committing, use it. If the block is in the buffer cache, and someone has altered it without committing, build a before image of the block from UNDO and use it (kcbgtcr()-Kernel Cache Buffer GeT for Consistent Read).
Updating the Data Once the data has been found, update it Acquire a row-level lock by placing an entry in the interested transaction list (ITL).  If the row is already locked, wait (or don't wait depending on what the user requested) The server generates an UNDO/REDO record containing the change vector for the record (ktugur()-Kernel Transaction Undo Generate Undo and Redo) UNDO contains the column foo with value bar REDO contains the column foo with value baz The Oracle server returns a packet to the client regarding success/failure of the statement.
Committing the Data The client sends a commit message to the server, which the server processes as before.  Because it's a command, it does not have to go through query planning. Flush the REDO/UNDO data to disk up to the point of the commit Increment the SCN Fast Commit and Delayed Block Cleanout In Fast Commit mode, Oracle does not clean the ITL it used on the last transaction as a part of commit. The next request to read the block will check to see whether the transactions in the ITL are still in progress, if not, there's no reason to get a consistent read version of the block. If the next request is DML, it will itself perform ITL cleanup for the old transaction.
Fetching the Data The client sends the server a fetch request for N number of rows from a the cursor. The server marshalls the data to be sent over the network The server sends as many packets as are necessary to contain the data The client reads the data, unmarshalls it, performs any necessary encoding changes, and returns it to the application.
Questions?
Thank You Fill out evaluation The Life of a Query Session #399 Further Information [email_address] http://www.oracle-internals.com/

More Related Content

PPT
2 a stacks
PPT
2 b queues
PPTX
Run time administration
PPT
Chapter 7 Run Time Environment
DOCX
DocumentationofchangesondocumentparsingofBlueHOUND
PPSX
Dynamic memory allocation
PPT
Rendering XML Document
PPT
XPath - XML Path Language
2 a stacks
2 b queues
Run time administration
Chapter 7 Run Time Environment
DocumentationofchangesondocumentparsingofBlueHOUND
Dynamic memory allocation
Rendering XML Document
XPath - XML Path Language

What's hot (20)

PPT
PDF
Lesson 5 link list
PPT
Data structure
DOCX
Udemy talend notes
PDF
Introduction to Data Mining with R and Data Import/Export in R
PPS
Rpg Pointers And User Space
PDF
8 query
PDF
Run time storage
PPTX
Linear data structure concepts
ODP
Letting In the Light: Using Solr as an External Search Component
PPTX
Hadoop MapReduce framework - Module 3
PPTX
Searching Algorithms
PPT
Lec6 mod linked list
PDF
Unit ii data structure-converted
PDF
Map Reduce data types and formats
PDF
XPath - A practical guide
PDF
U nit i data structure-converted
PPTX
Heap Management
PDF
Hadoop map reduce concepts
PPTX
Latex for beginner
Lesson 5 link list
Data structure
Udemy talend notes
Introduction to Data Mining with R and Data Import/Export in R
Rpg Pointers And User Space
8 query
Run time storage
Linear data structure concepts
Letting In the Light: Using Solr as an External Search Component
Hadoop MapReduce framework - Module 3
Searching Algorithms
Lec6 mod linked list
Unit ii data structure-converted
Map Reduce data types and formats
XPath - A practical guide
U nit i data structure-converted
Heap Management
Hadoop map reduce concepts
Latex for beginner
Ad

Viewers also liked (20)

PPT
Basic oracle for developer&beginner
PPTX
Oracle SQL - Select Part -1 let's write some queries!
PPTX
Exadata Consolidation in Retail Oracle OpenWorld
PDF
Best practice bi_design_bestpracticesv_1_5
PPT
Sql oracle
PPTX
What's New with 12c ASM
PPT
Writing Basic SQL SELECT Statements
PPT
Introduction to-sql
DOC
Eigrp
PPTX
ฉันเหมือนใคร
PPSX
Devon house
PPT
Promo summer school for web
PPTX
New Zealand Franchising Confidence Index | April 2012
PDF
Arps public lecture brook
PPTX
2012 CTL presentation
DOCX
Puntuaciones provisionales
PDF
使用Prm恢复受损的oracle数据表几个例子
PDF
Oracle中比对2张表之间数据是否一致的几种方法
PPTX
Que hago y_como_vivo
Basic oracle for developer&beginner
Oracle SQL - Select Part -1 let's write some queries!
Exadata Consolidation in Retail Oracle OpenWorld
Best practice bi_design_bestpracticesv_1_5
Sql oracle
What's New with 12c ASM
Writing Basic SQL SELECT Statements
Introduction to-sql
Eigrp
ฉันเหมือนใคร
Devon house
Promo summer school for web
New Zealand Franchising Confidence Index | April 2012
Arps public lecture brook
2012 CTL presentation
Puntuaciones provisionales
使用Prm恢复受损的oracle数据表几个例子
Oracle中比对2张表之间数据是否一致的几种方法
Que hago y_como_vivo
Ad

Similar to The life of a query (oracle edition) (20)

PDF
Introduction to DataFusion An Embeddable Query Engine Written in Rust
PPT
Overview of query evaluation
PPT
Cost Based Optimizer - Part 1 of 2
PDF
Hyperspace: An Indexing Subsystem for Apache Spark
PDF
InfluxDB IOx Tech Talks: Query Engine Design and the Rust-Based DataFusion in...
PPT
Accelerated data access
PDF
Sql introduction
PPT
Optimizing Data Accessin Sq Lserver2005
PDF
PostgreSQL 9.4, 9.5 and Beyond @ COSCUP 2015 Taipei
PPTX
Database Performance Tuning
PPT
ch02-240507064009-ac337bf1 .ppt
PPT
QPOfutyfurfugfuyttruft7rfu65rfuyt PPT - Copy.ppt
PDF
Faceted Search with Lucene
PPTX
Hadoop and HBase experiences in perf log project
PDF
zenoh: zero overhead pub/sub store/query compute
PDF
Spark SQL In Depth www.syedacademy.com
PDF
Data-and-Compute-Intensive processing Use Case: Lucene Domain Index
PPTX
Day 1 - Technical Bootcamp azure synapse analytics
PPTX
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)
Introduction to DataFusion An Embeddable Query Engine Written in Rust
Overview of query evaluation
Cost Based Optimizer - Part 1 of 2
Hyperspace: An Indexing Subsystem for Apache Spark
InfluxDB IOx Tech Talks: Query Engine Design and the Rust-Based DataFusion in...
Accelerated data access
Sql introduction
Optimizing Data Accessin Sq Lserver2005
PostgreSQL 9.4, 9.5 and Beyond @ COSCUP 2015 Taipei
Database Performance Tuning
ch02-240507064009-ac337bf1 .ppt
QPOfutyfurfugfuyttruft7rfu65rfuyt PPT - Copy.ppt
Faceted Search with Lucene
Hadoop and HBase experiences in perf log project
zenoh: zero overhead pub/sub store/query compute
Spark SQL In Depth www.syedacademy.com
Data-and-Compute-Intensive processing Use Case: Lucene Domain Index
Day 1 - Technical Bootcamp azure synapse analytics
The Road to U-SQL: Experiences in Language Design (SQL Konferenz 2017 Keynote)

More from maclean liu (20)

PDF
Mysql企业备份发展及实践
PDF
Oracle専用データ復旧ソフトウェアprm dulユーザーズ・マニュアル
PDF
【诗檀软件 郭兆伟-技术报告】跨国企业级Oracle数据库备份策略
PDF
基于Oracle 12c data guard & far sync的低资源消耗两地三数据中心容灾方案
PDF
TomCat迁移步骤简述以及案例
PDF
PRM DUL Oracle Database Health Check
PDF
dbdao.com 汪伟华 my-sql-replication复制高可用配置方案
DOCX
Vbox virtual box在oracle linux 5 - shoug 梁洪响
PDF
【诗檀软件】Mysql高可用方案
PPTX
Shoug at apouc2015 4min pitch_biotwang_v2
PPTX
Apouc 4min pitch_biotwang_v2
PDF
使用Oracle osw analyzer工具分析oswbb日志,并绘制系统性能走势图1
PDF
诗檀软件 Oracle开发优化基础
PDF
Orclrecove 1 pd-prm-dul testing for oracle database recovery_20141030_biot_wang
PDF
诗檀软件 – Oracle数据库修复专家 oracle数据块损坏知识2014-10-24
PDF
追求Jdbc on oracle最佳性能?如何才好?
PDF
使用Virtual box在oracle linux 5.7上安装oracle database 11g release 2 rac的最佳实践
PDF
Prm dul is an oracle database recovery tool database
PDF
Oracle prm dul, jvm and os
PDF
Oracle dba必备技能 使用os watcher工具监控系统性能负载
Mysql企业备份发展及实践
Oracle専用データ復旧ソフトウェアprm dulユーザーズ・マニュアル
【诗檀软件 郭兆伟-技术报告】跨国企业级Oracle数据库备份策略
基于Oracle 12c data guard & far sync的低资源消耗两地三数据中心容灾方案
TomCat迁移步骤简述以及案例
PRM DUL Oracle Database Health Check
dbdao.com 汪伟华 my-sql-replication复制高可用配置方案
Vbox virtual box在oracle linux 5 - shoug 梁洪响
【诗檀软件】Mysql高可用方案
Shoug at apouc2015 4min pitch_biotwang_v2
Apouc 4min pitch_biotwang_v2
使用Oracle osw analyzer工具分析oswbb日志,并绘制系统性能走势图1
诗檀软件 Oracle开发优化基础
Orclrecove 1 pd-prm-dul testing for oracle database recovery_20141030_biot_wang
诗檀软件 – Oracle数据库修复专家 oracle数据块损坏知识2014-10-24
追求Jdbc on oracle最佳性能?如何才好?
使用Virtual box在oracle linux 5.7上安装oracle database 11g release 2 rac的最佳实践
Prm dul is an oracle database recovery tool database
Oracle prm dul, jvm and os
Oracle dba必备技能 使用os watcher工具监控系统性能负载

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Digital-Transformation-Roadmap-for-Companies.pptx

The life of a query (oracle edition)

  • 1. Jonah H. Harris myYearbook.com Session #399 The Life of a Query (Oracle Edition)
  • 2. Speaker Qualifications Currently the Sr. DBA at myYearbook.com Oracle DBA/developer starting with Oracle V7 Database Internals Software Architect for 3 years Hobby is Researching Oracle Internals Speaker for IOUG, VOUG, NYOUG, SEOUC Technical Reviewer for IOUG SELECT & several O'Reilly books on SQL Blog about Oracle technology http://www.oracle-internals.com/ Developed patches for open-source databases: PostgreSQL, InnoDB, SAP DB, Firebird
  • 3. Disclaimer This is my hobby I’ve never been an Oracle insider The material in this presentation has been based on years of researching Oracle internals as well as analyzing network traffic and trace files. Do your own research! Use at your own risk!
  • 4. What’s in this for me? Get a better idea of what's happening behind-the-scenes. Use this information to help troubleshoot issues Use this information to help optimize queries or the system itself.
  • 6. Oracle Architecture It has layers! Each layer depends on the layer beneath it Developed primarily in the C programming language with platform-specific optimizations in assembly language Controls all facets of query execution, utility processes, etc.
  • 8. Connection Client requests a connection to a server SQL*Plus (OCI/UPI->NL [Network Layer]) Network Naming (NN layer) resolves the network address/port to connect to (TNSNAMES, etc.) and determines which Network Transport (NT layer) adapter to use (TCP/IP, SDB/IP, ...) Oracle Client software configures itself to perform communication using the Transparent Network Substrate (NS layer) protocol on the selected transport. The transport itself uses operating system dependent (OSD layer) code to handle portability differences between OSes like Windows, Linux, and various UNIX flavors. Client connects to the listener
  • 9. Listener Communication The Listener accepts the connection request and validates that the service requested by the client is available and that the client has access to it (via host-based access control) The Listener tells the client to reconnect to a different port or resend the request. The Listener creates another Oracle process/thread and passes the connection information to it.
  • 10. Handshaking The new process/thread accepts the client request for service and begins to perform handshaking Client and Server negotiate Additional Network Options (ANO) such as authentication, encryption, data integrity, etc. Client and server negotiate a common version of the protocol to use; if none are compatible, you'll generally see things like ORA-03134: Connections to this server version are no longer supported
  • 11. Authentication Client sends User Name, Terminal Name, Machine Name, Program Name, ... Server responds with challenge/response Server sends client an encrypted key via AUTH_SESSKEY Client decrypts AUTH_SESSKEY using the user's password, and then uses the secret to encrypt and hash the user's password and sends the result back to the server as AUTH_PASSWORD Server confirms valid/invalid password and proceeds accordingly.
  • 12. Session Creation After successful authentication, finish session creation and perform relevant actions Add session to global internal structures Execute AFTER LOGON triggers Once session creation is complete, the server process waits for input from the client.
  • 13. Client Sends a Query User issues a query UPDATE mytable SET foo = 'baz' WHERE foo = 'bar'; Oracle Client packages up the query text into a specific Two-Task Interface (TTI) subpacket (OALL*) with relevant flags set Oracle Client encapsulates the subpacket into a TNS data packet Client sends packet to the server.
  • 14. Server Receives the Query Server receives TNS data packet Server checks to see if data contains a subpacket Server parses the subpacket Server performs the Oracle Programmatic Interface (OPI) function actions based on the subpacket Parse Execute Fetch (about 170+ others)
  • 15. Parse the Query Oracle performs a hash based on the query text and performs a lookup in the Library Cache If Oracle has already parsed the query and has a plan for it, re-use the plan (generally) If no plan is found, perform a &quot;hard&quot; parse Tokenize the query Parse the query using a recursive descent parser Started by Bob Miner and still contains a little of his code Build a parse tree representation of the statement Includes objects referenced in the query Perform some type checking and data type coercion Does the query make sense syntactically? Does the query make sense semantically?
  • 16. Optimize the Query Goal is to determine how to best execute the query Query optimization is mathematical Discrete Math (Set Theory, Logic, Graph Theory, ...) Application of Relational Algebra Plan costs are based on weighted graph calculations Best plan is defined as having the lowest cost calculation Optimization Process is Query Rewrite Cost-based Query Optimization Execution Plan Generation
  • 17. Rewrite the Query Transform to canonical form Perform some basic optimizations Constant folding Transitive Closure Determine whether the query (in whole or in part) can be optimized to use Materialized Views
  • 18. Determine Access Paths Are there any indexes for columns specified in the predicate? If there are multiple indexes, build a plan for each If we are using an index, can we use that to optimize our join algorithm (hash, nested loop, external, ...)
  • 19. Perform Cost-Based Optimization The goal is to determine Which access methods to use (Index, FTS, etc.) Optimal Join Order Uses a branch-and-bound algorithm to build plans by: Performing join permutation (Join Ordering) Determining which joins are not needed (Join Elimination) Applying partitioning rules (Partition Elimination/Pruning) Attempting to push down selection in joins (to reduce the number of rows at each step) Determining which indexes are available for use in the plan and whether that changes the join algorithm (hash, nested loop, ...) Calculate the I/O and CPU costs for each step of the plan Choose plan with the best overall graph weight.
  • 20. Join Permutation Build graphs for joins in different orders Join R S = (R, S) = (S, R) Join R S T = ((R, S), T) = (R, (S, T)) Join is a binary Relational Algebra operation Follows mathematical rules for associativity and commutativity
  • 21. Join Elimination Generally follows the process If a table is joined but none of its attributes (fields) are projected (in the select-list), consider it for join removal If the table being joined is redundant due to PK/FK integrity constraints, is can be considered for removal. If the table being joined is redundant due to unique constraints, it can be considered for removal. If all conditions are met, it can be removed from the query plan
  • 22. Partition Elimination Based on the concept of constraint exclusion Drops (prunes) all partitions which could not possibly be used in our plan If you have range-based partitions for Q1, Q2, Q3, and Q4 and query data BETWEEN '01-JAN-09' AND '15-JAN-09', the optimizer knows that the data could not exist in partitions Q2, Q3, and Q4 by excluding them based on their constraint (Q2>='2009-03-31' and Q2 < '2009-07-01', ...)
  • 23. Selection Pushdown To try reduce the cost of a join, see if the number of rows in R or S can be reduced prior to the join by pushing down parts of the predicate to those individual tables prior to the join. One area where this is beneficial is in nested loop joins, whose basic cost is determined by cardinality(R) * cardinality(S) Another area where this is beneficial is in hash joins, where the server can reduce the cardinality of one of the tables significantly. This results in less CPU and memory required to build the hash table.
  • 24. Build an Execution Plan Based on the best query plan, transform the plan into an execution plan for executing the query.
  • 25. Execute the Plan For each node in the execution plan, perform the respective operation. Table Scan Index Scan Join Qualification ...
  • 26. Execute the Plan (Index Node) Find all rows in the index on mytable.foo where foo = 'bar'. Open the index Perform a search on the B*Tree Once the index entry is found, locate the data in the heap (table data) using the ROWID.
  • 27. Perform B*Tree Search FUNCTION btree_search (x, k) i := 1 WHILE i <= n[x] AND k > key i [x] DO i := i + 1 IF i <= n[x] AND k = key i [x] THEN RETURN (x, i); IF leaf[x] THEN RETURN NIL ELSE kcbget(c i [x]); RETURN btree_search(c i [x], k); END IF;
  • 28. Retrieving a Block (kcbg*()) Check the Buffer Cache If the block isn't in the buffer cache, read it from disk (sfrfb()-System File Read File Block) If the block is in the buffer cache, and no one has altered it without committing, use it. If the block is in the buffer cache, and someone has altered it without committing, build a before image of the block from UNDO and use it (kcbgtcr()-Kernel Cache Buffer GeT for Consistent Read).
  • 29. Updating the Data Once the data has been found, update it Acquire a row-level lock by placing an entry in the interested transaction list (ITL). If the row is already locked, wait (or don't wait depending on what the user requested) The server generates an UNDO/REDO record containing the change vector for the record (ktugur()-Kernel Transaction Undo Generate Undo and Redo) UNDO contains the column foo with value bar REDO contains the column foo with value baz The Oracle server returns a packet to the client regarding success/failure of the statement.
  • 30. Committing the Data The client sends a commit message to the server, which the server processes as before. Because it's a command, it does not have to go through query planning. Flush the REDO/UNDO data to disk up to the point of the commit Increment the SCN Fast Commit and Delayed Block Cleanout In Fast Commit mode, Oracle does not clean the ITL it used on the last transaction as a part of commit. The next request to read the block will check to see whether the transactions in the ITL are still in progress, if not, there's no reason to get a consistent read version of the block. If the next request is DML, it will itself perform ITL cleanup for the old transaction.
  • 31. Fetching the Data The client sends the server a fetch request for N number of rows from a the cursor. The server marshalls the data to be sent over the network The server sends as many packets as are necessary to contain the data The client reads the data, unmarshalls it, performs any necessary encoding changes, and returns it to the application.
  • 33. Thank You Fill out evaluation The Life of a Query Session #399 Further Information [email_address] http://www.oracle-internals.com/

Editor's Notes

  • #34: Congratulations, you’re done! The best way to receive feedback is via the evaluation forms. Make sure you ask the attendees to complete the forms. Provide your name, session name and session # for them to fill out on the form. Attendees or those who read your session from the web/CD may want to contact you with further questions; optionally you can provide your contact information.