




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































1
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:
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
Chapter 1. Introduction C HAPTE R 2
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:
DUAL to make the query work.
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.
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
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
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
The way in which Oracle accesses data is aptly called an access method. Oracle has a bunch of access methods in its arsenal: