Docsity

Oracle SQL and PL/SQL Optimization for Developers: Best Practices and Techniques, Study Guides, Projects, Research of Programming Languages

Toggle sidebar
bg1
Ultimate study guide for Oracle SQL &
PL/SQL Optimization for Developers
Documentation latest update Chapter 1-16
1
CONTENTS
Introduction 1
1.1 Why This Guide? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 System and User Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 SQL 5
2.1 SQL Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1.1 Style Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1.1 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1.2 Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1.3 Semicolons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1.4 Asterisks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1.5 Thrift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1.6 Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1.7 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1.8 Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1.9 Respect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1.10 Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.1.1.11 Coding Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Oracle SQL and PL/SQL Optimization for Developers: Best Practices and Techniques and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity!

Ultimate study guide for Oracle SQL &

iii

  • Documentation latest update Chapter 1- PL/SQL Optimization for Developers
    • Introduction CONTENTS
    • 1.1 Why This Guide?
    • 1.2 System and User Requirements
    • 1.3 Notes
  • 2 SQL - 2.1 SQL Basics - 2.1.1 Style Guide - 2.1.1.1 Conventions - 2.1.1.2 Capitalization - 2.1.1.3 Semicolons - 2.1.1.4 Asterisks - 2.1.1.5 Thrift - 2.1.1.6 Aliases - 2.1.1.7 Comments - 2.1.1.8 Constraints - 2.1.1.9 Respect - 2.1.1.10 Formatting - 2.1.1.11 Coding Guidelines
    • 2.1.2 Query Processing Order
  • 2.2 Execution Plans
    • 2.2.1 Explain Plan
      • 2.2.1.1 Cardinality
      • 2.2.1.2 Access Methods
      • 2.2.1.3 Join Methods
      • 2.2.1.4 Join Types
      • 2.2.1.5 Join Orders
      • 2.2.1.6 Partition Pruning
      • 2.2.1.7 Parallel Execution
    • 2.2.2 Adaptive Query Optimization
  • 2.3 Indexes
    • 2.3.1 Developer or Admin?
    • 2.3.2 Access Paths and Indexes
    • 2.3.3 Statistics
    • 2.3.4 Predicates: Equality before Inequality
    • 2.3.5 Predicates: LHS vs RHS
    • 2.3.6 Function-Based Indexes and NULLs i
    • 2.3.7 Predicates: The WHERE Clause
    • 2.3.8 Full Table Scans
    • 2.3.9 Top-N Queries and Pagination
    • 2.3.10 Index-Organized Tables
    • 2.3.11 Beyond B-Trees: Bitmap Indexes
  • 2.4 Subqueries
    • 2.4.1 Scalar Subqueries
    • 2.4.2 Nested and Correlated Subqueries
    • 2.4.3 Subquery Unnesting
    • 2.4.4 Combined Nested Subqueries
    • 2.4.5 Subqueries with DI STI NCT
    • 2.4.6 Inline Views and Factored Subqueries
  • 2.5 Joins
    • 2.5.1 Nested Loops
    • 2.5.2 Hash Join
  • 4.1 Partitioning
  • 4.1.1 Partitioned Indexes
  • 4.1.2 Caveats
  • 4.1.3 Recommendations
  • 4.1.3.1 Single-Level Partitioning
  • 4.1.3.2 Composite Partitioning
  • 4.1.3.3 Prefixed vs Non-Prefixed Local Indexes
  • 4.1.3.4 Partitioned vs Non-Partitioned Global Indexes
  • 4.2 Compression
  • 4.2.1 Compression Methods
  • 4.2.1.1 BASI C and OL TP
  • 4.2.1.2 Hybrid Columnar Compression
  • 4.2.2 Performance Considerations
  • 4.2.2.1 Size Reduction
  • 4.2.2.2 CPU Overhead
  • 5 Glossary
  • Bibliography

C HAPTE R

1

Introduction

SQL is a peculiar language. It is one of only a handful of fourth-generation programming languages (4GL) in general use today, it seems deceptively simple, and more often than not you have many quite disparate options at your disposal to get the results you want, but only few of the alternatives perform well in production environments. The simplicity of the language veils decades of research and development, and although the syntax feels (almost) immediately familiar, perhaps even natural, it is a language that you have to wrap your head around. People coming from imperative languages often think in terms of consecutive instructions: relational databases operate on sets not single entities. How the SQL optimizer decides to execute the query may not coincide with what you think it will (or ought to) do. To the untrained eye a database developer can seem like a sorcerer, and it is often said that query tuning through interpreting execution plans is more art than science. This could not be further from the truth: a thorough understanding of the inner workings of any database is essential to squeeze out every last millisecond of performance. The problem is: the information is scattered all over the place, so finding exactly what you need when you need it can be a daunting task. pages, Steven Feuerstein’s PL/SQL Obsession, Oracle Developer by Adrian Billington, books, and a wealth of blogs (e.g. by Oracle ACEs). ‘So why this guide?’ we hear you ask. Two reasons really:

  1. It’s a long and at times arduous journey to master Oracle databases, and it’s one that never ends: Oracle continues to develop its flagship database product and it is doubtful that anyone knows everything about its internals. We hope that other developers will benefit from the experiences (and rare insights) chronicled here. These page are personal field notes too, so they evolve as we discover new avenues of investigation.

1 .1 Why This Guide?

While it’s easy to write bad code in any programming language, SQL — and to some extent PL/SQL too — is particularly susceptible. The reason is simple: because of its natural-looking syntax and the fact that a lot of technical ‘stuff’ goes on behind the scenes, some of which is not always obvious to all but seasoned developers and DBAs, people often forget that they are still dealing with a programming language and that SQL is not a silver bullet. Just because it looks easy does not mean that it is. We don’t want to step on anyone’s toes but frequently production SQL code (e.g. reports) is created not by developers but business users who often lack the know-how to create quality code. It’s not necessarily their jobs to come up with efficient queries but it is not uncommon to hear their gripes afterwards, once they discover that a report takes ‘too long’ because the database is ‘too slow’. The fact of the matter is that they have run into one of many traps, such as non-SARGable predicates, bad (or no) use of indexes, unnecessarily complicated (nested) subqueries that not even their creator can understand after a short lunch break but somehow magically deliver the correct, or rather desired, results. Other programming languages, especially the more common third-generation ones, do not have that problem: applications are mostly developed by professional developers who (should) know what they’re doing. There are many excellent references on the topic of SQL and PL/SQL optimization, most notably Oracle’s own extensive documentation, Tom Kyte’s Ask Tom Q&A website, entries by Burleson Consulting, Tim Hall’s Oracle Base 1

1.3 Notes

Chapter 1. Introduction C HAPTE R 2

S QL

Before Edgar F. Codd formulated the relational model [Codd69] [Codd70] for database management in 1969/ we had the Dark Ages of databases. Applications that required some form of stored data used a database unique to the application. Therefore, each development project had to reinvent the wheel again. In the 1970s Donald Chamberlin and Raymond Boyce developed the Structured English Query Language (SEQUEL) at IBM to work with data stored in System R, IBM’s database management system of the time. Because of trademark dispute they later changed the name to SQL, which stands for Structured Query Language. Because of that there are quite a few people who still pronounce SQL as ‘sequel’, whereas others say ‘S-Q-L’. If you search the internet you are likely to find an equal amount of proponents of either school of pronunciation. Honestly, who gives a hoot! While IBM were still tinkering with their prototype System R, Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories (SDL) in 1977. The first version (1978) was never released officially but the code name ‘Oracle’, taken from the CIA database project all three founders had worked on while at Ampex Corporation, remains to this day. Another year later they - now calling themselves Relational Software Inc. (RSI) - released Oracle V2, the first commercially available implementation of SQL. It was not until 1979 that IBM had a commercial database product; IBM DB2 came out in 1983. A year before the release of DB2, Oracle decided they had enough of RSI and they became known as Oracle Systems Corporation, named after their primary product. In 1995 Oracle Systems Corporation was rechristened Oracle Corporation. Oracle is still the leader when it comes to relational database management software, although the competition is getting stronger (especially on Windows platforms where Microsoft is in the lead with SQL Server) and more diverse: NoSQL (Cassandra, MongoDB, Neo4j,... ), NewSQL (Clustrix, H-Store), in-memory databases (IMDB) like SAP’s HANA, highly distributed systems for cloud computing like Apache Hadoop, and so on. A nice indicator of database popularity is DB engines. Their ranking does not compare to in-depth market research by Gartner and the likes but of course it’s free and not that far from the truth. Because of its ubiquity SQL became a standard of ANSI in 1986 and ISO one year later. Before you start shouting ‘Halleluja!’ from the rooftops, bear in mind that large parts of SQL are the same across the many database vendors but many are not. For example:

  • COAL ESCE(... ) is the ANSI SQL function that Oracle has implemented but most Oracle SQL developers use NVL (... ) instead; in SQL Server there is I SNUL L (... ) even though COAL ESCE(... ) works too.
  • SELECT 3.1415 AS pi gives you a table with one row and one column in SQL Server, but all Oracle gives you is an ORA- 00923 error because it did not find the FROMkeyword where it expected it. Oracle needs FROM 3

DUAL to make the query work.

  • Returning ten rows from a result set can be accomplished with SELECT TOP 10 in SQL Server. Oracle requires you apply a filter like WHERE ROWNUM <= 10. To get the actual top-10 rows (based on some ordering), Oracle requires a subquery with an ORDER BY clause, whereas SQL Server allows you to simply issue ORDER BY in the same query. As of 12c it is possible to use the row limiting clause though: FETCH FIRST 10 ROWS ONLY, which comes after the ORDER BY clause.
  • Window functions (i.e. aggregate functions in the SEL ECT clause that are accompanied by an OVER clause with PARTITION BY and/or ORDER BY) are another cause of portability headaches: the SQL :2011 (ISO/IEC 9075:2011) standard defines a window clause (WI NDOW) that enables easy reuse (through an alias) of the same window but as of this writing no major RDBMS vendor, save for the open-source PostgreSQL project, has implemented the window clause.
  • Hierarchical queries are done with the CONNECT BY clause in Oracle, whereas SQL Server requires recursive common table expressions. Only since 11g R2 does Oracle support recursive common table expressions.
  • There are three inequality comparison operators in Oracle: <>, which is the standard operator,! =, which most databases accept too, and ^=, which happens to be supported by IBM DB2 but not by Microsoft SQL Server, for instance. We could go on with our list but you probably get the message: even if you stick to the ANSI SQL standard as much as possible, you may not end up with portable code. Anyway, portability is by no means necessary: if you spend all your days working with Oracle databases, why care about NVL (... ) not being understood by SQL Server? Joe Celko’s books are great if you are interested in ANSI-compliant SQL tips and tricks. SQL Performance Explained by Markus Winand as well as his website Use the Index, Luke! come highly recommended for those who seek performance tweaking techniques for multiple database platforms. As we have said before, we shall assume that you have knowledge of and considerable experience with SQL and Oracle. If not, you can read on but we do not recommend it.

2.1 SQL Basics

The histories of relational database management systems and SQL are inextricably linked. Very few top-notch RDBMSs use a non-SQL programming language as the primary data manipulation language, although a couple of alternatives have been spotted in the wild. The implementations of SQL vary from vendor to vendor, but most share roughly the same core feature set. Relational database management systems, such as Oracle, are built on two pillars of mathematics: set theory and (first-order) predicate logic. In a database live objects and these objects have certain relations to one another. The objects have properties that are quantifiable and we can use these properties to compare objects. All data is represented as n -ary relations. Each relation consists of both a heading and a body. A heading is a set of attributes, and a body of an n -ary relation is a set of n -tuples with no specific order of its elements. A sets is an unordered collection of unique elements: the sets {a,b,c} and {b,c,a,c,c} are equivalent. Whereas mathematicians generally use two-valued logic to reason about about data, databases use three-valued logic: true, false, and unknown (NUL L ). Note that up to this point we have not talked about tables or columns at all. So far we have been looking at the high-level conceptual database model, which consists only of entities (e.g. Location, Department, Product, Supplier, Customer, Sales, ...) and relations. The conceptual data model describes what we want to model. When we move on to the logical data model, we need to add attributes and primary keys to our entities and relations. We are still independent of the particulars of a database management system but we have to define how we want to model our entities and relations. Common logical data models include the relational, network, hierarchical, flat, entity- 4 Chapter 2. SQL

2.1.1.3 S emicolons Sentences end with full stops, SQL statements with semicolons. Not all RDBMS clients require a semicolon to execute a single SQL statement, but you save yourself a lot of trouble if you just learn to finish each statement with a semicolon. 2.1.1.4 Asterisks Never use SEL ECT * in production code. At some point, someone will come and modify the table or view you’re querying from. If, on the one hand, the column you need in your application has been removed, you’ll end up with an application that displays an error. Best case: you’re alerted by an automated unit test that fails, so you branch off and fix the issue before merging it back into the main repository. Worst case: your client calls you and says that the application displays a runtime error, although the feedback is usually more along the lines of ‘It does not work’. If, on the other hand, several columns have been added you grab more than you actually need, thereby generating unnecessary overhead in the database and additional network traffic, which bring us to the next point: 2.1.1.5 Thrift Grab only the data you really need. If a table has a hundred columns and you only need three of them, do not select everything ‘just in case’. You don’t go to a car dealer and buy two cars just in case the first one breaks down, do you? Take what you need: no more, no less. The same goes for subqueries: if you reuse a subquery multiple times in a larger query, don’t copy-paste it. Instead use a subquery factor or common table expression (i.e. WI TH clause). It makes your code easier to read, you don’t have to update your subquery in several places if you ever need to make changes, and more importantly, Oracle can avoid doing the same thing multiple times. Oracle sometimes caches a subquery that appears repeatedly in your query, but there is no guarantee. Factor your code in general. Portions of stored procedures (or user-defined functions) that you use frequently should become their own stored procedures (or functions). Whenever a (small) portion of a procedure or function needs to be modified, factored code can minimize the recompilation. Just because you are working on a database does not mean you can ignore good code design altogether. When your result set needs to be sorted, use the ORDER BY clause, but do not force Oracle to sort data when you do not require it to be so. Oracle generally ignores irrelevant ORDER BY clauses in subqueries, but it’s sloppy to leave them in your code, and it can have an adverse effect on performance in case Oracle does not decide to ignore it. Moreover, views with ORDER BY clauses cause multiple sorts to be performed whenever someone selects data from the view but in a different order. Don’t go nuts with minimalism though. Never use ordinals (a.k.a. the column position) to sort data in production code. Specify the column names (or aliases) in the ORDER BY clause and you won’t have any problems when someone alters the code. The same applies to the column list in I NSERT statements; never ever assume that the order in which the columns are provided matches the table you are adding data to, even though the data types happen to match, and that the order of both the source and the target will always stay the same. 2.1.1.6 Aliases When you are dealing with more than one table (or view), use meaningful aliases. It reduces the amount of typing and it makes reading the query easier on the eyes. The adjective meaningful is there to remind you that x and y are probably not that revealing, and they do no nothing to aid the legibility of your code. Moreover, when defining 6 Chapter 2. SQL

column aliases, use AS. Its use is optional but sometimes it can be hard to figure out whether you missed a comma between two column names or whether the alias for one column is supposed to be the name of another. 2.1.1.7 C omments Add meaningful comments to your code: either use / *... */ for (multiline) comment blocks or - - for comments that do not extend to the next line. The key word here is meaningful. Trivial comments should not be added as they clutter your code and are immediately obvious to all but the brain-dead. Add meaningful comments to the data dictionary with the COMMENT statement. You can add comments to tables, (materialized) views, columns, operators and index types. Note: You can automatically generate documentation (HTML, PDF, CHM, ...) from the metadata in the data dictionary (SEL ECT * FROM dictionary) with for instance the option to ‘Generate DB Doc’ from the connections window/tab in Oracle SQL Developer, Quest Toad’s ‘HTML Schema Doc Generator’ in the Database > Report menu. Specialized tools to extract and display metadata from Oracle’s data dictionary exist too: for example, the xSQL’s excellent Database Documenter or the free SchemaSpy. 2.1.1.8 C onstraints We’ve said it before and we are going to say it again: be consistent. Especially when it comes to constraints that force user data into straitjackets. Constraints are imperative to databases. However, when you add NOT NULL constraints to columns that can have missing data (NUL L ), you force users to enter rubbish. As they will soon find out after receiving an error message: a blank space will often do the trick. Before you think about adding TRI M(... ) or REGEXP_L I KE(... ) checks to all data entered manually, think again: users will also quickly figure out that any random character (combination) will work and you cannot account for all possible situations. Prior to 11g you may have needed to convert NUL L to ' N/ A' or something similar to allow indexing on missing values, but that is not necessary any longer. The link shows a function-based B-tree index that includes columns with NUL L. By the way, bitmap indexes include rows with NUL L ; the default index is a B-tree index though. 2.1.1.9 Respect No, you don’t have to get all Aretha Franklin over your database, but you have to respect data types. Never rely on implicit data type conversions, and always convince yourself that the data type you think applies, really does apply. With a simple DESC tab_name you can remove all doubt. If you’re not convinced, please take a look at the following example, which shows you what you get when you sort numerical-looking data that is actually stored as a string. SQL Basics 7

2.1.1.11 Coding Guidelines We recommend that each organization define a programming standards document that clearly specifies how to write consistent and maintainable code. At the very least the coding standards should tell you how to name objects and format code. That includes, but is not limited to, standard prefixes for all database objects, notation standards (e.g. keywords in upper case, application-specific identifiers in lower case, underscores between words in identifiers), maximum line length, line break rules, indentation spaces for code blocks, and default headers. If your IDE supports IntelliSense or something similar, then Hungarian notation may be overkill, but for complex programs it may be beneficial to prefix the logical (Apps Hungarian) or the physical (Systems Hungarian) type to avoid collisions, although the former is often to be preferred to the latter. An example of a comprehensive set of coding guidelines for both SQL and PL/SQL is by Ian Hellström. The document’s source is in Markdown and publicly available in order to make it easy for you to adapt it to your (organization’s) needs. Steven Feuerstein’s and topcoder’s best practices and programming standards focus mainly on PL/SQL.

2.1.2 Query Processing Order

Important to understand before we discuss execution plans is how Oracle processes queries logically. Let’s look at the following query: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 SQL Basics 9 SEL ECT f. pr oduc t AS beer , p.product AS c r i s ps FROM fridge f CROSS J OI N pantry p WHERE f. pr oduc t = ' Beer ' AND f. t emper at ur e < 5 AND f. s i z e = '50 fl oz' AND p. pr oduc t = ' Cr i s ps ' AND p. s t yl e = 'Cream Cheese' AND p. s i z e = ' 250g' ORDER BY c r i s ps , beer ;

16 17 18 What does this query tell you other than that you’re a tad peckish, extremely thirsty, and that the fridge and pantry seem to use different systems of measurement? You may think that it reads the query in the way that we type it, but Oracle (and other RDBMSs too) does not read from top to bottom. It more or less reads our queries upside down. Not exactly, but we’ll see what it does in a minute. Oracle is a fancy machine that translates our SQL statements into something it can understand and execute. In essence, it’s a data robot that does exactly what we tell it to do. Now, suppose you have purchased a robot to help you around the house, and its first and foremost task is to assist you in quenching your thirst and sating your appetite. How would you tell it go fetch a beer and a packet of crisps? Well, you’d probably tell it to go to the fridge, look for beer, grab a bottle (50 fl oz) with a temperature below 5 degrees Celsius, then go to the pantry and look for a 250g packet of cream cheese crisps. Once it’s done, it should come back to you and place the items in front of you, sorted in the way you asked it to do. That’s right, you first tell it to go to the place where the fridge and the pantry are located (probably the kitchen: FROM), then to look for everything that matches your criteria (WHERE), and finally to return the items (SEL ECT) sorted in the order you specified (ORDER BY). That’s pretty much what Oracle does too. The order in which clauses are logically processed by Oracle is as follows: FROM -> CONNECT BY -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY. Of course, your query does not have to have every clause, and some cannot even be used with/without others (e.g. HAVI NG can only be used when you use GROUP BY). Fig. 1: Oracle’s query processing order, including optional clauses. The processing order is also the reason why the previous query worked like a charm and the following will result in an error: 1 2 3 (continues on next page) 2.1. (continued from previous page) 10 Chapter 2. SQL SEL ECT pr oduc t AS i t em , MI N ( t emper at ur e) AS mi n_t emper at ur e

Note: All characters affect the hash value, including spaces and line breaks as well as capitalization and of course comments. The last stage of the parser is to look for possible shortcuts by sifting through the shared pool , which is a “portion of the SGA that contains shared memory constructs such as shared SQL areas”, which hold the parse tree and execution plans for SQL statements; each unique statement has only one shared SQL area. We can distinguish two cases: hard and soft parses. 12 Chapter 2. SQL

  1. Soft parse (library cache hit): if the statement hashes to a value that is identical to one already present in the shared pool and the texts of the matching hash values are the same and its parsed representation can be shared, Oracle looks up the execution plan and executes the statement accordingly. Literals must also be the same for Oracle to be able to use the same shared SQL area. The exception is when CURSOR_SHARI NG is set to FORCE.
  2. Hard parse (library cache miss): if the statement has a hash value different from the ones that are available in the SGA or its parsed representation cannot be shared, Oracle hands the code over to the query optimizer. The query optimizer then has to build an executable version from scratch. Criteria for when a SQL statement or PL/SQL block can be shared are described in the Oracle Database Performance Tuning Guide , which can be found here. Basically, the statements’ hashes and texts, all referenced objects, any bind variables (name, data type, and length), and the session environments have to match. PL/SQL blocks that do not use bind variables are said to be not re-entrant, and they are always hard-parsed. To find out why statements cannot be shared you can use the view v$s ql _s har ed_c ur s or. Perhaps you noticed that we had sneaked in the column pl an_has h_val ue in the v$s ql query above. SQL statements with different hash values can obviously have the same plan, which means that their plan hash values are equal. Note: The plan hash value is merely an indicator of similar operations on database objects: filter and access predicates, which we shall discuss in more detail, are not part of the plan hash value calculation. For hard parses, the next station on the SQL compiler line is the query optimizer. The query optimizer, or just optimizer, is the “built-in database software that determines the most efficient way to execute a SQL statement”. The optimizer is also known as the cost-based optimizer (CBO), and it consists of the query transformer, the estimator, and the plan generator:
  • The query transformer “decides whether to rewrite a user query to generate a better query plan, merges views, and performs subquery unnesting”.
  • The estimator “uses statistics [from the data dictionary] to estimate the selectivity, cardinality, and cost of execution plans. The main goal of the estimator is to estimate the overall cost of an execution plan”.
  • The plan generator “tries out different possible plans for a given query so that the query optimizer can choose the plan with the lowest cost. It explores different plans for a query block by trying out different access paths , join methods, and join orders”. The optimizer also evaluates expressions, and it can convert correlated subqueries into equivalent join statements or vice versa. What the optimizer does, in a nutshell, is apply fancy heuristics to figure out the best way to execute your query: it calculates alternate routes from your screen through the database back to your screen, and picks the best one. By default Oracle tries to minimize the estimated resource usage (i.e. maximize the throughput), which depends on I/O, CPU, memory, the number of rows returned, and the size of the initial data sets. The objective of the optimization can be altered by changing the value of OPTI MI ZER_MODE parameter. If you can recall our example of the robot, the beer, and the packet of crisps, you may remember that the robot had to check both the pantry and the fridge. If we equip our robot with Oracle’s query optimizer, the robot will not simply walk to the kitchen, find the items by searching for them, and then return with our refreshments, but try to do it as efficiently as possible. It will modify our query without altering the query’s function (i.e. fetch you some booze and a few nibbly bits), and explore its options when it comes to retrieving the items from the kitchen. For instance, if we happen to have a smart fridge with a display on the door that shows where all bottles are located, including the contents, temperature, and size of each bottle, the robot does not have to rummage through decaying fruit and vegetables at the bottom in the hope that a bottle is located somewhere underneath the 2.2. Execution Plans 13

4 5 6 7 8 9 10 11 12 What you end up with is a tabular representation of the execution plan; the table is a top-down, left-to-right traversal of the execution tree. Each operation is printed on a single line, together with more detailed information about that operation. The sequence and types of operations depend on what the query optimizer considers to be the best plan, that is the one with the lowest cost. The components that are factored into the cost of a query are • Cardinality

  • Access methods

2.2.1.3 Join Methods

2.2.1.4 Join Types

2.2.1.5 Join Orders

2.2.1.6 Partition Pruning

2.2.1.7 Parallel Execution

We shall now discuss each of these components separately. 2.2.1.1 C ardinality No, cardinality has nothing to do with the clergy. What cardinality refers to is the uniqueness (or lack thereof) of data in a particular column of a database table. It is a measure of the number of distinct elements in a column. A low cardinality implies that a column has very few distinct values, and is thus not very selective. In the context of execution plans, the cardinality shows the number of rows estimated to come out of each operation. The cardinality is computed from table and column statistics, if available. 2 If not, Oracle has to estimate the cardinality. For instance, suppose you have an equality predicate in a single-table query, for which there is no histogram (i.e. no statistics). The query optimizer will then assume a uniform distribution, so that the cardinality of each operation in the execution plan is calculated by dividing the total number of rows by the number of distinct values after the equality predicate has been applied. The number of rounded up and shown in the column CARDI NAL I TY. What can (negatively) impact the accuracy of the estimate and therefore the quality of the execution plan are i) data skew, ii) multiple single-column predicates on a single table, iii) function-wrapped columns in WHERE clause predicates, and iv) complex expressions. Interestingly, you can see runtime cardinality information by using the GATHER_PL AN_STATI STI CS hint in your query, after which you have to execute SEL ECT * FROM table(DBMS_XPLAN. DISPLAY_CURSOR(FORMAT=>'ALLSTATS LAST')). The result shows you the estimated number of rows (E- Rows ) and the actual number of rows (A- Rows ), which can of course be quite different because of data skew. Don’t use this hint in a production environment as each query incurs some overhead. 2 By default, Oracle determines all columns that need histograms based on usage statistics and the presence of data skew. You can manually create histograms with the DBMS_STATS. GATHER_TABL E_STATS procedure. 2.2. Execution Plans 15

2.2.1.2 Access Methods

The way in which Oracle accesses data is aptly called an access method. Oracle has a bunch of access methods in its arsenal:

  • A full table scan reads all rows from a heap-organized table and filters out the ones that do not match the WHERE clause predicates. Each formatted block of data under the high water mark (HWM) is read only once and the blocks are read in sequence. A multi-block read can be performed to speed up the table scan: several adjacent blocks are combined into a single I/O call. The DB_FI L E_MUL TI BL OCK_READ_COUNT parameter in the init.ora file defines the number of blocks that can be lumped into one multi-block read. A full table scan is typically employed if - no index exists; - the index cannot be used because the query predicate has a function applied to an indexed column (in a non-function-based index); - the optimizer decides against an index skip scan because the query predicate does not include the leading edge of a (B-tree) index; - SELECT COUNT(*) is issued and the index contains nulls; - the table statistics are stale and the table has grown considerably since the statistics were last computed; - the query is not selective, so that a large portion of the rows must be accessed; - the cost of a full table scan is the lowest because the table is small, in particular the number of formatted blocks under the high water mark is smaller than DB_FI L E_MUL TI BL OCK_READ_COUNT; - the table has a high degree of parallelism, which makes the optimizer biased towards full table scans; – the query uses the FUL L hint.
  • In a table access by ROWID, Oracle looks up each selected row of a heap-organized table based on its ROWID, which specifies the data file, the data block within that file, and the location of the row within that block. The ROWID is obtained either from the WHERE clause predicate or through an index scan. If the execution plan shows a line TABLE ACCESS BY INDEX ROWID BATCHED it means that Oracle retrieves a bunch of ROWIDs from the index and then tries to access rows in block order to reduce the number of times each block needs to be accessed.
  • The SAMPL E and SAMPL E_BL OCK clauses (with a sample percentage below 100%) cause a sample table scan, which fetches a random sample of data from a heap-organized table. Note that block sampling is only possible during full table scans or index fast scans.
  • For an index unique scan only one row of a (B-tree) index or index-organized table will be returned because of an equality predicate on a unique index or a primary key constraint; the database stops looking for more rows once it has found its match because there cannot be any more matches thanks to the UNI QUE constraint. Hence, all columns of a unique index must be referenced with equality operators. Please observe the index itself must be unique: creating an index on a column and subsequently adding a UNI QUE or PRIMARY KEY constraint to the table is not enough, as the index is not aware of uniqueness; you are liable to end up with an index range scan.
  • An index range scan scans values in order. By default, Oracle stores and scans indexes and index-organized tables in ascending order. Oracle accesses adjacent index entries and uses the ROWID values to retrieve the rows in ascending order. If multiple index entries happen to have the same keys, Oracle returns the entries in ascending order by ROWID. 16 Chapter 2. SQL