Structured Query Language - Print Version
Structured Query Language - Print Version
Structured Query Language/Print version - Wikibooks, open books for an open world
Introduction Contents
1 Introduction 2 It's a Translation and a Guide 3 What this Wikibook is not 4 How to proceed 5 Conventions 5.1 Historical Context 5.2 What makes up a Database Management System? 5.3 Classification of DBMS Design 6 The Theory 7 The Data Model 8 Some more Basics 9 History 10 Characteristics 11 Fundamentals 12 Turing completeness 13 Benefit of Standardization 14 Limits 15 The Standardization Process 16 Verification of Conformance to the Standard 17 Implementations 18 Standard Track 19 More than a Spreadsheet 20 Conceive the Structure 21 Fasten Decisions 22 The Result 23 Back to Start 24 Store new Data with INSERT Command 25 Retrieve Data with SELECT Command 26 Modify Data with UPDATE Command 27 Remove data with DELETE Command 28 Summary 29 person 30 contact 31 hobby 32 person_hobby 33 Visualisation of the Structure 34 person 35 contact 36 hobby 37 person_hobby 38 Grow up 39 Projection 39.1 UNIQUE 39.2 Aliases for Columnnames 39.3 Functions 39.4 SELECT within SELECT 40 Table names 41 Restriction 41.1 Comparisions
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 1/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
41.2 Boolean logic 42 Grouping 43 Sorting 44 Combine the Language Elements 45 Further Information 46 Exercises 47 AUTOCOMMIT 48 COMMIT 49 ROLLBACK 50 Exercises 51 The Idea 52 The Basic Syntax 53 Four Join Types 53.1 Inner Join 53.2 Left (outer) Join 53.3 Right (outer) Join 53.4 Full (outer) Join 54 Carthesian Product 55 The n:m Situation 56 More Details 57 Exercises 58 Constitute Groups 58.1 Grouping over multiple columns 59 Inspect Groups 60 Focus on Desired Groups 61 The Overall Picture 62 Exercises 63 Extention of Boolean Logic 64 Retrieve the NULL Value 65 Some Examples 66 Coalesce() and similar Functions 67 Exercises 68 Aggregate functions 68.1 NULL value 68.2 ALL vs. DISTINCT 68.3 Hint 69 Scalar functions 70 Exercises 71 UNION 72 INTERSECT 73 EXCEPT 74 Order By 75 Group By 76 Exercises 77 Two Examples 78 Syntax 79 Typical Use Cases 80 Exercises 81 Classification 82 Scalar Value Subquery 83 Row Subquery 84 Table Subquery 85 Another Example 86 Exercises 87 Create a View 88 Examples and Explanations 88.1 Example 1: Hid Columns 88.2 Example 2: Rename Columns 88.3 Example 3: Apply WHERE Condition 88.4 Example 4: Use Functions 88.5 Example 5: Join 89 Some more Hints 90 Write Access via Views 91 Clean up the Example Database
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 2/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
92 Exercises 93 Evaluate Values at Runtime 94 Evaluate Rows at Runtime 95 Clean up Your Database 96 Exercises 97 Evaluate Values at Runtime 98 Subqueries in WHERE Clause 99 Exercises 100 Description 101 Example 102 Use Case 103 Extentions 104 Caveat 105 Exercises 106 Example 107 Exercise 108 Example 109 An Analogy 110 Exercises 111 General Description 112 Column Definition 112.1 Data Type 112.2 Default Value 112.3 Identity Specification 112.4 Column Constraint 113 Table Constraint 113.1 Primary Key, UNIQUE and Foreign Key 113.2 NOT NULL and Simple Column Checks 113.3 General Column Checks 114 Column Constraints vs. Table Constraints 115 Clean Up 116 Exercises 117 Classic Track 118 Structured Query Language (SQL) 119 Relationships 120 SQL data types 121 SELECT query 121.1 First query 121.2 WHERE clause 121.2.1 Predicate 121.2.2 Operators 121.2.3 LIKE 121.2.4 BETWEEN and IN 121.2.5 EXISTS 121.2.6 IS NULL 121.3 FROM clause 121.3.1 FULL OUTER JOIN 121.3.2 RIGHT OUTER JOIN 121.3.3 LEFT OUTER JOIN 121.3.4 INNER JOIN 121.3.5 Alias 121.4 SELECT clause 121.5 ORDER BY clause 121.6 GROUP BY clause 121.7 HAVING clause 121.8 FETCH FIRST clause 122 SQL Functions 123 INSERT statement 124 UPDATE statement 125 DELETE statement 126 CREATE statement 127 ALTER statement 127.1 ADD CONSTRAINT clause 127.2 DROP CONSTRAINT clause
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 3/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
127.3 ADD COLUMN clause 127.4 DROP COLUMN clause 128 DROP statement 129 GRANT statement 129.1 Sending privileges on columns 130 REVOKE statement 131 Result set column 132 Avoid the value expressions 133 Index 134 Appendices 135 SQLCA 136 SQLCODE 136.1 Zero (Successful) 136.2 Negative (through -251) 136.3 Negative (-300 to -499) 136.4 Negative (-500 to -697) 136.5 Negative (-713 to -991) 136.6 Negative (Smaller than -991) 136.7 Positive Values (Warnings) 136.8 Letter SQL Codes 137 External resources 138 License 138.1 GNU Free Documentation License 139 0. PREAMBLE 140 1. APPLICABILITY AND DEFINITIONS 141 2. VERBATIM COPYING 142 3. COPYING IN QUANTITY 143 4. MODIFICATIONS 144 5. COMBINING DOCUMENTS 145 6. COLLECTIONS OF DOCUMENTS 146 7. AGGREGATION WITH INDEPENDENT WORKS 147 8. TRANSLATION 148 9. TERMINATION 149 10. FUTURE REVISIONS OF THIS LICENSE 150 11. RELICENSING 151 How to use this License for your documents
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
4/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
How to proceed
For everyone new to SQL, it will be necessary to study the chapters and pages from beginning to end. For persons who have some experience with SQL or who are interested in a specific aspect, it is possible to navigate directly to any page. Knowledge about any other computer language is not necessary, but it will be helpful. This wikibook consists of descriptions, definitions, and examples. It should be read with care. Furthermore, it is absolutely necessary to personally do some experiments with data and data structures. Hence, access to a concrete database system where read-only and read-write tests can be done is necessary. For those tests, our example database or individually defined tables and data can be used.
Conventions
The elements of the language SQL are case-insensitive, e.g.: it makes no difference whether you write SELECT ..., Select ..., select ... or any combination of upper and lower case characters like SeLecT .... For readability reasons, this wikibook uses the convention that all language keywords are written in upper case letters and all names of user objects e.g. table and column names, are written in lower case letters. We will write short SQL commands within one row.
S E L E C Ts t r e e tF R O Ma d d r e s sW H E R Ec i t y=' D u c k b u r g ' ;
Advice: Storing and retrieving text data is case sensitive! If you store a cityname 'Duckburg' you cannot retrieve it as 'duckburg'.
Historical Context
One of the original scopes of computer applications was storing large amounts of data on mass storage devices and retrieving them at a later point in time. Over time user requirements increased to include not only sequential access but also random access to data records, concurrent access by parallel (writing) processes, recovery after hardware and software failures, high performance, scalability, etc. In the 1970s and 1980s, the science and computer industries developed techniques to fulfill those requests.
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
navigate directly to data stored in lower levels. You must first navigate over the given hierarchy before reaching that data. The best-known hierarchical DBMS is IMS from IBM. Network DBMS: The network model designs data structures as a complex network with links from one or more parent nodes to one or more child nodes. Even cycles are possible. There is no need for a single root node. In general the terms parent node and child node lose their hierarchical meaning and may be referred as link source and link destination. Since those links are realized as physical links within the database, applications which follow the links show good performance. Relational DBMS: The relational model designs data structures as relations (tables) with attributes (columns) and the relationship between those relations. Definitions in this model are expressed in a pure declarative way not predetermining any implementation issues like links from one relation to another or a certain sequence of rows in the database. Relationships are based purely upon content. At runtime all linking and joining is done by evaluating the actual data values, e.g.: . . .W H E R Ee m p l o y e e . d e p a r t m e n t _ i d=d e p a r t m e n t . i d. . . . The consequence is that - with the exception of explicit foreign keys there is no meaning of a parent/child or owner/member denotation. Relationships in this model do not have any direction. The relational model and SQL are based on the mathematical theory of relational algebra. During the 1980s and 1990s proprietary and open source DBMS's based on the relational design paradigm established themselves as market leaders. Object oriented DBMS: Nowadays most applications are written in an object oriented programming language (OOP). If, in such cases, the underlaying DBMS belongs to the class of relational DBMS, the so called object-relational impedance mismatch arises. That is to say, in contrast to the application language pure relational DBMS (prDBMS) does not support central concepts of OOP: Type system: OOPs do not only know primitive data types. As a central concept of their language they offer the facility to define classes with complex internal structures. The classes are built on primitive types, system classes, references to other or the same class. prDBMS knows only predefined types. Secondary prDBMS insists in first normal form, which means that attributes must be scalar. In OOPs they may be sets, lists or arrays of the desired type. Inheritance : Classes of OOPs may inherit attributes and methods from their superclass. This concept is not known to prDBMS. Polymorphism: The runtime system can decide via late binding which one of a group of methods with the same name and parameter types will be called. This concept is not known by prDBMS. Encapsulation: Data and access methods to data are stored within the same class. It is not possible to access the data directly - the only way is using the access methods of the class. This concept is not known to prDBMS. Object oriented DBMS are designed to overcome the gap between prDBMS and OOP. At their peak, they reached a weak market position in the mid and late 1990s. Afterwards some of their concepts were incorporated into the SQL standard as well as rDBMS implementations. NoSQL: The term NoSQL stands for the emerging group of DBMS which differs from others in central concepts: They do not necessarily support all aspects of the ACID paradigm. The data must not necessarily be structured according to any schema. Their goal is support for fault-tolerant, distributed data with very huge volume. Implementations differ widely in storing techniques: you can see key-value stores, document oriented databases, graph oriented databases and more. They do not offer an SQL interface. In 2011 an initiative started to define an alternative language: Unstructured Query Language as part of SQLite.
The Theory
A relational DBMS is an implementation of data stores according to the design rules of the relational model. This approach allows operations on the data according to the relational algebra like projections, selections, joins, set operations (union, difference, intersection, ...) and more. Together with Boolean algebra (and, or, not, exists, ...) and other mathematical concepts, relational algebra builds up a complete mathematical system with basic operations, complex operations and transformation rules between the operations. Neither a DBA nor an application programmer needs to know the relational algebra. But it is helpfull to know that your rDBMS is based on this mathematical foundation - and that it has the freedom to transform queries into several forms.
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Operations within databases must have the ability to act not only on single rows, but also on sets of rows. Relational algebra offers this possibility. Therefore languages based on relational algebra, e.g.: SQL, offer a powerful syntax to manipulate a great bunch of data within one single command. As operations within relational algebra may be replaced by different but logically equivalent operations, a language based on relational algebra should not predetermine how its syntax is mapped to operations (the execution plan). The language should describe what should be done and not how to do it. Note: This choice of operations does not concern the use or neglect of indices. As described before the relational model tends to break up objects into sub-objects. In this and in other cases it is often necessary to collect associated information from a bunch of tables into one information unit. How is this possible without links between participating tables and rows? The answer is: All joining is done based on the values which are actually stored in the attributes. The rDBMS must make its own decisions about how to reach all concerned rows: whether to read all potentially affected rows and ignore those which are irrelevant (full table scan) or, to use some kind of index and read only those which match the criteria. This value-based approach allows even the use of operators other than the equal-operator, e.g.:
S E L E C T*F R O Mg i f tJ O I Nb o xO Ng i f t . e x t e n t<b o x . e x t e n t ;
This command will join all "gift" records to all "box" records with a larger "extent" (whatever "extent" means).
History
As outlined above, rDBMS acts on the data with operations of relational algebra like projections, selections, joins, set operations (union, except and intersect) and more. The operations of relational algebra are denoted in a mathematical language which is highly formal and hard to understand for end users and - possibly also for many software engineers. Therefore rDBMS offers a layer above relational algebra, which is easy to understand but nevertheless can be mapped to the underlying relational operations. Since the 1970s we have seen some languages doing this job, one of them was SQL - another example was QUEL. In the early 1980s (after a rename from its original name SEQUEL due to trademark problems) SQL achieved market dominance. And in 1986 SQL was standardized for the first time. The current version is SQL 2011.
Characteristics
The tokens and syntax of SQL are oriented on English common speech to keep the access barrier as small as possible. An SQL command like U P D A T E e m p l o y e eS E Ts a l a r y=2 0 0 0W H E R Ei d=5 1 1 ;is not far away from the sentence "Change employee's salary to 2000 for the employee with id 511." The next simplification is that all key words of SQL can be expressed in any combination of upper and lower case characters. It makes no difference whether U P D A T E ,u p d a t e ,U p d a t e ,U p D a t eor any other combination of upper and lower case characters is written. The keywords are case insensitive . Next SQL is a descriptive language, not a procedural one. It does not pre-decide all aspects of the relational operations (which operation, their order, ...) which are generated from the given SQL statement. The rDBMS has the freedom to generate more than one execution plan from a statement. It compares the genereated execution plans with each other and runs this one, it thinks is best in the given situation. Additionally the end user is freed from all the gory details of data access, e.g.: Which one of a set of WHERE criteria should be evaluated first if they are combined with AND? Despite those simplifications SQL is very powerful. Especially since it allows the manipulation of a set of data records with one single statement. U P D A T E e m p l o y e eS E Ts a l a r y=s a l a r y*1 . 1W H E R Es a l a r y<2 0 0 0 ;will affect all employee records with an actual salary smaller than 2000. Potentially, there may be thousands of those records, only a few or even zero. It may also be noted that the operation is not a fix manipulation. The wording S E Ts a l a r y= s a l a r y*1 . 1leads to an increase of the salaries by 10%, which may be 120 for one employee and 500 for another one. The designer of SQL tried to define the language elements orthogonally to each other. Among other things this refers to the fact that any language element may be used in all positions of a statement where the result of that element may be used directly. E.g.: If you have a function power() which takes two numbers and returns another number, you can use this function in all positions where numbers are allowed. The following statements are syntactically correct (if you have defined the function power() ) - and lead to the same resulting rows.
Another example of orthogonality is the use of subqueries within UPDATE, INSERT, DELETE or inside another SELECT statement. However, SQL is not free of redundancy. Often there are several possible formulations to express the same situation.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
7/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
This is a very simple example. In complex statements there may be the choice between joins, subqueries and the exists predicate.
Fundamentals
Core SQL consists of statements. Statements consist of key words, operators, values, names of system- and user-objects or functions. The statements are concluded by a semicolon. In the statement S E L E C Ts a l a r yF R O Me m p l o y e eW H E R Ei d<1 0 0 ;the tokens SELECT, FROM and WHERE are key words. salary, employee and id are object names, the "<" sign is an operator and "100" is a value. The SQL standard arranges statements into 9 groups: "The main classes of SQL-statements are: SQL-schema statements; these may have a persistent effect on the set of schemas. SQL-data statements; some of these, the SQL-data change statements, may have a persistent effect on SQL data. SQL-transaction statements; except for the <commit statement>, these, and the following classes, have no effects that persist when an SQL-session is terminated. SQL-control statements. SQL-connection statements. SQL-session statements. SQL-diagnostics statements. SQL-dynamic statements. SQL embedded exception declaration." This detailed grouping is unusual in common speech. Usually it is distinguish between three groups: Data Definition Language (DDL): Managing the structure of database objects (create/drop tables, views, columns, ...) Data Manipulation Language (DML): Managing and retrieval of data with the statements INSERT, UPDATE, DELETE, SELECT, COMMIT and ROLLBACK. Data Control Language (DCL): Managing access rights. Hint: In some publications the SELECT statement is said to build its own group Data Query Language. This group has no other statements than SELECT.
Turing completeness
Core SQL as described above is not Turing complete. It misses conditional branches, variables, subroutines. But the standard as well as most implementations offers an extension to fulfill the demand for Turing completeness. In 'Part 4: Persistent Stored Modules (SQL/PSM)' of the standard there are definitions for IF-, CASE-, LOOP-, assignment- and other statements. The existing implementations of this part have different names, different syntax and also a different scope of operation: PL/SQL in Oracle, SQL/PL in DB2, Transact-SQL or T-SQL in SQL Server and Sybase, PL/pgSQL in Postgres and simply 'stored procedures' in MySQL.
Benefit of Standardization
Like most other standards the main purpose of SQL is portability. Usually software designers and application developers structure and solve problems in layers. Every abstraction level is realized in its own component or sub-component: presentation to end user, business logic, data access, data storage, net and operation system demands are typical representatives of such components. They are organized as a stack and every layer offers an interface to the upper layers to use its functionality. If one of those components is realized by two different providers and both offer the same interface (as an API, Web-Service, language specification, ...) it is possible to exchange them without changing the layers which are based on them. In essence the software industry needs stable interfaces at the top of important layers to avoid dependence on a single provider. SQL acts as such an interface to relational database systems. If an application uses only those SQL commands which are defined within standard SQL, it should be possible to exchange the underlaying rDBMS with a different one without changing the source code of the application. In practice this is a hard job, because concrete implementations offer numerous additional features and software engineers love to use them. A second aspect is the conservation of know how. If a student learns SQL, he is in a position to develop applications which are based on an arbitrary database system. The situation is comparable with any other popular programming language. If one learns Java or C-Sharp, he can develop applications of any kind running on a lot of different hardware systems and even different hardware architectures.
Limits
Database systems consist of many components. The access to the data is an important but not the only component. Additionally there are many more tasks: throughput optimization, physical design, backup, distributed databases, replication, 7x24 availability, ... . Standard SQL is focused mainly on data access and ignores typical DBA tasks. Even the C R E A T EI N D E Xstatement as a widely used optimization strategy is not part of the standard. Nevertheless the standard fills thousands of pages. But most of the DBA's daily work is highly specialized to every concrete implementation and must be done in a different way when he switches to a different rDBMS. Mainly application developers benefit from SQL.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
8/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Implementations
To fulfill their clients' demands all major vendors of rDBMS offers - among other data access ways - the language SQL within their product. The implementations cover Core SQL, a bunch of additional standardized features and a huge number of additional, not standardized features. The access to standardized features may use the regular syntax or an implementation specific syntax. In essence SQL is the clamp holding everything together, but normally there are a lot of detours around the official language.
Standard Track
Foundation
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
a name. 3. Of which data type are the information units? All data values within one column must be of the same datatype. We cannot put an arbitrary string to a column of datatype DATE. In our example we decide to save firstname, lastname, date and place of birth, the social security number as well as the persons weight. Obviously date of birth is of data type DATE, the weight is a number and all others are some kind of strings. For strings there is a distinction between those that have a fixed length and those in which the length usually varies greatly from row to row. The former is named CHAR(<n>), where <n> is the fixed length, and the others VARCHAR(<n>), where <n> is the maximum length.
Fasten Decisions
The decisions previously taken must be expressed in a machine-understandable language. This language is SQL, which acts as the interface between end users - or between special programms - and the DBMS.
-c o m m e n tl i n e ss t a r t sw i t ht w oc o n s e c u t i v em i n u ss i g n sf o l l o w e db yas p a c e' -' C R E A T ET A B L Ep e r s o n( -d e f i n ec o l u m n s( n a m e/t y p e/d e f a u l tv a l u e/n u l l a b l e ) i d D E C I M A L N O TN U L L , f i r s t n a m e V A R C H A R ( 5 0 ) N O TN U L L , l a s t n a m e V A R C H A R ( 5 0 ) N O TN U L L , d a t e _ o f _ b i r t h D A T E , p l a c e _ o f _ b i r t hV A R C H A R ( 5 0 ) , s s n C H A R ( 1 1 ) , w e i g h t D E C I M A LD E F A U L T0N O TN U L L , -s e l e c to n eo ft h ed e f i n e dc o l u m n sa st h eP r i m a r yK e ya n d -g u e s sam e a n i n g f u l ln a m ef o rt h eP r i m a r yK e yc o n s t r a i n t :' p e r s o n _ p k 'm a yb eag o o dc h o i c e C O N S T R A I N Tp e r s o n _ p kP R I M A R YK E Y( i d ) ) ;
We choose person as the name of the table, which consists of seven columns. One of them plays the role of the Primary Key: id. We can store exclusively digits in the column id and weight , strings in a length up to 50 characters in firstname, lastname and place_of_birth, dates in date_of_birth and a string of exactly eleven characters in ssn. The phrase NOT NULL is part of the definition of id, firstname, lastname and weight . This means that in every row there must be a value for those four columns. Storing no value in any of those columns is not possible - but the 8-character-string 'no value' or the digit '0' are allowed because they are values. Or to say it the other way round: it is possible to omit the values of date_of_birth, place_of_birth and ssn. The definition of a Primary Key is called a 'constraint' (later on we will get to know more kinds of constraints). Every constraint should have a name - it's person_pk in this example.
The Result
After execution of the above 'CREATE TABLE' command the DBMS has created an object that one can imagine similar to the following Wiki-table: id firstname lastname date_of_birth place_of_birth ssn weight
This Wiki-table shows 4 lines. The first line represents the names of the columns - no values! The following 3 lines are for demonstration purposes only. But in the database table exists currently no single row! She is completely empty, no rows at all, no values at all! The only thing that exists in the database is the structure of the table.
Back to Start
Maybe we want to delete the table one day. To do so we can use the DROP command. It removes the table totally: all data and the complete structure are thrown away.
D R O PT A B L Ep e r s o n ;
Don't confuse the DROP command with the DELETE command, which we present on the next page. The DELETE comand removes only rows - possibly all of them. However, the table itself, which holds the definition of the structure, keeps retained. As shown in the previous page we now have an empty table named person. What can we do with such a table? Just use it like a bag! Store things in it, look into it to check the existence of things, modify things in it or throw things out of it. These are the four natural operations, which concerns data in tables: INSERT: put some data into the table SELECT: retrieve data from the table UPDATE: modify data, which exists in the table
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 10/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
DELETE: remove data from the table. Each of these four operations are expressed by their own SQL command. They start with a keyword and runs up to a semicolon at the end. This rule applies to all SQL commands: They are introduced by a keyword and terminated by a semicolon. In the middle there may be more keywords as well as object names and values.
Here is an example
-p u to n er o w I N S E R TI N T Op e r s o n( i d ,f i r s t n a m e ,l a s t n a m e , d a t e _ o f _ b i r t h , p l a c e _ o f _ b i r t h ,s s n , w e i g h t ) V A L U E S ( 1 , ' L a r r y ' , ' G o l d s t e i n ' ,D A T E ' 1 9 7 0 1 1 2 0 ' ,' D a l l a s ' , ' 0 7 8 0 5 1 1 2 0 ' ,9 5 ) ; -c o n f i r mt h eI N S E R Tc o m m a n d C O M M I T ;
When the DBMS recognise the keywords INSERT INTO and VALUES it knows what to do: it creates a new row in the table and put the given values into the named columns. In the above example the command is followed by a second one: COMMIT confirms the INSERT operation as well as the other writing operations UPDATE and DELETE. (We will learn much more about COMMIT and its counterpart ROLLBACK in a later chapter.)
A short comment about the format of the value for date_of_birth : There is no unique format for dates honored all over the world. Peoples use different formats depending on their cultural habit. For our purpose we decide to represent dates in the hierarchical format defined in ISO 8601. It may be possible that your local database installation use a different format so that you are forced to either modify our examples or to modify the default date format of your database installation.
Now we will put some more rows into our table. To do so we use a variation of the above syntax. It is possible to omit the list of columnnames if the list of values correlates exactly with the number, order and datatype of the columns used in the original CREATE TABLE statement.
Hint: The practice of omitting the list of columnnames is not recommended for real applications! Table structures change over time, e.g. someone may add new columns to the table. In this case unexpected side effects may occur in applications.
-p u tf o u rr o w s I N S E R TI N T Op e r s o nV A L U E S( 2 , I N S E R TI N T Op e r s o nV A L U E S( 3 , I N S E R TI N T Op e r s o nV A L U E S( 4 , I N S E R TI N T Op e r s o nV A L U E S( 5 , C O M M I T ;
' T o m ' , ' B u r t o n ' , D A T E ' 1 9 8 0 0 1 2 2 ' ,' B i r m i n g h a m ' , ' 0 7 8 0 5 1 1 2 1 ' ,7 5 ) ; ' L i s a ' , ' H a m i l t o n ' , D A T E ' 1 9 7 5 1 2 3 0 ' ,' M u m b a i ' , ' 0 7 8 0 5 1 1 2 2 ' ,5 6 ) ; ' D e b o r a ' ,' P a t t e r s o n ' ,D A T E ' 2 0 1 1 0 6 0 1 ' ,' S h a n g h a i ' , ' 0 7 8 0 5 1 1 2 3 ' ,1 1 ) ; ' J a m e s ' , ' d eW i n t e r ' ,D A T E ' 1 9 7 5 1 2 2 3 ' ,' S a nF r a n c i s c o ' ,' 0 7 8 0 5 1 1 2 4 ' ,7 5 ) ;
As with the INSERT command you may omit some parts. The simplest example is
S E L E C T F R O M
* p e r s o n ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
11/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The asterik character '*' indicates 'all columns'. In the result, the DBMS should deliver all five rows each with the seven values we used previously with the INSERT command. In the following examples we add the actually missing clauses of the general syntax - one after the other. Add a list of some or all columnnames
S E L E C T F R O M
f i r s t n a m e ,l a s t n a m e p e r s o n ;
The DBMS should deliver the two columns firstname and lastname of all five rows. Add a search condition
S E L E C T F R O M W H E R E
i d ,f i r s t n a m e ,l a s t n a m e p e r s o n i d>2 ;
The DBMS should deliver the three columns id, firstname and lastname of three rows. Add a sort instruction
S E L E C T i d ,f i r s t n a m e ,l a s t n a m e ,d a t e _ o f _ b i r t h F R O M p e r s o n W H E R E i d>2 O R D E RB Yd a t e _ o f _ b i r t h ;
The DBMS should deliver the four columns id, firstname, lastname and date_of_birth of three rows in the ascending order of date_of_birth.
U P D A T E< t a b l e n a m e > S E T < c o l u m n n a m e >=< v a l u e > , < c o l u m n n a m e >=< v a l u e > , . . . W H E R E < s e a r c h _ c o n d i t i o n > ;
Values are assigned to the named columns. Unmentioned columns keep unchanged. The search_condition acts in the same way as in the SELECT command. It restricts the coverage of the command to rows, which satisfy the criteria. If the WHERE keyword and the search_condition are omitted, all rows of the table are affected. It is possible to specify search_conditions, which hit no rows. In this case no rows are updated - and no error or exception occurrs. Change one column of one row
The first name of Mr. de Winter changes to James Walker whereas all his other values keep unchanged. Also all other rows keep unchanged. Please verify this with a SELECT command. Change one column of multiple rows
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 12/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The <search_condition> isn't restricted to the Primary Key column. We can specify any other column. And the comparision operator isn' t restricted to the equal sign. We can use other operators - they solely have to match the data type of the column. In this example we change the firstname of four rows with a single command. If there is a table with millions of rows we can change all of them using one single command. Change two columns of one row
D E L E T E F R O M p e r s o n W H E R E i d=5 ; C O M M I T ;
The row of James de Winter is removed from the table. Delete many rows
D E L E T E F R O M p e r s o n ; C O M M I T ;
All remained rows are deleted as we have omitted the <search_condition>. The table is empty, but it still exists. No rows affected
D E L E T E F R O M p e r s o n W H E R E i d=9 9 ; C O M M I T ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
13/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
This command will remove no row as there is no row with id equals to 99. But the syntax and the execution within the DBMS are still perfect. No exception is thrown. The command terminates without any error message or error code.
Summary
The INSERT and DELETE commands affect rows in its entirety. INSERT puts a complete new row to a table (unmentioned columns keeps empty) and DELETE removes complete rows. In contrast SELECT and UPDATE affect only those columns, which are mentioned in the command. Unmentioned columns keeps unaffected. The INSERT command (in the simple version of this page) has no <search_condition> and therefore handles exactly one row. The three other commands may affect zero, one or more rows depending on the evaluation of their <search_condition>. First of all a database is a collection of data. These data is organized in tables as shown in the example person. In addition, there are many other kinds of objects in the DBMS: views, functions, procedures, indices, rights and many others. Initially we focus on tables and present four of them. They serve as the foundation for our Wikibook. Other kind of objects will be presented later. We try to keep everything as simple as possible. Nevertheless this minimalistic set of four tables demonstrates a 1:n as well as a n:m relationship.
person
The person table holds information about fictitious persons; see: Create a simple Table.
-c o m m e n tl i n e ss t a r t sw i t ht w oc o n s e c u t i v em i n u ss i g n s' ' C R E A T ET A B L Ep e r s o n( -d e f i n ec o l u m n s( n a m e/t y p e/d e f a u l tv a l u e/n u l l a b l e ) i d D E C I M A L N O TN U L L , f i r s t n a m e V A R C H A R ( 5 0 ) N O TN U L L , l a s t n a m e V A R C H A R ( 5 0 ) N O TN U L L , d a t e _ o f _ b i r t h D A T E , p l a c e _ o f _ b i r t hV A R C H A R ( 5 0 ) , s s n C H A R ( 1 1 ) , w e i g h t D E C I M A LD E F A U L T0N O TN U L L , -s e l e c to n eo ft h ed e f i n e dc o l u m n sa st h eP r i m a r yK e ya n d -g u e s sam e a n i n g f u l ln a m ef o rt h eP r i m a r yK e yc o n s t r a i n t :' p e r s o n _ p k 'm a yb eag o o dc h o i c e C O N S T R A I N Tp e r s o n _ p kP R I M A R YK E Y( i d ) ) ;
contact
The contact table holds information about the contact data of some persons. One could consider to store this contact information in additional columns of the person table: one column for email, one for icq, and so on. We decided against it for some serious reasons. Missing values: A lot of people do not have most of those contact values respectively we doen't know the values. Hereinafter the table will look like a sparse matrix. Multiplicities: Other people have more than one email adress or multiple phone numbers. Shall we define a lot of columns email_1, email_2, ... ? What is the upper limit? Standard SQL does not offer something like an 'array of values' for columns (some implementations do). Future Extentions: Some day there will be one or more contact types which are unknown today. Then we have to modify the table. We can deal with all this situations in an uncomplicated way, when the contact data goes to its own table. The only special thing is bringing persons together with their contact data. This task will be managed by the column person_id of table contact . It holds the same value as the Primary Key of the allocated person. The general statement is, that we do have one information unit (person) to which potentially multiple information units of same type (contact) belongs to. We call this togetherness a relationship - in this case a 1:m relationship. Whenever we encounter such a situation, we store the values, which may occure more than once, in a separate table together with the id of the first table.
C R E A T ET A B L Ec o n t a c t( -d e f i n ec o l u m n s( n a m e/t y p e/d e f a u l tv a l u e/n u l l a b l e ) i d D E C I M A L N O TN U L L , p e r s o n _ i d D E C I M A L N O TN U L L , -u s ead e f a u l tv a l u e ,i fc o n t a c t _ t y p ei so m i t t e d c o n t a c t _ t y p e V A R C H A R ( 2 5 ) D E F A U L T' e m a i l 'N O TN U L L , c o n t a c t _ v a l u e V A R C H A R ( 5 0 ) N O TN U L L , -s e l e c to n eo ft h ed e f i n e dc o l u m n sa st h eP r i m a r yK e y C O N S T R A I N Tc o n t a c t _ p kP R I M A R YK E Y( i d ) , -d e f i n eF o r e i g nK e yr e l a t i o nb e t w e e nc o l u m np e r s o n _ i da n dc o l u m ni do ft a b l ep e r s o n C O N S T R A I N Tc o n t a c t _ f kF O R E I G NK E Y( p e r s o n _ i d )R E F E R E N C E Sp e r s o n ( i d ) , -m o r ec o n t r a i n t ( s ) C O N S T R A I N Tc o n t a c t _ c h e c kC H E C K( c o n t a c t _ t y p eI N( ' f i x e dl i n e ' ,' m o b i l e ' ,' e m a i l ' ,' i c q ' ,' s k y p e ' ) ) ) ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
14/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
hobby
People usually pursue one or more hobbies. Concerning multiplicity we have the same problems as before with contact . So we need a separate table for hobbies.
You may have noticed, that there is no column for the corresponding person. Why this? With hobbies we have an additional problem: It's not just that one person pursues multiple hobbies. At the same time multiple persons pursue the same hobby. We call this kind of togetherness a n:m relationship. It can be designed by creating a third table between the two original tables. The third table holds the id's of the first and second table. So one can decide which person persues which hobby. In our example this 'table-in-the-middle' is person_hobby and will be defined next.
person_hobby
C R E A T ET A B L Ep e r s o n _ h o b b y( -d e f i n ec o l u m n s( n a m e/t y p e/d e f a u l tv a l u e/n u l l a b l e ) i d D E C I M A L N O TN U L L , p e r s o n _ i d D E C I M A L N O TN U L L , h o b b y _ i d D E C I M A L N O TN U L L , -A l s ot h i st a b l eh a si t so w nP r i m a r yK e y ! C O N S T R A I N Tp e r s o n _ h o b b y _ p kP R I M A R YK E Y( i d ) , -d e f i n eF o r e i g nK e yr e l a t i o nb e t w e e nc o l u m np e r s o n _ i da n dc o l u m ni do ft a b l ep e r s o n C O N S T R A I N Tp e r s o n _ h o b b y _ f k _ 1F O R E I G NK E Y( p e r s o n _ i d )R E F E R E N C E Sp e r s o n ( i d ) , -d e f i n eF o r e i g nK e yr e l a t i o nb e t w e e nc o l u m nh o b b y _ i da n dc o l u m ni do ft a b l eh o b b y C O N S T R A I N Tp e r s o n _ h o b b y _ f k _ 2F O R E I G NK E Y( h o b b y _ i d )R E F E R E N C E Sh o b b y ( i d ) ) ;
Every row of the table holds one id from person and one from hobby. This is the technic how the information of persons and hobbies are joined together.
rDBMS offers different ways to put data into their storage: from csv files, Excel files, product specific binary files, via several API's or special gateways to other databases respectively database systems and some more technics. So there is a wide range of non standardised - possibilities to bring data into our system. Because we are speaking about SQL we use the standardised INSERT command to do the job. It is available on all systems. We use only a small amount of data because we want to keep things simple. Sometimes one needs a great number of rows to do performance tests. For this purpose we show a special INSERT command at the end of this page, which inflates your table in an exponential fashion.
person
Visual Representation of our Example Database
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
15/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
-D E L E T EF R O Mp e r s o n _ h o b b y ; -D E L E T EF R O Mh o b b y ; -D E L E T EF R O Mc o n t a c t ; -D E L E T EF R O Mp e r s o n ; -C O M M I T ; I N S E R TI N T Op e r s o nV A L U E S( 1 , ' L a r r y ' , ' G o l d s t e i n ' ,D A T E I N S E R TI N T Op e r s o nV A L U E S( 2 , ' T o m ' , ' B u r t o n ' , D A T E I N S E R TI N T Op e r s o nV A L U E S( 3 , ' L i s a ' , ' H a m i l t o n ' , D A T E I N S E R TI N T Op e r s o nV A L U E S( 4 , ' K i m ' , ' G o l d s t e i n ' ,D A T E I N S E R TI N T Op e r s o nV A L U E S( 5 , ' J a m e s ' , ' d eW i n t e r ' ,D A T E I N S E R TI N T Op e r s o nV A L U E S( 6 , ' E l i a s ' , ' B a k e r ' , D A T E I N S E R TI N T Op e r s o nV A L U E S( 7 , ' Y o r g o s ' ,' S t e f a n o s ' , D A T E I N S E R TI N T Op e r s o nV A L U E S( 8 , ' J o h n ' , ' d eW i n t e r ' ,D A T E I N S E R TI N T Op e r s o nV A L U E S( 9 , ' R i c h i e ' ,' R i c h ' , D A T E I N S E R TI N T Op e r s o nV A L U E S( 1 0 ,' V i c t o r ' ,' d eW i n t e r ' ,D A T E C O M M I T ;
contact
-D E L E T EF R O Mc o n t a c t ; -C O M M I T ; I N S E R TI N T Oc o n t a c tV A L U E S( 1 , I N S E R TI N T Oc o n t a c tV A L U E S( 2 , I N S E R TI N T Oc o n t a c tV A L U E S( 3 , I N S E R TI N T Oc o n t a c tV A L U E S( 4 , I N S E R TI N T Oc o n t a c tV A L U E S( 5 , I N S E R TI N T Oc o n t a c tV A L U E S( 6 , I N S E R TI N T Oc o n t a c tV A L U E S( 7 , I N S E R TI N T Oc o n t a c tV A L U E S( 8 , I N S E R TI N T Oc o n t a c tV A L U E S( 9 , C O M M I T ; 1 , 1 , 1 , 1 , 4 , 4 , 5 , 7 , 7 , ' f i x e dl i n e ' ,' 5 5 5 0 1 0 0 ' ) ; ' e m a i l ' , ' l a r r y . g o l d s t e i n @ a c m e . x x ' ) ; ' e m a i l ' , ' l g @ m y _ c o m p a n y . x x ' ) ; ' i c q ' , ' 1 2 1 1 1 ' ) ; ' f i x e dl i n e ' ,' 5 5 5 0 1 0 1 ' ) ; ' m o b i l e ' , ' 1 0 1 2 3 4 4 4 4 4 4 ' ) ; ' e m a i l ' , ' j a m e s . d e w i n t e r @ a c m e . x x ' ) ; ' f i x e dl i n e ' ,' + 3 0 0 0 0 0 0 0 0 0 0 0 0 0 ' ) ; ' m o b i l e ' , ' + 3 0 6 9 5 1 0 0 0 0 0 0 0 0 ' ) ;
hobby
-D E L E T EF R O Mh o b b y ; -C O M M I T ; I N S E R TI N T Oh o b b yV A L U E S( 1 , ' P a i n t i n g ' , ' A p p l y i n gp a i n t ,p i g m e n t ,c o l o ro ro t h e rm e d i u mt oas u r f a c e . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 2 , ' F i s h i n g ' , ' C a t c h i n gf i s h e s . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 3 , ' U n d e r w a t e rD i v i n g ' , ' G o i n gu n d e r w a t e rw i t ho rw i t h o u tb r e a t h i n ga p p a r a t u s( s c u b ad i v i n g/b r e a t h h o l d i n g ) . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 4 , ' C h e s s ' , ' T w op l a y e r sh a v e1 6f i g u r e se a c h .T h e ym o v et h e mo na ne i g h t b y e i g h tg r i da c c o r d i n gt os p e c i a lr u l e s . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 5 , ' L i t e r a t u r e ' ,' R e a d i n gb o o k s . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 6 , ' Y o g a ' , ' Ap h y s i c a l ,m e n t a l ,a n ds p i r i t u a lp r a c t i c e sw h i c ho r i g i n a t e di na n c i e n tI n d i a . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 7 , ' S t a m pc o l l e c t i n g ' , ' C o l l e c t i n go fp o s ts t a m p sa n dr e l a t e do b j e c t s . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 8 , ' A s t r o n o m y ' , ' O b s e r v i n ga s t r o n o m i c a lo b j e c t ss u c ha sm o o n s ,p l a n e t s ,s t a r s ,n e b u l a e ,a n dg a l a x i e s . ' ) ; I N S E R TI N T Oh o b b yV A L U E S( 9 , ' M i c r o s c o p y ' , ' O b s e r v i n gv e r ys m a l lo b j e c t su s i n gam i c r o s c o p e . ' ) ; C O M M I T ;
person_hobby
-D E L E T EF R O Mp e r s o n _ h o b b y ; -C O M M I T ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 1 ,1 ,1 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 2 ,1 ,4 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 3 ,1 ,5 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 4 ,5 ,2 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 5 ,5 ,3 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 6 ,7 ,8 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 7 ,4 ,4 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 8 ,9 ,8 ) ; I N S E R TI N T Op e r s o n _ h o b b yV A L U E S( 9 ,9 ,9 ) ; C O M M I T ;
Grow up
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 16/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
For realistic performance tests we need a huge amount of data. The few number of rows in our example database does not meet this criteria. How can we generate test data and store it in a table? There are different possibilities: FOR loops in a procedure, (pseudo-) recursive calls, importing external data in a system specific fashion and some more. Because we are dealing with SQL we introduce an INSERT command which is portable across all rDBMS. Although it has a simple syntax it is very powerful. With every execution it will double the number of rows. Suppose there is 1 row in a table. After the first execution there will be a second row in the table. At first glance this sounds boring. But after 10 executions there are more than thousand rows, after 20 executions there are more than a million, and we suspect that only few installations are able to execute it more than 30 times.
I N S E R TI N T Op e r s o n( i d , f i r s t n a m e ,l a s t n a m e ,w e i g h t ) S E L E C T i d+( S E L E C TM A X ( i d )F R O Mp e r s o n ) ,f i r s t n a m e ,l a s t n a m e ,w e i g h t F R O M p e r s o n ; C O M M I T ;
The command is an INSERT in combination with a (Sub-)SELECT. The SELECT retrievs all rows of the table because there is no WHERE clause. This is the reason for the doubling. The mandatory columns firstname and lastname keeps unchanged. We ignore optional columns. Only the primary key id is computed. The new value is the sum of the old value plus the highest available id when starting the command. Some more remarks: max(id) is determined only once per execution! This illustrates an important aspect of rDBMS: At a conceptual level the database has a certain state before execution of a command and a new state after its execution. Commands are atomic operations moving the database from one state to another - they run completely or not a bit! Both, the SELECT and the inner SELECT with the max(id), act on the initial state. They never see the result or an intermediate result of the INSERT. Otherwise the INSERT would never end. If we wish to observe the process of growing, we can add a column to the table to store max(id) with each iteration. The computation of the new id may be omitted if the DBMS supports AUTO INCREMENT columns. For performance tests it may be helpful to store some random data in one or more columns. Basic Commands
The SELECT command retrievs data from one or more tables or views. It generally consists of the following language elements:
S E L E C T < t h i n g s _ t o _ b e _ d i s p l a y e d > -t h es oc a l l e d' P r o j e c t i o n '-m o s t l yal i s to fc o l u m n n a m e s F R O M < t a b l e n a m e > -t a b l eo rv i e wn a m e sa n dt h e i ra l i a s e s W H E R E < w h e r e _ c l a u s e > -t h es oc a l l e d' R e s t r i c t i o n 'o r' s e a r c hc o n d i t i o n ' G R O U PB Y< g r o u p _ b y _ c l a u s e > H A V I N G < h a v i n g _ c l a u s e > O R D E RB Y< o r d e r _ b y _ c l a u s e > ;
With the exception of the first two elements all others are optional. The sequence of language elements is mandatory. At certain places within the command there may start new SELECT commands - in a recursive manner.
Projection
In the projection part of the SELECT command you specifiy a list of columns, operations working on columns, functions, fixed values or new SELECT commands.
* / * / * / * /
The DBMS will retrieve ten rows, each of them consists of four columns. We can mix the sequence of columns in any order or retrieve them several times.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
17/110
4/2/2014
F R O M p e r s o n ;
Structured Query Language/Print version - Wikibooks, open books for an open world
S E L E C T*F R O Mp e r s o n ;
For numeric colums we can apply the usual numeric operators +, -, * and /. There are also a lot of predefined functions depending on the data type: power, sqrt, modulo, string functions, date functions.
UNIQUE
It is possible to compact results in the sense of UNIQUE values. In this case all resulting rows , which would be identical without the UNIQUE keyword, will be compressed to one row. In other words: duplicates are eliminated - just like in set theorie.
-T h ek e y w o r d' A S 'i so p t i o n a l S E L E C Tl a s t n a m eA Sf a m i l y _ n a m e ,w e i g h tw e i g h t _ i n _ k g F R O M p e r s o n ;
Functions
There are predefined functions for use in projections (and at some other positions). The most frequently used are: count(<columnname>|'*'): Counts the number of resulting rows. max(<columnname>): The highest value in <column> of the resultset. Also applicable on strings. min(<columnname>): The lowest value in <column> of the resultset. Also applicable on strings. sum(<columnname>): The sum of all values in a numeric column. avg(<columnname>): The average of a numeric column. concat(<columnname_1>, <columnname_2>): The concatenation of two columns. Alternatively the function may be expressed by the '||' operator: <columnname_1> || <columnname_2> Standard SQL and every DBMS offers much more functions. We must differ between those functions which return one value per row like concat() and those which return only one row per complete resultset like max(). The former one may be mixed in any combination with column names as shown in the very first example of this page. With the later ones there exists a problem: If we mix them with a normal column name, the DBMS recognise a contradiction in the query. On the one hand it should retrieve exactly one value (in one row) and on the other hand it should retrieve a lot of values (in a lot of rows). The reaction of DBMS differ from vendor to vendor. Some throw an error message at runtime, others deliver suspicious results.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 18/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
-w o r k sf i n e S E L E C Tl a s t n a m e ,c o n c a t ( w e i g h t ,'k g ' ) F R O M p e r s o n ; -c h e c kt h er e a c t i o no fy o u rD B M S S E L E C Tl a s t n a m e ,a v g ( w e i g h t ) F R O M p e r s o n ;
-r e t r i e v e s1 0r o w s ;n o t i c et h ea d d i t i o n a lp a r e n t h e s i st od e l i m i tt h et w oS E L E C T sf r o me a c ho t h e r . S E L E C Tl a s t n a m e ,( S E L E C Ta v g ( w e i g h t )F R O Mp e r s o n ) F R O M p e r s o n ; -C o m p u t et h ep e r c e n t a g eo fe a c hp e r s o n sw e i g h ti nr e l a t i o nt ot h ea v e r a g ew e i g h to fa l lp e r s o n s S E L E C Tl a s t n a m e ,w e i g h t ,w e i g h t*1 0 0/( S E L E C Ta v g ( w e i g h t )F R O Mp e r s o n )A Sp e r c e n t a g e _ o f _ a v e r a g e F R O M p e r s o n ;
Table names
Behind the Keyword FROM we have to announce the name of the table on which the command shall work. Thereby the table name is well known and may be used as an identifier. In the first simple examples the use of an additional identifier seems to be needless. Later on it will turn into a neccessary feature to formulate complex commands.
Restriction
In the WHERE clause we specify some 'search conditions' which are among the named table(s) or view(s). The evaluation of this criterias is - mostly - one of the first things during the execution of a SELECT command. Before any row can be sorted or displayed, she must meet the conditions in the clause. If we ommit the clause all rows of the table are retrieved. Else the number of rows will be reduced according to the specified criterias. If we specify 'weight < 70', for example, only those rows are retrieved where the weight column stores a value less than 70. It is such that restrictions act on rows of tables by evaluation column values (sometime they act on other things like the existence of rows, but for the moment we focus on basic principles). As a result, we can imagine that the evaluation of the 'where clause' produces a list of rows. This list of rows will be processed in further steps like sorting, grouping or displaying certain columns (projection).
Comparisions
We compare variables, constant values and results of function calls with each other in the same way as we would do in other programming languages. The only difference is, that we use column names instead of variables. The comparision operators must match the given data types they have to operate on. The result of the comparision is a boolean value. If it is 'true' the according row will be processed furthermore. Some examples: 'weight = 70' compares the column 'weight' with the constant value '70' whether the column is equal to the constant value.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 19/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
'70 = weight': same as before. 'firstname = lastname' compares two columns - each of the same row - for equality. Names like 'Frederic Frederic' evaluate to true. 'firstname < lastname' is a legal comparision of two columns according to the lexical order of strings. 'LENGTH(firstname) < 5' compares the result of a function call to the constant value '5'. The function LENGTH() operates on strings and returns a number.
Boolean logic
Often we want to specify more than a single search criteria, e.g.: Are there people born in San Francisco with lastname Baker? To do this, we specify every necessary comparision independent from the next one and join them together with the boolean operators AND respectively OR.
The result of a comparision is a boolean. It may be toggled between 'true' and 'false' by the unary operator NOT.
S E L E C T * F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' A N DN O Tl a s t n a m e=' B a k e r ' ;-a l le x c e p t' B a k e r ' -f o rc l a r i f i c a t i o n :T h eN O Ti nt h ef o r e g o i n ge x a m p l ei sa n' u n a r yo p e r a t i o n 'o nt h er e s u l to ft h e c o m p a r i s i o n .I t ' sn o ta na d d i t i o nt ot h eA N D . S E L E C T * F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' A N D( N O T( l a s t n a m e=' B a k e r ' ) ) ; - s a m ea sb e f o r e ,b u te x p l i c i tn o t a t e dw i t hp a r e n t h e s i s
The precedence of comparisions and boolean logic is as follows: 1. 2. 3. 4. all comparisions NOT operator AND operator OR operator
-A N D( b o r ni nS Fa n dl a s t n a m eB a k e r ;1h i ta sa ni n t e r m e d i a t er e s u l t )w i l lb ep r o c e s s e db e f o r e -O R ( p e r s o nY o r g o s ;1h i t ) -1+1= = >2r o w s S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o '-4h i t sS F A N D l a s t n a m e=' B a k e r ' -1h i tB a k e r O R f i r s t n a m e=' Y o r g o s ' -1h i tY o r g o s ; -A N D( p e r s o nY o r g o sB a k e r ;n oh i ta sa ni n t e r m e d i a t er e s u l t )w i l lb ep r o c e s s e db e f o r e -O R ( b o r ni nS F ;4h i t s ) -0+4= = >4r o w s S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o '-4h i t sS F O R f i r s t n a m e=' Y o r g o s ' -1h i tY o r g o s A N D l a s t n a m e=' B a k e r ' -1h i tB a k e r ; -W ec a nm o d i f yt h es e q u e n c eo fe v a l u a t i o n sb ys p e c i f y i n gp a r e n t h e s e s . -S a m ea sf i r s te x a m p l e ,a d d i n gp a r e n t h e s e s ,o n er o w . S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o '-4h i t sS F A N D ( l a s t n a m e=' B a k e r ' -1h i tB a k e r O R f i r s t n a m e=' Y o r g o s ' ) -1h i tY o r g o s ;
Two abbreviations Sometimes we shorten the syntax by using the BETWEEN keyword. It defines a lower and upper limit and is used mainly for numeric and date values, but also applicable to strings.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 20/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
For the comparision of a column or function with a number of values we can use the short IN expression.
Grouping
We will offer the GROUP BY clause in combination with the HAVING clause in a later chapter.
Sorting
The DBMS is free to deliver the resulting rows in an arbitrary order. Rows may be returned in the order of the Primary Key, in the chronological order they are stored into the database, in the order of an B-tree organised internal key, or even in a random order. Concerning the sequence of delivered rows the DBMS may do what it wants to do. Don't expect anything. If we expect a certain order of rows, we must express our whishes explicitly. We can do this in the ORDER BY clause. There we specify a list of columnnames in combination with an option for ascending repectively descending sorting.
-a l lp e r s o n si na s c e n d i n g( w h i c hi st h ed e f a u l t )o r d e ro ft h e i rw e i g h t S E L E C T* F R O M p e r s o n O R D E RB Yw e i g h t ; -a l lp e r s o n si nd e s c e n d i n go r d e ro ft h e i rw e i g h t S E L E C T* F R O M p e r s o n O R D E RB Yw e i g h tD E S C ;
In the above result there are two rows with identical values in the column weight . As this situation leads to random results, we have the possibility to specify more columns. These following columns are processed only for those rows with identical values in all preceeding columns.
-A l lp e r s o n si nd e s c e n d i n go r d e ro ft h e i rw e i g h t .I na m b i g u o u sc a s e so r d e rt h e -a d d i t i o n a lc o l u m np l a c e _ o f _ b i r t ha s c e n d i n g :B i r m i n g h a mb e f o r eS a nF r a n c i s c o . S E L E C T* F R O M p e r s o n O R D E RB Yw e i g h tD E S C ,p l a c e _ o f _ b i r t h ;
In the ORDER BY clause we can specify any column of the processed table. We are not limited to the ones which are returned by the projection.
-s a m eo r d e r i n ga sa b o v e S E L E C Tf i r s t n a m e ,l a s t n a m e F R O M p e r s o n O R D E RB Yw e i g h tD E S C ,p l a c e _ o f _ b i r t h ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
21/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Further Information
There are more information about additional opportunities of the SELECT command. Join Operation Grouping Set Operations Like Operator Predefined Functions
Exercises
Show hobbyname and remark from the hobby table. Click to see solution
S E L E C Th o b b y n a m e ,r e m a r k F R O M h o b b y ;
Show hobbyname and remark from the hobby table. Order the result by hobbyname. Click to see solution
S E L E C Th o b b y n a m e ,r e m a r k F R O M h o b b y O R D E RB Yh o b b y n a m e ;
Show hobbyname and remark from the hobby table. Choose 'Hobby' as first columnname and 'Short_Description_of_Hobby' as second columnname. Click to see solution
S E L E C Th o b b y n a m eA SH o b b y ,r e m a r kA SS h o r t _ D e s c r i p t i o n _ o f _ H o b b y F R O M h o b b y ; -c o l u m n n a m ew i t h o u tu n d e r s c o r e :U s eq u o t e s S E L E C Th o b b y n a m eA SH o b b y ,r e m a r kA S" S h o r tD e s c r i p t i o no fH o b b y " F R O M h o b b y ;
Show firstname and lastname of persons born in San Francisco. Click to see solution
S E L E C Tf i r s t n a m e ,l a s t n a m e F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' ;
Show all information items of persons with lastname 'de Winter'. Click to see solution
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 22/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
S E L E C T* F R O M p e r s o n W H E R E l a s t n a m e=' d eW i n t e r ' ;
How many rows are stored in the contact table? Click to see solution
S E L E C TC O U N T ( * ) F R O M c o n t a c t ; 9
How many E-Mails are stored in the contact table? Click to see solution
S E L E C TC O U N T ( * ) F R O M c o n t a c t W H E R E c o n t a c t _ t y p e=' e m a i l ' ; 3
What is the mean weight of persons born in San Francisco? Click to see solution
S E L E C Ta v g ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' ; 7 1 . 2 5
Find persons born after 1979-12-31, which weigh more than / less than 50 kg. Click to see solution
S E L E C T* F R O M p e r s o n W H E R E d a t e _ o f _ b i r t h>D A T E' 1 9 7 9 1 2 3 1 ' A N D w e i g h t>5 0 ; S E L E C T* F R O M p e r s o n W H E R E d a t e _ o f _ b i r t h>D A T E' 1 9 7 9 1 2 3 1 ' A N D w e i g h t<5 0 ;
Find persons born in Birmingham, Mumbai, Shanghai or Athens in the order of their firstname. Click to see solution
S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' B i r m i n g h a m ' O R p l a c e _ o f _ b i r t h=' M u m b a i ' O R p l a c e _ o f _ b i r t h=' S h a n g h a i ' O R p l a c e _ o f _ b i r t h=' A t h e n s ' O R D E RB Yf i r s t n a m e ; -e q u i v a l e n t : S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t hI N( ' B i r m i n g h a m ' ,' M u m b a i ' ,' S h a n g h a i ' ,' A t h e n s ' ) O R D E RB Yf i r s t n a m e ;
Find persons born in Birmingham, Mumbai, Shanghai or Athens within the 21. century. Click to see solution
S E L E C T* F R O M p e r s o n W H E R E ( p l a c e _ o f _ b i r t h=' B i r m i n g h a m ' O Rp l a c e _ o f _ b i r t h=' M u m b a i '
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
23/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
O Rp l a c e _ o f _ b i r t h=' S h a n g h a i ' O Rp l a c e _ o f _ b i r t h=' A t h e n s ' ) A N D d a t e _ o f _ b i r t h> =D A T E' 2 0 0 0 0 1 0 1 ' ; -e q u i v a l e n t : S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t hI N( ' B i r m i n g h a m ' ,' M u m b a i ' ,' S h a n g h a i ' ,' A t h e n s ' ) A N D d a t e _ o f _ b i r t h> =D A T E' 2 0 0 0 0 1 0 1 ' ;
Find persons born between Dallas and Richland ('between' not in the sense of a geografic area but of the lexical order of citynames) Click to see solution
-s t r i n g sh a v eal e x i c a lo r d e r .S ow ec a nu s es o m eo p e r a t o r sk n o w n -f r o mn u m e r i cd a t at y p e s . S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h> =' D a l l a s ' A N D p l a c e _ o f _ b i r t h< =' R i c h l a n d ' O R D E RB Yp l a c e _ o f _ b i r t h ; -e q u i v a l e n t : S E L E C T* F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t hB E T W E E N' D a l l a s 'A N D' R i c h l a n d ' O R D E RB Yp l a c e _ o f _ b i r t h ;
Which kind of contacts are stored in the contact table? (Only one row per value.) Click to see solution
S E L E C TD I S T I N C Tc o n t a c t _ t y p e F R O M c o n t a c t ; f i x e dl i n e e m a i l i c q m o b i l e
How many different kind of contacts are stored in the contact table? (Hint: Count the rows of above query.) Click to see solution
S E L E C TC O U N T ( D I S T I N C Tc o n t a c t _ t y p e ) F R O M c o n t a c t ; 4
Show contact_type, contact_value and a string of the form 'total number of contacts: <x>', where <x> is the quantity of all existing contacts. Click to see solution
S E L E C Tc o n t a c t _ t y p e ,c o n t a c t _ v a l u e , ( S E L E C Tc o n c a t ( ' t o t a ln u m b e ro fc o n t a c t s :' ,C O U N T ( * ) )F R O Mc o n t a c t ) F R O M c o n t a c t ; -S o m es y s t e m sn e e de x p l i c i tt y p ec a s t i n gf r o mn u m e r i ct os t r i n g S E L E C Tc o n t a c t _ t y p e ,c o n t a c t _ v a l u e , ( S E L E C Tc o n c a t ( ' t o t a ln u m b e ro fc o n t a c t s :' ,C A S T ( C O U N T ( * )A SC H A R ) )F R O Mc o n t a c t ) F R O M c o n t a c t ; -T h e' | | 'o p e r a t o ri ss o m ek i n do f' s y n t a c t i c a ls u g a r ' .I t ' sa na b b r e v i a t i o nf o rt h ec o n c a t ( )f u n c t i o n . -T h eo p e r a t o ri sp a r to ft h eS Q Ls t a n d a r d ,b u tn o ti m p l e m e n t e db ya l lv e n d o r s . S E L E C Tc o n t a c t _ t y p e ,c o n t a c t _ v a l u e , ( S E L E C T' t o t a ln u m b e ro fc o n t a c t s :'| |C O U N T ( * )F R O Mc o n t a c t ) F R O M c o n t a c t ;
DBMS offers a special service. We can undo a single or even multiple consecutive write and delete operations. To do so we use the command ROLLBACK. When modifying data, the DBMS writes in a first step all new, changed or deleted data to a temporary space. During this stage the modified data is not part of the 'regular' database. If we are sure the modifications shall apply, we use the COMMIT command. If we want to revert our changes, we use the ROLLBACK command. All changes up to the finally COMMIT or ROLLBACK are considered to be part of a so called transaction. The syntax of COMMIT and ROLLBACK is very simple.
C O M M I TW O R K ;
-c o m m i t sa l lp r e v i o u sI N S E R T ,U P D A T Ea n dD E L E T Ec o m m a n d s ,w h i c h
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
24/110
4/2/2014
R O L L B A C KW O R K ;
Structured Query Language/Print version - Wikibooks, open books for an open world
-o c c u r r e ds i n c el a s tC O M M I To rR O L L B A C K -r e v e r t sa l lp r e v i o u sI N S E R T ,U P D A T Ea n dD E L E T Ec o m m a n d s ,w h i c h -o c c u r r e ds i n c el a s tC O M M I To rR O L L B A C K
AUTOCOMMIT
The feature AUTOCOMMIT automatically performs a COMMIT after every write operation (INSERT, UPDATE or DELETE). This feature is not part of the SQL standard, but is implemented and activated by default in some implementations. If we want to use the ROLLBACK command, we must deactivate the AUTOCOMMIT. (After an - automatic or explicit - COMMIT command a ROLLBACK command is syntactically okay, but it does nothing as everything is already committed.) Often we can deactivate the AUTOCOMMIT with a separate command like 'SET autocommit = 0;' or 'SET autocommit off;' or by clicking an icon on a GUI. To test the following statements it is neccessary to work without AUTOCOMMIT.
COMMIT
Let us insert a new person into the database and test the COMMIT.
-S t o r ean e wp e r s o nw i t hi d9 9 . I N S E R TI N T Op e r s o n( i d ,f i r s t n a m e ,l a s t n a m e ,d a t e _ o f _ b i r t h , p l a c e _ o f _ b i r t h ,s s n , w e i g h t ) V A L U E S ( 9 9 ,' H a r r i e t ' ,' F l i n t ' , D A T E ' 1 9 7 0 1 0 1 9 ' ,' D a l l a s ' , ' 0 7 8 0 5 1 1 2 0 ' ,6 5 ) ; -I st h en e wp e r s o nr e a l l yi nt h ed a t a b a s e ?T h ep r o c e s sw h oe x e c u t e st h ew r i t eo p e r a t i o nw i l ls e ei t sr e s u l t s , -e v e ni ft h e ya r ea c t u a l l yn o tc o m m i t t e d .( O n eh i te x p e c t e d . ) S E L E C T* F R O M p e r s o n W H E R E i d=9 9 ; -T r yC O M M I Tc o m m a n d C O M M I T ; -I ss h es t i l li nt h ed a t a b a s e ?( O n eh i te x p e c t e d . ) S E L E C T* F R O M p e r s o n W H E R E i d=9 9 ;
So far, so boring.
ROLLBACK
The exciting command is the ROLLBACK. It restores changes of previous INSERT, UPDATE or DELETE commands. We delete and restore Mrs. Hamilton from our example database.
D E L E T E F R O M p e r s o n W H E R E i d=3 ;-L i s aH a m i l t o n -n oh i te x p e c t e d S E L E C T* F R O M p e r s o n
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
25/110
4/2/2014
W H E R E i d=3 ; -R O L L B A C Kr e s t o r e st h ed e l e t i o n R O L L B A C K ;
Structured Query Language/Print version - Wikibooks, open books for an open world
-O N Eh i te x p e c t e d! ! !E l s e :c h e c kA U T O C O M M I T S E L E C T* F R O M p e r s o n W H E R E i d=3 ;
The ROLLBACK is not restricted to one single row. It may affect several rows, several commands, different kind of commands and even several tables.
-s a m ea sa b o v e D E L E T E F R O M p e r s o n W H E R E i d=3 ; -d e s t r o ya l le m a i la d r e s s e s U P D A T Ec o n t a c t S E T c o n t a c t _ v a l u e=' u n k n o w n ' W H E R E c o n t a c t _ t y p e=' e m a i l ' ; -v e r i f ym o d i f i c a t i o n s S E L E C T*F R O Mp e r s o n ; S E L E C T*F R O Mc o n t a c t ; -As i n g l eR O L L B A C Kc o m m a n dr e s t o r e st h ed e l e t i o ni no n et a b l ea n dt h em o d i f i c a t i o n si na n o t h e rt a b l e R O L L B A C K ; -v e r i f yR O L L B A C K S E L E C T*F R O Mp e r s o n ; S E L E C T*F R O Mc o n t a c t ;
Exercises
Supose the hobby table contains 9 rows and the person table 10 rows. We execute the following operations: add 3 hobbies add 4 persons commit add 5 hobbies add 6 persons rollback Whow many rows are in the hobby table? Click to see solution
1 2
Whow many rows are in the person table? Click to see solution
1 4
Structured Query Language/INSERT Structured Query Language/UPDATE Structured Query Language/DELETE Daily Operations Data should be stored in a way, that no redundant information exists in the database. If more than one person indulge a hobby, for example, we avoid storing information about hobbies (designation, remarks, ...) within each affected persons row as this would double the hobbies information. And we avoid storing information about persons (name, ssn, ...) within each affected hobby row for the same reason. Instead we create independent person and hobby tables and point from one to the other. This technic of grouping data items redundancy-free into separate tables is called database normalization. As a result, information about complex objects is scattered across multiple tables. And we need a opportunity to reassemble the whole, original situation. This reverse technic is called a 'JOIN operation'.
The Idea
In our example database there are the two tables person and contact . The contact table contains the column person_id, which correlates with the Primary Key column id of the person table. By evaluating the column values we can join contacts and persons together.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
26/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
person table P ID LASTNAME FIRSTNAME ... 1 2 3 4 Goldstein Burton Hamilton Goldstein Larry Tom Lisa Kim ... ... ... ... ... ... ... ...
contact table C ID PERSON_ID CONTACT_TYPE CONTACT_VALUE 1 2 3 4 5 6 1 1 1 1 4 4 fixed line email email icq fixed line mobile ... ... 555-0100 [email protected] lg@my_company.xx 12111 5550101 10123444444 ... ...
Joined (virtual) table, created out of person and contact P.ID P.LASTNAME P.FIRSTNAME ... C.ID C.PERSON_ID C.CONTACT_TYPE C.CONTACT_VALUE 1 1 1 1 2 3 4 4 ... Goldstein Goldstein Goldstein Goldstein Burton Hamilton Goldstein Goldstein ... Larry Larry Larry Larry Tom Lisa Kim Kim ... ... 1 ... 2 ... 3 ... 4 ... ? ... ? ... 5 ... 6 ... ... 1 1 1 1 ? ? 4 4 ... fixed line email email icq ? ? fixed line mobile ... 555-0100 [email protected] lg@my_company.xx 12111 ? ? 5550101 10123444444 ...
As we see, Larry Goldstein, who exists only once in the real table person now occurs four times in the joined, virtual table, every time in combination with one of his four contact items. The same applies for Kim Goldstein with his two contact items. But what is going on with Tom Burton and Lisa Hamilton, whose contact information is not available? We may have some trouble with the attempt to join their person with - not existing - contact information. For the moment we have flagged the situation with question marks. Later on this page we will explain in detail how to transform the problem into a solution.
S E L E C T< t h i n g s _ t o _ b e _ d i s p l a y e d > -a su s u a l F R O M < t a b l e n a m e _ 1 >< t a b l e _ 1a l i a s > -at a b l ea l i a s J O I N < t a b l e n a m e _ 2 >< t a b l e _ 2a l i a s >O N< J O I Nc o n d i t i o n >-t h ej o i nc r i t e r i o n . . . -o p t i o n a l l ya l lt h eo t h e re l e m e n t so fS E L E C Tc o m m a n d ;
S E L E C T* F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
27/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The table names are mentioned behind the FROM (as usual) and behind the new keyword JOIN, which instructs the DBMS to perform a join operation. Next there is the ON keyword, which introduces the columnnames together with a comparision operator (or a general condition as you will see later). The columnnames are prefixed with the aliases of the tablenames p and c respectively. This is necessary, because in different tables there may exist columns with identical names like id. When the DBMS executes the command it delivers 'something' that contains all columns of table person and all columns of table contact - amongst others the two columns id of person and id of contact . The result contains 9 rows, one per existing combination of person and contact ('existing' in the sense of the formulation behind the 'ON' keyword). Please notice that persons without any stored contact are not part of the result. The delivered 'something' looks like a new table. And in fact it has the same structure, behaviour and data like a table. If it is created during a subselect or from a view, we can perform new SELECTs on it. But there is an important difference to tables: The data is not stored in the DBMS at its own place, the data is computed at runtime out of the values of real tables. The key feature of assembling complex information out of simple tables is possible by using the two simple keywords JOIN and ON. At the same time - as you will see - the syntax is extendable to manage very complex querys, so that there may be a great number of additional details in specifying your join criterias. People sometimes gets confused about the gap between their intention and some unexpected results. If you run into a problem of that kind, try to reduce your query to the shown simple form. Confusion often results from the fact, that the JOIN syntax itself may be complex due to a lot of details. Additionally joining can be combined with all other syntactical elements of the SELECT command, which also may lead to lack of clarity. The combination of the join syntax with other language elements is shown in the following examples.
-s h o wo n l yi m p o r t a n tc o l u m n s S E L E C Tp . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ t y p eA S" K i n do fC o n t a c t " ,c . c o n t a c t _ v a l u eA S" C a l lN u m b e r " F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d ; -s h o wo n l yd e s i r e dr o w s S E L E C Tp . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ t y p eA S" K i n do fC o n t a c t " ,c . c o n t a c t _ v a l u eA S" C a l lN u m b e r " F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d W H E R E c . c o n t a c t _ t y p eI N( ' f i x e dl i n e ' ,' m o b i l e ' ) ; -a p p l ya n ys o r to r d e r S E L E C Tp . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ t y p eA S" K i n do fC o n t a c t " ,c . c o n t a c t _ v a l u eA S" C a l lN u m b e r " F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d W H E R E c . c o n t a c t _ t y p eI N( ' f i x e dl i n e ' ,' m o b i l e ' ) O R D E RB Yp . l a s t n a m e ,p . f i r s t n a m e ,c . c o n t a c t _ t y p eD E S C ; -u s ef u n c t i o n s :m i n ( )/m a x ( )/c o u n t ( ) S E L E C TC O U N T ( * ) F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d W H E R E c . c o n t a c t _ t y p eI N( ' f i x e dl i n e ' ,' m o b i l e ' ) ; -J O I Nat a b l ew i t hi t s e l f .E x a m p l e :S e a r c hd i f f e r e n tp e r s o n sw i t hs a m el a s t n a m e S E L E C Tp 1 . i d ,p 1 . f i r s t n a m e ,p 1 . l a s t n a m e ,p 2 . i d ,p 2 . f i r s t n a m e ,p 2 . l a s t n a m e F R O M p e r s o np 1 J O I N p e r s o np 2O Np 1 . l a s t n a m e=p 2 . l a s t n a m e-f o rs e c o n di n c a r n a t i o no fp e r s o nw em u s tu s ead i f f e r e n ta l i a s W H E R E p 1 . i d! =p 2 . i d -s o r t i n go fp 2 . l a s t n a m ei sn o tn e c c e s s a r ya si ti si d e n t i c a lt ot h ea l r e a d ys o r t e dp 1 . l a s t n a m e O R D E RB Yp 1 . l a s t n a m e ,p 1 . f i r s t n a m e ,p 2 . f i r s t n a m e ; -J O I Nm o r et h a nt w ot a b l e s .E x a m p l e :c o n t a c ti n f o r m a t i o no fd i f f e r e n tp e r s o n sw i t hs a m el a s t n a m e S E L E C Tp 1 . i d ,p 1 . f i r s t n a m e ,p 1 . l a s t n a m e ,p 2 . i d ,p 2 . f i r s t n a m e ,p 2 . l a s t n a m e ,c . c o n t a c t _ t y p e ,c . c o n t a c t _ v a l u e F R O M p e r s o np 1 J O I N p e r s o np 2O Np 1 . l a s t n a m e=p 2 . l a s t n a m e J O I N c o n t a c tcO Np 2 . i d=c . p e r s o n _ i d -c o n t a c ti n f of r o mp e r s o n 2 .p 1 . i dw o u l dl e a dt op e r s o n 1 W H E R E p 1 . i d! =p 2 . i d O R D E RB Yp 1 . l a s t n a m e ,p 1 . f i r s t n a m e ,p 2 . l a s t n a m e ;
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
FULL [OUTER] JOIN Keywords surrounded by [ ] are optional. Omitting the INNER keyword leads to the basic syntax we have seen in the previous paragraph.
Inner Join
In most cases, people use the inner join. As we have seen previously the result in this version contains exactly those rows, which achievs exactly the criterion specified behind the ON. As a first example we create a list of persons and their contacts.
The important thing is that persons without any contact information are not part of the result.
Obviously the result contains all rows just like in the above inner join. Additionally there are rows for persons which have no contact information. As they do not have those information the values for the contact columns are not known. The DBMS fills them with the so called 'null value' (which is different from the string 'null value' and different from the binary 0 - and for SQL users it's waste to know how it is implemented). You will find more informations about null values and how to retrieve them in a later chaper. In summary the left (outer) join is an inner join plus one row for each row without a counterpart. Consider the word 'left'. It indicates that the evaluation of the formulation "FROM <table_1> LEFT JOIN <table_2>" is done from left to right. All rows of the left listed table (here: table_1) are included in the result, they may have a counterpart in table_2 or not. Another example:
S E L E C T p . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ t y p e ,c . c o n t a c t _ v a l u e F R O M c o n t a c tc L E F TJ O I Np e r s o np O Np . i d=c . p e r s o n _ i d -i d e n t i c a lm e a n i n g :L E F TO U T E RJ O I N. . . O R D E RB Y p . l a s t n a m e ,p . f i r s t n a m e ,c . c o n t a c t _ t y p eD E S C ,c . c o n t a c t _ v a l u e ;
What makes the difference? We have changed the order of tablenames. As contact is now mentioned on the left side, it is evaluated first (all the contact rows go to the result - plus their according person information). As in our example database there is no contact without a person, the result is the same as with an inner join. But it's different from the first example of the left join paragraph.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
29/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
In our example database their is no contact without a person, so the result of this query is identical to an inner join. In general a right join is identical to a left join with reverse order of table names, see our 'another example' above.
S E L E C T p . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ t y p e ,c . c o n t a c t _ v a l u e F R O M p e r s o np F U L LJ O I Nc o n t a c tcO Np . i d=c . p e r s o n _ i d -i d e n t i c a lm e a n i n g :F U L LO U T E RJ O I N. . . O R D E RB Y p . l a s t n a m e ,p . f i r s t n a m e ,c . c o n t a c t _ t y p eD E S C ,c . c o n t a c t _ v a l u e ;
table_2 ID TABLE_1_ID Y 1 2 1 5 21 22
S E L E C T * F R O M t a b l e _ 1t 1 F U L LJ O I Nt a b l e _ 2t 2O Nt 1 . i d=t 2 . t a b l e _ 1 _ i d ;
will result in T1.ID T1.X T2.ID T2.TABLE_1_ID T2.Y 1 2 3 null 11 12 13 null 1 null null 2 1 null null 5 21 null null 22
The result contains the (single) matching row plus all other rows, which are extended by null values in the missing cells. Hint: The full join is not supported by all DBMS. But as it isn't an atomic operation it is always possible to create the desired result by a combination of multiple SELECTs with SET operations.
Carthesian Product
In the case of the inner join version of the command we can omit the ON part. SQL interprets this situation as a request to combine every row of the left table with every row of the right table. The result will contain a large number of rows: number of rows within left table multiplied by number of rows within right table. This special kind of an inner join is called a carthesian product, see also: carthesian product in german Wiki. The carthesian product is an elementary operation of the relationa algebra, which is the foundation for all rDBMS implementations.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
30/110
4/2/2014
J O I N c o n t a c tc ;
Structured Query Language/Print version - Wikibooks, open books for an open world
Be carefull: If we (falsely) forget the ON term we will receive a large number of resulting rows. If, for example, the first table contains 10.000 rows and the second one 20.000 rows, we will receive 200 million rows.
-p e r s o n sc o m b i n e dw i t ht h e i rh o b b i e s S E L E C Tp . i dp _ i d ,p . f i r s t n a m e ,p . l a s t n a m e ,h . h o b b y n a m e ,h . i dh _ i d F R O M p e r s o n p J O I N p e r s o n _ h o b b yp hO Np . i d=p h . p e r s o n _ i d J O I N h o b b y h O Np h . h o b b y _ i d=h . i d O R D E RB Yp . l a s t n a m e ,p . f i r s t n a m e ,h . h o b b y n a m e ;
Please notice that no column of the table person_hobby goes to the result. This table acts only during intermediate execution steps. Even its column id is not of interest. Some people do not perform a hobby. As we performed an INNER JOIN they are not part of the above list. If we want to see in the list also persons without hobbies, we must do what we have done before: use LEFT OUTER JOINs instead of INNER JOINs.
-A L Lp e r s o n sp l u st h e i rh o b b i e s( i fp r e s e n t ) S E L E C Tp . i dp _ i d ,p . f i r s t n a m e ,p . l a s t n a m e ,h . h o b b y n a m e ,h . i dh _ i d F R O M p e r s o n p L E F TJ O I N p e r s o n _ h o b b yp hO Np . i d=p h . p e r s o n _ i d L E F TJ O I N h o b b y h O Np h . h o b b y _ i d=h . i d O R D E RB Yp . l a s t n a m e ,p . f i r s t n a m e ,h . h o b b y n a m e ;
Hint: If neccessary we can combine every kind of join with every other kind of join in every desired sequence, eg: LEFT OUTER with FULL OUTER with INNER ... .
More Details
Criterias for join operations are not restricted to the usual formulation:
S E L E C T. . . F R O M t a b l e _ 1t 1 J O I N t a b l e _ 2t 2O Nt 1 . i d=t 2 . f k . . .
First, we can use any column, not only primary key and foreign key columns. In one of the above examples we used the lastname for a join. Lastname is of type character and has no meaning of any key. To avoid poor peformance some DBMS restrict the use of columns to those having an index. Second, the comparator is not restricted to the equal sign. We can use any sensfull operator, for example the 'greater than' for numeric values.
-W h i c hp e r s o nh a st h eg r e a t e rb o d yw e i g h t-r e s t r i c t e dt o' d eW i n t e r 'f o rc l a r i t y S E L E C Tp 1 . i d ,p 1 . f i r s t n a m eA S" i sh e a v i e r " ,p 1 . w e i g h t ,p 2 . i d ,p 2 . f i r s t n a m eA S" t h a n " ,p 2 . w e i g h t F R O M p e r s o np 1 J O I N p e r s o np 2O Np 1 . w e i g h t>p 2 . w e i g h t W H E R E p 1 . l a s t n a m e=' d eW i n t e r ' A N D p 2 . l a s t n a m e=' d eW i n t e r ' O R D E RB Yp 1 . w e i g h tD E S C ,p 2 . w e i g h tD E S C ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
31/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Exercises
Show first- and lastname plus icq number for persons having an icq number Click to see solution
S E L E C Tp . i d ,p . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ v a l u e F R O M p e r s o np J O I N c o n t a c tcO Np . i d=c . p e r s o n _ i d W H E R E c . c o n t a c t _ t y p e=' i c q ' ;
Show first- and lastname plus icq number plus fixed line number for persons having an icq number AND a fixed line. You need to join the contact table twice. Click to see solution
S E L E C Tp . i d ,p . f i r s t n a m e ,p . l a s t n a m e , c 1 . c o n t a c t _ v a l u eA Si c q , c 2 . c o n t a c t _ v a l u eA S" f i x e dl i n e " F R O M p e r s o np J O I N c o n t a c tc 1O Np . i d=c 1 . p e r s o n _ i d J O I N c o n t a c tc 2O Np . i d=c 2 . p e r s o n _ i d W H E R E c 1 . c o n t a c t _ t y p e=' i c q ' A N D c 2 . c o n t a c t _ t y p e=' f i x e dl i n e ' ;
-l o o k sl i k ep r e v i o u s ,b u ti sd i f f e r e n t -i t ' sas e c o n d( v i r t u a l )i n c a r n a t i o no fc o n t a c tt a b l e -f r o mf i r s ti n c a r n a t i o n -f r o ms e c o n di n c a r n a t i o n
Show first- and lastname plus (if present) the icq number for ALL persons Click to see solution
-T or e t r i e v eA L Lp e r s o n si t ' sn e c c e s s a r yt ou s eaL E F Tj o i n . -B u tt h ef i r s ta p p r o a c hi sn o tw h a tw ee x p e c t !I nt h i se x a m p l et h eL E F TJ O I Ni se v a l u a t e df i r s t -a n dc r e a t e sa ni n t e r m e d i a t et a b l ew i t hn u l l v a l u e si nc o n t a c t _ t y p e( e l i m i n a t et h e -W H E R Ec l a u s et os e et h i si n t e r m e d i a t er e s u l t ) .T h e s er o w sa n da l lo t h e re x c e p tt h e -o n ew i t h' i c q 'a r et h e nt h r o w na w a yb ye v a l u a t i n gt h eW H E R Ec l a u s e . S E L E C T p . i d ,p . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ v a l u e F R O M p e r s o np L E F TJ O I Nc o n t a c tcO Np . i d=c . p e r s o n _ i d W H E R E c . c o n t a c t _ t y p e=' i c q ' ; -I t ' sn e c c e s s a r yt of o r m u l a t et h es e a r c hc r i t e r i o na sp a r to ft h eJ O I N .U n l i k ew i t h -t h eI N N E RJ O I Ni nt h ep r e v i o u se x a m p l ew i t h( L E F T / F U L L / R I G H T )O U T E RJ O I N si ti sn o tp o s s i b l e -t os h i f ti tt ot h eW H E R Ec l a u s e . S E L E C T p . i d ,p . f i r s t n a m e ,p . l a s t n a m e ,c . c o n t a c t _ v a l u e F R O M p e r s o np L E F TJ O I Nc o n t a c tcO Np . i d=c . p e r s o n _ i dA N Dc . c o n t a c t _ t y p e=' i c q ' ;
Create a list which contains ALL hobbies plus according persons (if present) Click to see solution
S E L E C Tp . i dp _ i d ,p . f i r s t n a m e ,p . l a s t n a m e ,h . h o b b y n a m e ,h . i dh _ i d F R O M p e r s o n p R I G H T J O I N p e r s o n _ h o b b yp hO Np . i d=p h . p e r s o n _ i d R I G H T J O I N h o b b y h O Np h . h o b b y _ i d=h . i d O R D E RB Yh . h o b b y n a m e ,p . l a s t n a m e ,p . f i r s t n a m e ;
Is it possible that one of the three outer joins contains fewer rows than the corresponding inner join? Click to see solution
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 32/110
4/2/2014
N o .
Structured Query Language/Print version - Wikibooks, open books for an open world
A l lf o u rj o i nt y p e sc o n t a i nt h es a m er o w sw i t hc o l u m n m a t c h i n g v a l u e s .I na d d i t i o n o u t e rj o i n sc o n t a i nr o w sw h e r ec o l u m nv a l u e sd on o tm a t c h-i fs u c has i t u a t i o ne x i s t s .
In this chapter we will leave the level of individual rows. We strive to find informations and statements that refer to groups of rows - at the expense of information about individual rows. In the context of SQL such 'row-groups' (or sets of rows) are build by the GROUP BY clause and further processed by the HAVING clause.
Constitute Groups
First we must establish criteria according to which the rows are assigned to groups. To do so we use the content of one or more columns of the involved table(s). If the values are identical, the rows belong to the same group. Consider the lastname in table person. In our small example we can insinuate that persons with same lastname form a family. So if we strive for informations about families we should use this column as the grouping criterion. This grouping allows us to ask questions concerning whole families, such as 'Which families are there?', 'How many families exists?', 'How many persons are in each family?'. Please note that all of them are questions about the whole group (which means the family), not about single rows (which means the person). In the SQL syntax the criterion is specified after the key word GROUP BY and consists of one or more columnnames.
S E L E C T. . . F R O M . . . G R O U PB Y< c o l u m n n a m e > . . . ;
-a su s u a l -a su s u a l( o p t i o n a l l yp l u sJ O I N s ) -o p t i o n a l l ym o r ec o l u m n n a m e s -o p t i o n a l l yo t h e re l e m e n t so fS E L E C Tc o m m a n d
S E L E C Tl a s t n a m e F R O M p e r s o n G R O U PB Yl a s t n a m e ;
The query retrieves seven 'family names' out of the 10 rows. There are several persons with lastname 'Goldstein' or 'de Winter'. We can retrieve the same seven 'family names' by applying the key word DISTINCT in a SELECT without GROUP BY.
S E L E C TD I S T I N C Tl a s t n a m e F R O M p e r s o n ; -n oG R O U PB Yc l a u s e
What makes the difference? The DISTINCT key word is limited to remove duplicate values. It can not initiate computations on other rows and columns of the result set. In contrast, the GROUP BY additionally arranges the intermediate received rows as a number of groups and offers the possibility to get informations about each of this groups. It is even the case that within this groups all columns are available, not only the 'criterion'-column. To confirm this statement about 'all' columns we use weight which is not the 'criterion'-column.
S E L E C Tl a s t n a m e ,a v g ( w e i g h t ) -a v g ( )i saf u n c t i o nt oc o m p u t et h ea r i t h m e t i cm e a no fn u m e r i c a lv a l u e s F R O M p e r s o n G R O U PB Yl a s t n a m e ;
The result shows the seven family names - as seen before - plus the average weight of every family. The weight of individual persons is not shown. (In groups with exactly one person the average weight of the group is of course identical to the single persons weight.)
-G r o u po v e ro n ec o l u m n :p l a c e _ o f _ b i r t hl e a d st o6r e s u l t i n gr o w s
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
33/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
S E L E C Tp l a c e _ o f _ b i r t h ,C O U N T ( * ) F R O M p e r s o n G R O U PB Yp l a c e _ o f _ b i r t h ; -G r o u po v e rt w oc o l u m n s :p l a c e _ o f _ b i r t hp l u sl a s t n a m el e a d st o8r e s u l t i n gr o w sw i t hR i c h l a n da n dS Fs h o w nt w i c e S E L E C Tp l a c e _ o f _ b i r t h ,l a s t n a m e ,C O U N T ( * ) F R O M p e r s o n G R O U PB Yp l a c e _ o f _ b i r t h ,l a s t n a m e ;
Inspect Groups
After we have defined groups with the GROUP BY key word, we can select more informations about each of them, e.g.: how much persons (rows) exist within each family (group of rows)?
S E L E C Tl a s t n a m e ,C O U N T ( * ) -c o u n t ( )i saf u n c t i o nw h i c hc o u n t sv a l u e so rr o w s F R O M p e r s o n G R O U PB Yl a s t n a m e ;
We see that in our small example database there is one family with 3 members, another with 2 members and all others consist of exactly 1 member. What is going on behind the scene during the execution of the command? 1. 2. 3. 4. All ten rows of table person are retrieved (in the above command there is no WHERE clause). The rows are arranged into seven groups according to the value of column lastname. Every group with all of its rows is passed to the SELECT clause. The SELECT builds one resulting row for every received group (in 'real world' databases each of the groups may contain thousands of rows).
In step 4 exactly one resulting row is generated per group. Because the SELECT creates only one resulting row per group, it is not possible to show values of such columns which may differ from row to row, e.g. the firstname. The SELECT can only show such values of which it is ensured that they are identical within all rows of the group: the 'criterion'-column.
-I ti sn o tp o s s i b l et os h o wt h e' f i r s t n a m e 'o fag r o u p !' F i r s t n a m e 'i sa na t t r i b u t eo fs i n g l ep e r s o n s . -W i t h i nag r o u p' f i r s t n a m e 'v a r i e sf r o mr o wt or o w . -T h eD B M Ss h o u l dr e c o g n i s et h i sp r o b l e ma n ds h o u l di s s u ea ne r r o rm e s s a g e . S E L E C Tl a s t n a m e ,f i r s t n a m e F R O M p e r s o n G R O U PB Yl a s t n a m e ; -Ah i n tt ou s e r so fM y S Q L : -T or e c e i c ec o r r e c tr e s u l t s( t h ee r r o rm e s s a g e )y o um u s td e a c t i v a t eas p e c i a lp e r f o r m a n c ef e a t u r eb yi s s u et h ec o m m a n d -s e ts q l _ m o d e=' O N L Y _ F U L L _ G R O U P _ B Y ' ;o rs e ti ti nt h ew o r k b e n c ho ri nt h ei n i f i l e .
Nevertheless we can get information about the non-criterion-columns. But this information is more generalised. The DBMS offers a special group of functions which builds one value out of a set of rows. Consider the avg() function, which computes the arithmetic mean of numerical values. This function receives a columnname and operates on a set of rows. If our command in question contains a GROUP BY clause, the avg() function does compute one value per group - not one value per all rows as usual. So it is possible to show the result of such functions together with the values of the 'criterion'-column. Here is an - incomplete - list of such functions: count(), max(), min(), sum(), avg(). Not all functions are of that kind, e.g. the function concat(), which concatenates two strings, operates on single rows and creates one value per row.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
34/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
S E L E C Tl a s t n a m e F R O M p e r s o n G R O U PB Yl a s t n a m e -g r o u p i n go v e rl a s t n a m e H A V I N GC O U N T ( * )>1 ;-m o r et h a no n ep e r s o nw i t h i nt h eg r o u p
All families with one member are no longer part of the result. In a second example we focus on such groups which satifies a criterion on column firstname. Consider that firstname is not the grouping-column.
The result shows the 5 families Baker, de Winter, Goldstein, Rich and Stefanos (, but not the row(s) with the long firstname). Please note that this result is very different from the similar question to persons whose firstname has more than 4 characters:
Where is the additional row coming from? In the family de Winter there are two persons with a firstname longer than 4 characters: James and Victor. Because in the command without GROUP BY we select for persons and not for families, both rows are displayed individually. In summary we can say that the HAVING clause decides, which groups are part of the result set and which are not.
-T h i si st h eo b l i g a t o r yo r d e ro fc l a u s e s S E L E C T. . . F R O M . . . W H E R E . . . G R O U PB Y. . . H A V I N G . . . O R D E RB Y. . . ;
As mentioned the WHERE clause works on the row-level whereas the HAVING clause works on the group-level. First the WHERE is evaluated, next the GROUP BY, next the HAVING, next the ORDER BY and at the end the SELECT. Every step is based on the results of the previous one. Finally we offer two additional examples:
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
35/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Exercises
Are there persons born on the same day in the same city? Hint: group over both criteria Click to see solution
S E L E C Td a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h F R O M p e r s o n G R O U PB Yd a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h H A V I N G C O U N T ( * )>1 ;
Categorise persons according to the formula: 'round (weight / 10)': 10 to 19 kg --> 1, 20 to 29 kg --> 2, ... How much persons exist in each category? Click to see solution
S E L E C Tr o u n d( w e i g h t/1 0 ) ,C O U N T ( * ) F R O M p e r s o n G R O U PB Yr o u n d( w e i g h t/1 0 ) -O R D E RB Yr o u n d( w e i g h t/1 0 ) -o r d e rb yc a t e g o r y O R D E RB YC O U N T ( * ) -o r d e rb yf r e q u e n c y ;
Which contact type is used in which frequency in table contact? Click to see solution
S E L E C Tc o n t a c t _ t y p e ,C O U N T ( * ) F R O M c o n t a c t G R O U PB Yc o n t a c t _ t y p e -O R D E RB Yc o n t a c t _ t y p e -o r d e rb yc o n t a c t _ t y p e O R D E RB YC O U N T ( * ) -o r d e rb yf r e q u e n c y ;
Restrict previous result to contact types which occurs more than once. Click to see solution
S E L E C Tc o n t a c t _ t y p e ,C O U N T ( * ) F R O M c o n t a c t G R O U PB Yc o n t a c t _ t y p e H A V I N G C O U N T ( * )>1 -o r d e rb yc o n t a c t _ t y p e -o r d e rb yc o n t a c t _ t y p e O R D E RB YC O U N T ( * ) -o r d e rb yf r e q u e n c y ;
Are there persons performing more than 2 hobies? Hint: check table person_hobby. Click to see solution
S E L E C Tp e r s o n _ i d ,C O U N T ( * ) F R O M p e r s o n _ h o b b y G R O U PB Yp e r s o n _ i d H A V I N G C O U N T ( * )>2 ;
Are there persons performing only one hobby? Click to see solution
S E L E C Tp e r s o n _ i d ,C O U N T ( * ) F R O M p e r s o n _ h o b b y G R O U PB Yp e r s o n _ i d H A V I N G C O U N T ( * )=1 ;
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
When creating new rows it may occur that we don't know the value of one or more columns. Let's assume that we want to store informations about banking accounts and for one of those accounts we don't know the balance. What can we do? There are several possibilities: Reject the whole row with all other informations like account number, dispositional credit, interest rate, ... . Not very attractive. Store a default value instead of the value we acually don't know. But there are cases where it is impossible to define a default value because every value is possible, e.g. a bank account of '0' or '-1' is not unusual. Store a flag that signals that no value is stored. Relational DBMS uses the last mentioned technique and the sense of the flag is 'there is no value stored'. Sometimes people say 'The NULL value is stored'.
S E L E C T. . . F R O M . . . W H E R E < c o l u m n n a m e >I SN U L L . . . ;
We must use exactly this wording. The use of any arithmetic operator like >, <=, !=, ... will not retrieve rows with the NULL value. The same holds true even for the condition '(balance = 0) OR NOT (balance = 0)', which is a tautology in conventional true/false logic. Beside this IS NULL predicate there is no other way to retrieve the NULL values - without one simple but not helpfull exception: if you omit the WHERE condition, all rows of the table are retrieved, with and without NULL values in any column. That's all! Dealing with NULL values and the 3-value-logic might sound strange if you first met this topic. But as the IS NULL predicate evaluates always to true or false everything works as usual afterwards. We can use all other elements of the SELECT command (boolean logic, join, having, order by, ...) in the same way we have done so far.
Some Examples
Our test database does not contain NULL values. Nevertheless we have met the situation during the explanation of OUTER joins. OUTER joins create resulting rows where some columns contain the NULL value. We must consider this possibility, if we deal with the results of such subselects. There are two other ways to generate NULL values. INSERT or UPDATE command with the explicit notion of the NULL value. In this case the SQL key word null is used as a representative for the NULL value. INSERT command without using all columns. The omitted columns will get the NULL value - or a default, if one is defined. To demonstrate this and to create some examples for the following excercises, we put one row into the person table with some columns left empty.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 37/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
-I n s e r tan e wr o wf o rt e s t i n gp u r p o s e I N S E R TI N T Op e r s o n( i d ,f i r s t n a m e ,l a s t n a m e ) V A L U E S( 5 1 ,' H a l fm a n ' ,' U n c o m p l e t e ' ) ; C O M M I T ; -R e t r i e v et h er o w .A sd e f i n e di nC R E A T ET A B L Es t a t e m e n tt h ew e i g h th a sad e f a u l tv a l u eo fi n t e g e r0 . -D a t e _ o f _ b i r t ha n dp l a c e _ o f _ b i r t hc o n t a i nt h eN U L Lv a l u e . S E L E C T*F R O Mp e r s o nW H E R E i d=5 1 ; -u s et h eI SN U L Lp r e d i c a t ew i t h i nW H E R Ec l a u s e .T h er e s u l tc o n t a i n s1r o w . S E L E C T*F R O Mp e r s o nW H E R Es s nI SN U L L ; -w e i g h th a sav a l u e ! !W ee x p e c tt or e t r i e v en or o w sw h e nw eu s et h eI SN U L Lp r e d i c a t e . S E L E C T*F R O Mp e r s o nW H E R Ew e i g h tI SN U L L ; -o r ,t os a yi tt h eo t h e rw a yr o u n d ,t h en u m b e ro fr o w si s0 S E L E C TC O U N T ( * )F R O Mp e r s o nW H E R Ew e i g h tI SN U L L ; -b u ti nt h en e x ts t a t e m e n tt h en u m b e ro fr o w si s1 S E L E C TC O U N T ( * )F R O Mp e r s o nW H E R Ew e i g h t=0 ; -N e g a t et h eI SN U L Lp r e d i c a t e S E L E C TC O U N T ( * )F R O Mp e r s o nW H E R Es s nI SN U L L ; -I SN U L L S E L E C TC O U N T ( * )F R O Mp e r s o nW H E R Es s nI SN O TN U L L ;-N e g a t i o no fI SN U L L S E L E C TC O U N T ( * ) F R O M p e r s o n W H E R E s s nI SN U L L O R s s nI SN O TN U L L ;-At a u t o l o g y ,w h i c ha l w a y sr e t r i e v e sA L Lr o w so fat a b l e -S a m ea sa b o v e S E L E C TC O U N T ( * ) F R O M p e r s o n W H E R E s s nI SN U L L O RN O Ts s nI SN U L L ;-At a u t o l o g y ,w h i c ha l w a y sr e t r i e v e sA L Lr o w so fat a b l e
Next we show the use of the UPDATE command in combination with the NULL value
-I n s e r tan e wr o wf o rt e s t i n gp u r p o s ew i t ha l lc o l u m n sf i l l e dw i t hau s e f u l lv a l u e I N S E R TI N T Op e r s o n( i d ,f i r s t n a m e ,l a s t n a m e , d a t e _ o f _ b i r t h , p l a c e _ o f _ b i r t h ,s s n , w e i g h t ) V A L U E S ( 5 2 ,' L y n ' , ' M u t a b l e ' ,D A T E ' 1 9 5 1 0 5 1 3 ' ,' A n c h o r a g e ' , ' 0 7 8 0 5 1 1 5 2 ' ,6 9 ) ; C O M M I T ; S E L E C T*F R O Mp e r s o nW H E R Ei d=5 2 ; -D e l e t eas i n g l ec o l u m nv a l u e( n o tt h ec o m p l e t er o w ) U P D A T Ep e r s o nS E Ts s n=N U L LW H E R Ei d=5 2 ; C O M M I T ; S E L E C T*F R O Mp e r s o nW H E R Ei d=5 2 ; -o n er o w S E L E C T*F R O Mp e r s o nW H E R Es s nI SN U L L ; -t w or o w s :5 1+5 2
D E L E T EF R O Mp e r s o nW H E R Ei d>5 0 ; C O M M I T ;
The function name coalesce results from the fact that the function accepts an arbitrary number of parameters and evaluates them in a recursive manner. If parameter n results in a not NULL value, it evaluates to this parameter, else the function calls itself without the n-th parameter. coalesce(expression_1, expression_2, expression_3) evaluates to expression_1, if expression_1 is not NULL, else to expression_2, if expression_2 is not NULL, else to expression_3.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 38/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The SQL standard defines another function nullif(<expression_1>, <expression_2>). It evaluates to NULL, if the two expressions are equal - and it evaluates to the first expression, if they differ from each other. Different vendors offers some more functions like isnull(), ifnull() or nvl() to support handling of NULL values. The meaning of this functions is vendor specific.
Exercises
Insert a new hobby 'Snowshoeing' without a remark. Click to see solution
I N S E R TI N T Oh o b b y( i d ,h o b b y n a m e , r e m a r k ) V A L U E S ( 1 0 ,' S n o w s h o e i n g ' ,N U L L ) ; C O M M I T ;
Find a second solution for the above question without using the key word 'null'. (First delete row 10.) Click to see solution
D E L E T EF R O Mh o b b yW H E R Ei d=1 0 ; I N S E R TI N T Oh o b b y( i d ,h o b b y n a m e ) V A L U E S ( 1 0 ,' S n o w s h o e i n g ' ) ; C O M M I T ;
How many hobbies are exemplified with a remark? Click to see solution
-9r o w s S E L E C TC O U N T ( * )F R O Mh o b b yW H E R Er e m a r kI SN O TN U L L ;
Change row 10 of hobby in the way that the hobbname contains the string 'NULL' and the remark 'Name of hobby not known'. Click to see solution
-C o n s i d e rt h et w oa p o s t r o p h e ss u r r o u n d i n gt h es t r i n g' N U L L ' ,w h i c hc o n s i s t so ft h e4c h a r a c t e r sN ,U ,La n dL! ! U P D A T Eh o b b yS E Th o b b y n a m e=' N U L L ' ,r e m a r k=' N a m eo fh o b b yn o tk n o w n 'W H E R Ei d=1 0 ; C O M M I T ;
a) Retrieve the row where hobbyname is 'NULL'. b) Retrieve the row where remark is 'Name of hobby not known'. Click to see solution
-T h i sm a yb eap i t f a l lq u e s t i o n .T h e r ei sn or e l a t i o nt ot h eI SN U L Lp r e d i c a t e S E L E C T*F R O Mh o b b yW H E R Eh o b b y n a m e=' N U L L ' ; S E L E C T*F R O Mh o b b yW H E R Er e m a r k=' N a m eo fh o b b yn o tk n o w n ' ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
39/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
There are two groups of predefined functions: aggregate functions . They work on a set of rows, which means they receive one value for each row of a set of rows and returns one value for the whole set. If they are called in the context of a GROUP BY clause, they are called once per group, else once for all rows. scalar functions . They work on single rows, which means they receive one value of a single row and returns one value for each of them.
Aggregate functions
They work on a set of rows and return one single value like the number of rows, the highest or lowest value, the standard deviation, etc. The most important aggregate functions are: Signatur
C O U N T ( * ) C O U N T ( < c o l u m n n a m e > ) M I N ( < c o l u m nn a m e > ) M A X ( < c o l u m nn a m e > ) S U M ( < c o l u m nn a m e > ) A V G ( < c o l u m nn a m e > )
Semantic The number of rows The number of rows where <column name> contains a value (is not NULL). The elimination of NULL values applies to all aggregate functions. Lowest value. In the case of strings according to the sequence of characters. Highest value. In the case of strings according to the sequence of characters. Sum of all values Arithmetic mean
S E L E C TM A X ( w e i g h t ) F R O M p e r s o n ;
A Word of Caution Aggregate functions result in one value for a set of rows. Therefore it is not possible to use them together with 'normal' columns in the projection (the part behind SELECT key word). If we specify, for example,
S E L E C Tl a s t n a m e ,S U M ( w e i g h t ) F R O M p e r s o n ;
we try to instruct the DBMS to show a lot of rows containing the lastname simultaneously with one value. This is a contradiction and the system will throw an exception. We can use a lot of aggregate functions within one projection but we are not allowed to use them together with 'normal' columns.
-M u l t i p l ea g g r e g a t ef u n c t i o n s .N o' n o r m a l 'c o l u m n s . S E L E C TS U M ( w e i g h t ) / C O U N T ( w e i g h t )A Sa v e r a g e _ 1 ,A V G ( w e i g h t )A Sa v e r a g e _ 2 F R O M p e r s o n ;
Grouping If we use aggregate functions in the context of commands containing a GROUP BY, the aggregate functions are called once per group.
-N o to n l yo n er e s u l t i n gr o w ,b u to n er e s u l t i n gr o wp e rl a s t n a m et o g e t h e rw i t ht h ea v e r a g ew e i g h to fa l lr o w sw i t ht h i sl a s t n a m e . S E L E C TA V G ( w e i g h t ) F R O M p e r s o n G R O U PB Yl a s t n a m e ;
In such cases the GROUP BY column(s) may be displayed as it is impossible that they change within the group.
-T h el a s t n a m em a yb es h o w na si ti st h eG R O U PB Yc r i t e r i a S E L E C Tl a s t n a m e ,A V G ( w e i g h t ) F R O M p e r s o n G R O U PB Yl a s t n a m e ;
NULL value
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 40/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
If a row contains no value (which is the NULL value) in the named column, the row is not part of the computation.
-I fs s ni sN U L L ,t h i sr o ww i l ln o tc o u n t . S E L E C TC O U N T ( s s n ) F R O M p e r s o n ;
Hint
The standard defines some more aggregate functions to compute statistical messures. Also the keywords ANY, EVERY and SOME formally are defined as aggregate functions. We will discuss them on a separate page.
Scalar functions
Scalar functions act on a 'per row basis'. They are called once per row and they return one value per call. Often they are grouped according to the data types they act on: String functions SUBSTRING(<column name> FROM <pos> FOR <len>) returns a string starting at position <pos> (first character counts '1') in the length of <len>. UPPER(<column name>) returns the uppercase equivalent of the column value. LOWER(<column name>) returns the lowercase equivalent of the column value. CHARACTER_LENGTH(<column name>) returns the length of the column value. TRIM(<column name>) returns the column value without leading and trailing spaces. TRIM(LEADING FROM <column name>) returns the column value without leading spaces. TRIM(TRAILING FROM <column name>) returns the column value without trailing spaces. Numeric functions SQRT(<column name>) returns the square root of the column value. ABS(<column name>) returns the absolute value of the column value. MOD(<column name>, <divisor>) returns the remaining of column value divided by divisor. others: FLOOR, CEIL, POWER, EXP, LN. Date, Time & Interval functions EXTRACT(month FROM date_of_birth) returns the month of column date_of_birth. build-in functions. They do not have any input parameter. CURRENT_DATE() returns the currente date. CURRENT_TIME() returns the currente time. There is another wikibook where those functions are shown in detail. The data type of the return value is not always identical to the type of the input, e.g. 'character_length()' receives a string and returns a number. Here is an example with some scalar functions:
S E L E C TL O W E R ( f i r s t n a m e ) ,U P P E R ( l a s t n a m e ) ,C O N C A T ( ' t o d a yi s :' ,C U R R E N T _ D A T E ) F R O M p e r s o n ;
Exercises
What is the hightest id used so far in the hobby table?
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 41/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Which lastname will occur first in an ordered list? Click to see solution
S E L E C TM I N ( l a s t n a m e ) F R O M p e r s o n ;
Are there aggregate functions where it makes no difference to use the ALL or the DISTINCT key word? Click to see solution
Y e s .m i n ( A L L< c o l u m nn a m e > )l e a d st ot h es a m er e s u l ta sm i n ( D I S T I N C T< c o l u m nn a m e > )a s i tm a k e sn od i f f e r e n c ew h e t h e rt h es m a l l e s tv a l u eo c c u r so n eo rm o r et i m e s .T h es a m ei st r u ef o rm a x ( ) .
Show persons with a short firstname (up to 4 characters). Click to see solution
-W ec a nu s ef u n c t i o n sa sp a r to ft h eW H E R Ec l a u s e . S E L E C T* F R O M p e r s o n W H E R E C H A R A C T E R _ L E N G T H ( f i r s t n a m e )< =4 ;-H i n t :S o m ei m p l e m e n t a t i o n su s ead i f f e r e n tf u n c t i o nn a m e :l e n g t h ( )o rl e n ( ) .
Show firstname, lastname and the number of characters for the concatenated string. Find two different solutions. You may use the character_length() function to compute the length of strings and the concat() function to concatenate strings. Click to see solution
-A d d i t i o no ft h ec o m p u t e dl e n g t h .H i n t :S o m ei m p l e m e n t a t i o n su s ead i f f e r e n tf u n c t i o nn a m e :l e n g t h ( )o rl e n ( ) . S E L E C Tf i r s t n a m e ,l a s t n a m e ,C H A R A C T E R _ L E N G T H ( f i r s t n a m e )+C H A R A C T E R _ L E N G T H ( l a s t n a m e ) F R O M p e r s o n ; -l e n g t ho ft h ec o n c a t e n a t e ds t r i n g S E L E C Tf i r s t n a m e ,l a s t n a m e ,C H A R A C T E R _ L E N G T H ( c o n c a t( f i r s t n a m e ,l a s t n a m e ) ) F R O M p e r s o n ; -s h o wb o t hs o l u t i o n st o g e t h e r S E L E C Tf i r s t n a m e ,l a s t n a m e , C H A R A C T E R _ L E N G T H ( f i r s t n a m e )+C H A R A C T E R _ L E N G T H ( l a s t n a m e )A SL 1 , C H A R A C T E R _ L E N G T H ( c o n c a t( f i r s t n a m e ,l a s t n a m e ) )A SL 2 F R O M p e r s o n ;
Tables, views and results of SELECT commands are in somewhat similar to sets of set theory. In this comparision the elements of sets correspond to rows of tables, views and SELECT results. The differences between set theory and the itemized SQL constructs are: Sets of set theory do not allow duplicates whereas SQL allows duplicates. (Even different rows of one table may be identical as there is no duty to use the concept of primary keys.) In the following we use the term multiset when we speak about sets in SQL where duplicates are possible. Sets of set theory and multisets are not ordered. But for the result of a SELECT command we can enforce an ordering by means of the optional ORDER BY clause. The comparision between set theory and SQL goes even further. In SQL we have operations which acts on multisets in the sense of set theory: The SQL operations UNION, INTERSECT and EXCEPT (some name it MINUS) process intermediate multisets generated by differents SELECT commands. The operations expect the multisets are of the same type. This means mainly that they must have the same number of columns. Also their data type should correlate, but this is not mandatory. If they do not, the DBMS will cast them to a common data type - if possible.
UNION
The UNION operation pushs the result of several SELECT commands together. The result of the UNION contains those values, which are in the first or in the second intermediate result.
-P l e a s ec o n s i d e rt h a tt h i si so n l yo n ec o m m a n d( o n l yO N Es e m i c o l o na tt h ev e r ye n d ) S E L E C Tf i r s t n a m e -f i r s tS E L E C Tc o m m a n d F R O M p e r s o n
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
42/110
4/2/2014
U N I O N S E L E C Tl a s t n a m e F R O M p e r s o n ;
Structured Query Language/Print version - Wikibooks, open books for an open world
-p u s hb o t hi n t e r m e d i a t er e s u l t st o g e t h e rt oo n er e s u l t -s e c o n dS E L E C Tc o m m a n d
This is a single SQL command. It consists of two SELECTs and one UNION operation. The SELECTs are evaluated first. Afterwards their results are pushed together to one single result. In our example the result contains all lastnames and firstnames in a single column (our example may be of limited help in praxis, it's only a demonstration for the UNION). DISTINCT / ALL The UNION of If we examine the result closely, we will notice that it consists only of 17 values. The table person contains ten rows so that we probably two intermediate expect twenty values in the result. If we perform the 'SELECT firstname ...' and 'SELECT lastname ...' as separate commands without the results UNION, we receive for both commands 10 values. The explanation for the 3 missing values is the UNION command. It behaves by default that it removes duplicates. Therefore some of the intermediate values are skipped. If we want to obtain this duplicate values we have to extent the UNION. It can be widen with one of the two key words DISTINCT or ALL. DISTINCT is the default and its behaviour is the removal of duplicate values which we have seen before. ALL leads to the retention of all values, independent whether they appeared before or not.
A hint for Oracle users: The use of the key word DISTINCT, which is the default, is not accepted by Oracle. Omit it. General hint In most cases the UNION combines SELECT commands on different tables or on different columns of the same table. SELECT commands on the same column of a single table usually use the WHERE clause in combination with boolean logic.
-Av e r yu n u s u a le x a m p l e .P e o p l ea p p l ys u c hq u e r y so nt h es a m et a b l eo n l yi nc o m b i n a t i o nw i t hv e r yc o m p l e xW H E R Ec o n d i t i o n s . -T h i se x a m p l ew o u l dn o r m a l l ye x p r e s s e dw i t hap h r a s i n gs i m i l a rt o :W H E R El a s t n a m eI N( ' d eW i n t e r ' ,' G o l d s t e i n ' ) ; S E L E C T* F R O M p e r s o n W H E R E l a s t n a m e=' d eW i n t e r ' U N I O NA L L S E L E C T* F R O M p e r s o n W H E R E l a s t n a m e=' G o l d s t e i n ' ;
INTERSECT
The INTERSECT operation evaluates to those values, which are in both intermediate results, in the first as well as in the second.
INTERSECT
-A si no u re x a m p l ed a t a b a s et h e r ei sn oe x a m p l ef o rt h eI N T E R S E C Tw ei n s e r tan e wp e r s o n . -T h i sp e r s o nh a st h es a m el a s t n a m e' V i c t o r 'a st h ef i r s tn a m eo fa n o t h e rp e r s o n . I N S E R TI N T Op e r s o nV A L U E S( 2 1 ,' P a u l ' ,' V i c t o r ' ,D A T E ' 1 9 6 6 0 4 0 2 ' ,' W a s h i n g t o n ' ,' 0 7 8 0 5 1 1 2 1 ' ,6 6 ) ; C O M M I T ; -A l lf i r s t n a m e sw h i c ha r eu s e da sl a s t n a m e . S E L E C Tf i r s t n a m e -f i r s tS E L E C Tc o m m a n d F R O M p e r s o n I N T E R S E C T -l o o k i n gf o rc o m m o nv a l u e s S E L E C Tl a s t n a m e -s e c o n dS E L E C Tc o m m a n d F R O M p e r s o n ;
A hint to MySQL users: MySQL (5.5) does not support INTERSECT operation. But as it is not an elementary operation, there are workarrounds.
EXCEPT
The EXCEPT operation evaluates to those values, which are in the first intermediate result but not in the second.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
43/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
EXCEPT
A hint to MySQL users: MySQL (5.5) does not support the EXCEPT operation. But as it is not an elementary operation, there are workarrounds. A hint to Oracle users: Oracle use the key word MINUS instead of EXCEPT.
-C l e a nu pt h ee x a m p l ed a t a b a s e D E L E T EF R O Mp e r s o nW H E R Ei d>1 0 ; C O M M I T ;
Order By
We can combine set operations with all other elements of SELECT command, in particular with ORDER BY and GROUP BY. But this may lead to some uncertainties. Therefore, we would like to explain some of the details below.
S E L E C Tf i r s t n a m e -f i r s tS E L E C Tc o m m a n d F R O M p e r s o n U N I O N -p u s hb o t hi n t e r m e d i a t er e s u l t st o g e t h e rt oo n er e s u l t S E L E C Tl a s t n a m e -s e c o n dS E L E C Tc o m m a n d F R O M p e r s o n O R D E RB Yf i r s t n a m e ;
To which part of the command belongs the ORDER BY? To the first SELECT, to the second SELECT or to the result of the UNION? The SQL rules determine, that set operations are evaluated before ORDER BY clauses (as always parenthesis can change the order of evaluation). Therefore the ORDER BY sorts the final result and not any of the intermediate results. We rearrange the example in the hope that things get clear.
First the two SELECTS are evaluated, afterwareds the UNION. This intermediate result gets the name 't'. 't' is ordered. Often one would like to achieve that the rows from the first SELECT are ordered independent from those of the second SELECT. We can do this by adding a virtuel column to the result of both SELECTs.
Group By
With the GROUP BY clause things are little more complicated than with ORDER BY. The GROUP BY refers to the last SELECT or - to say it the other way round - to the SELECT of its direct level.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 44/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Exercises
Show the lowest, highest and mean weight as a) 3 values of 1 row and b) 1 value in 3 rows. Click to see solution
-1r o w S E L E C TM I N ( w e i g h t ) ,M A X ( w e i g h t ) ,a v g ( w e i g h t ) F R O M p e r s o n ; -3r o w s S E L E C TM I N ( w e i g h t ) F R O M p e r s o n U N I O N S E L E C TM A X ( w e i g h t ) F R O M p e r s o n U N I O N S E L E C Ta v g ( w e i g h t ) F R O M p e r s o n ;
Extend the previous 3-rows-solution to meet two additional criteria: a) consider only persons born in San Francisco and b) add a virtual column to show 'Min', 'Max' and 'Avg' according to the correlating numeric values. Click to see solution
S E L E C T' M i n ' ,M I N ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T' M a x ' ,M A X ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T' A v g ' ,a v g ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' ;
Extend the previous solution to order the result: the minimum value first, followed by the average and then the highest value. Click to see solution
-' u g l y 's o l u t i o n S E L E C T' 1M i n 'A Sn o t e ,M I N ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T' 3M a x 'A Sn o t e ,M A X ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T' 2A v g 'A Sn o t e ,a v g ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' O R D E RB Yn o t e ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
45/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
-' c l e a n 's o l u t i o n S E L E C T1A Sn o t e ,' M i n ' ,M I N ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T3A Sn o t e ,' M a x ' ,M A X ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' U N I O N S E L E C T2A Sn o t e ,' A v g ' ,a v g ( w e i g h t ) F R O M p e r s o n W H E R E p l a c e _ o f _ b i r t h=' S a nF r a n c i s c o ' O R D E RB Yn o t e ;
Create a list of lastnames for persons with a weight greater than 70 kg together with all e-mail values (one value per row). There is no concordance between lastnames and e-mails. (This example is not very helpfull for praxis, but instructive.) Click to see solution
S E L E C Tl a s t n a m e F R O M p e r s o n W H E R E w e i g h t>7 0 U N I O N S E L E C Tc o n t a c t _ v a l u e F R O M c o n t a c t W H E R E c o n t a c t _ t y p e=' e m a i l ' ;
In the previous example the lastname 'de Winter' is shown only once. But there are more than one persons of the family with a weight greater than 70 kg. Why? Extend the previous solution to show as much resulting rows as hits to the criteria. Click to see solution
-E x t e n d' U N I O N 't o' U N I O NA L L ' .T h ed e f a u l ti s' U N I O ND I S T I N C T ' S E L E C Tl a s t n a m e F R O M p e r s o n W H E R E w e i g h t>7 0 U N I O NA L L S E L E C Tc o n t a c t _ v a l u e F R O M c o n t a c t W H E R E c o n t a c t _ t y p e=' e m a i l ' ;
Sometimes it's necessary to translate stored values (or values to be stored) from one representation to another. Suppose there is a column status with legal values from 0 to 9 but the end-users should receive strings which explain the meaning of the numeric values in short, eg.: 'ordered', 'delivered', 'back delivery', 'out of stock', ... . The recommended way to do this is a separate table where the numeric values maps to the explanatory strings. Notwithstanding this, application developers may favor a solution within an application server. The CASE expression, which is shown on this page, is a technique for solving the described situation as part of a SELECT, INSERT or UPDATE command as well as solving additional problems. As part of the language it's a powerful term which can be applied at plenty places within SQL commands. On this page we focus on its use together with the SELECT command. The strategy and syntax for CASE within INSERT and UPDATE are equivalent and are presented over there. In comparison with the recommended technique of a separate table for the translation the CASE expression is much more flexible (which is not an advantage in all cases).
Two Examples
-T e c h n i c a lt e r m :" s i m p l ec a s e " -S e l e c ti d ,c o n t a c t _ t y p ei nat r a n s l a t e dv e r s i o na n dc o n t a c t _ v a l u e S E L E C Ti d , C A S Ec o n t a c t _ t y p e W H E N' f i x e dl i n e 'T H E N' P h o n e ' W H E N' m o b i l e ' T H E N' P h o n e ' E L S E ' N o tat e l e p h o n en u m b e r ' E N D , c o n t a c t _ v a l u e F R O M c o n t a c t ;
The CASE expression is introduced with its key word CASE and runs up to the END key word. In this first example it specifies a column name and a series of WHEN/THEN clauses with an optional ELSE clause. The WHEN/THEN clauses are compared and evaluated against the values of the named column, one after the other. If non of them hits, the ELSE clause applies. If there is no ELSE clause and non of the WHEN/THEN clauses hit, the NULL value will be applied.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
46/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The comparison between the values of the column and the fixed values within the WHEN/THEN clause is done solely by "=" (equals). This is a good starting point, but real applications need more than that. Therefore there is a variant of the CASE.
-T e c h n i c a lt e r m :" s e a r c h e dc a s e " -S e l e c tp e r s o n sn a m e ,w e i g h ta n dad e n o m i n a t i o no ft h ew e i g h t S E L E C Tf i r s t n a m e , l a s t n a m e , w e i g h t , C A S E W H E N( w e i g h tI SN U L LO Rw e i g h t=0 )T H E N' w e i g h ti su n k n o w n ' W H E Nw e i g h t<4 0 T H E N' l i g h t w e i g h t ' W H E Nw e i g h tB E T W E E N4 0A N D8 5 T H E N' m e d i u m ' E L S E ' h e a v y w e i g h t ' E N D F R O M p e r s o n ;
The crucial point is the direct succession of the two key words CASE and WHEN. There is no column name between them. In this variant there must be a complete expression, which evaluates to one of the 3-value-logic terms true, false or unknown, between each WHEN and THEN. Now it is possible to use all the comparisons and boolean operators as they are known by the WHERE clause. It is even possible to compare different columns or function calls with each other.
Syntax
There are the two variants simple case and searched case.
-" s i m p l ec a s e "p e r f o r m ss u c c e s s i v ec o m p a r i s o n su s i n gt h ee q u a lo p e r a t o r :< c o l u m n _ n a m e >=< e x p r e s s i o n _ x > C A S E< c o l u m n _ n a m e > W H E N< e x p r e s s i o n _ 1 >T H E N< r e s u l t _ 1 > W H E N< e x p r e s s i o n _ 2 >T H E N< r e s u l t _ 2 > . . . E L S E < d e f a u l t _ r e s u l t > -o p t i o n a l E N D -" s e a r c h e dc a s e "i sr e c o g n i s e db y' n o t h i n g 'b e t w e e nC A S Ea n df i r s tW H E N C A S E W H E N< c o n d i t i o n _ 1 >T H E N< r e s u l t _ 1 > W H E N< c o n d i t i o n _ 2 >T H E N< r e s u l t _ 2 > . . . E L S E < d e f a u l t _ r e s u l t > -o p t i o n a l E N D
The simple case is limited to one column and the use of the equal operator whereas the searched case may evaluate arbitrary columns of the (intermediate) result with arbitrary operators, functions or predicates.
S E L E C T* F R O M c o n t a c t O R D E R B Y -a" s i m p l ec a s e "c o n s t r u c ta ss u b s t i t u t i o nf o rac o l u m nn a m e C A S Ec o n t a c t _ t y p e W H E N' f i x e dl i n e 'T H E N0 W H E N' m o b i l e ' T H E N1 W H E N' e m a i l ' T H E N2 W H E N' i c q ' T H E N3 E L S E 4 E N D , c o n t a c t _ v a l u e ;
In the next example persons are ordered by weight classes, within the classes by their name.
-o r d e rb yw e i g h tc l a s s e s S E L E C Tf i r s t n a m e ,l a s t n a m e ,w e i g h t , C A S E
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
47/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
W H E N( w e i g h tI SN U L LO Rw e i g h t=0 )T H E N' w e i g h ti su n k n o w n ' W H E Nw e i g h t<4 0 T H E N' l i g h t w e i g h t ' W H E Nw e i g h tB E T W E E N4 0A N D8 5 T H E N' m e d i u m ' E L S E ' h e a v y w e i g h t ' E N D F R O M p e r s o n O R D E R B Y -a" s e a r c h e dc a s e "c o n s t r u c tw i t hI SN U L L ,B E T W E E Na n d' l e s st h a n ' . C A S E W H E N( w e i g h tI SN U L LO Rw e i g h t=0 )T H E N0 W H E Nw e i g h t<4 0 T H E N1 W H E Nw e i g h tB E T W E E N4 0A N D8 5 T H E N2 E L S E 3 E N D ,l a s t n a m e ,f i r s t n a m e ;
WHERE clause Within the WHERE clauses there may occur fixed values or column names. CASE expressions can be used as a substitution for them. In the example persons receive a discount on their weight depending on their place of birth (consider it as a theoretical example). Thus Mr. Goldstein with its 95 kg counts only with 76 kg and is not part of the result set.
Exercises
Show firstname, lastname and the gender of all persons. Consider Larry, Tom, James, John, Elias, Yorgos, Victor as 'male', Lisa as 'female' and all others as 'unknown gender'. Use a simple case expression. Click to see solution
S E L E C Tf i r s t n a m e ,l a s t n a m e , C A S Ef i r s t n a m e W H E N' L a r r y ' T H E N' m a l e ' W H E N' T o m ' T H E N' m a l e ' W H E N' J a m e s ' T H E N' m a l e ' W H E N' J o h n ' T H E N' m a l e ' W H E N' E l i a s ' T H E N' m a l e ' W H E N' Y o r g o s ' T H E N' m a l e ' W H E N' V i c t o r ' T H E N' m a l e ' W H E N' L i s a ' T H E N' f e m a l e ' E L S E ' u n k n o w ng e n d e r ' E N D F R O M p e r s o n ;
Use a searched case expression to solve the previous question. Click to see solution
S E L E C Tf i r s t n a m e ,l a s t n a m e , C A S E W H E Nf i r s t n a m eI N( ' L a r r y ' ,' T o m ' ,' J a m e s ' ,' J o h n ' ,' E l i a s ' ,' Y o r g o s ' ,' V i c t o r ' ) T H E N' m a l e ' W H E Nf i r s t n a m e=' L i s a ' T H E N' f e m a l e ' E L S E ' u n k n o w ng e n d e r ' E N D F R O M p e r s o n ;
Show firstname, lastname and a classification of all persons. Classify persons according to the length of their firstname. Call the class 'short name' if character_length(firstname) < 4, 'medium length' if < 6, 'long name' else. Click to see solution
-H i n t :S o m ei m p l e m e n t a t i o n su s ead i f f e r e n tf u n c t i o nn a m e :l e n g t h ( )o rl e n ( ) . S E L E C Tf i r s t n a m e ,l a s t n a m e , C A S E
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
48/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
W H E NC H A R A C T E R _ L E N G T H ( f i r s t n a m e )<4T H E N' s h o r tn a m e ' W H E NC H A R A C T E R _ L E N G T H ( f i r s t n a m e )<6T H E N' m e d i u ml e n g t h ' E L S E ' l o n gn a m e ' E N D p e r s o n ;
F R O M
Count the number of short, medium and long names of the above exercise. Click to see solution
-H i n t :S o m ei m p l e m e n t a t i o n su s ead i f f e r e n tf u n c t i o nn a m e :l e n g t h ( )o rl e n ( ) . S E L E C TS U M ( C A S E W H E NC H A R A C T E R _ L E N G T H ( f i r s t n a m e )<4T H E N1 E L S E 0 E N D )A Ss h o r t _ n a m e s , S U M ( C A S E W H E NC H A R A C T E R _ L E N G T H ( f i r s t n a m e )B E T W E E N4A N D5T H E N1 E L S E 0 E N D )A Sm e d i u m , S U M ( C A S E W H E NC H A R A C T E R _ L E N G T H ( f i r s t n a m e )>5T H E N1 E L S E 0 E N D )A Sl o n g _ n a m e s F R O M p e r s o n ;
A subquery is a complete SELECT command which is used within another SELECT, UPDATE, INSERT or DELETE command. The only difference to a simple SELECT is, that it is enclosed in parenthesis.
Classification
Depending on the type of the created result there are three classes of subqueries: Scalar Value Subquery: The subquery returns one single value, e.g: ( S E L E C Tm a x ( w e i g h t )F R O Mp e r s o n ) . Row Subquery: The subquery returns one single row of one or more values, e.g: ( S E L E C Tm i n ( w e i g h t ) ,m a x ( w e i g h t )F R O Mp e r s o n ) . Table Subquery: The subquery returns a list of rows, which is a table, e.g: ( S E L E C Tl a s t n a m e ,w e i g h tF R O Mp e r s o n ) . For the classification it makes no difference whether the resulting list contains zero, one or more rows. The demarcation between a table subquery and a row subquery is that potentially more than one row may occur. Every type can be used on all positions where the type it stands for may occur: the scalar value subquery where a single value may occur, the row subquery where a single row may occur and the table subquery where a table may occur. Additionally table subqueries may occur as an argument of an EXISTS, IN, SOME, ANY or ALL predicate. Independent from this classification subqueries may be correlated subqueries or non-correlated subqueries. Correlated subqueries have a correlation to the surrounding query by the fact that they use values from the surrounding query within the subquery. Non-correlated subqueries are independent from the surrounding query. This distinction is shown in detail in the next chapter but applies also to the other two subquery classes. Because correlated subqueries use values, which are determined by the surrounding query and may change from row to row, the subquery is executed conceptional - as often as resulting rows of the surrounding query exist. This might lead to performance problems. Nevertheless correlated subqueries are an often used construct. In many cases exist equivalent constructs which use a JOIN. Which one shows the better performance depends highly on the DBMS, and the number of involved rows, the existence of indices and a lot more variables.
S E L E C Ti d , l a s t n a m e , w e i g h t , ( S E L E C Ta v g ( w e i g h t )F R O Mp e r s o n ) F R O M p e r s o n O R D E RB Yl a s t n a m e ;
-t h i si st h es u b q u e r y
Because the subquery uses the a v g ( )function, the SQL compiler knows that it will return exactly one single value. Therefore it's type is Scalar Value Subquery and can be used on positions where scalar values may occur, e.g. in the list between SELECT and FROM. In the next example the subquery is used as a deputy for a value within the WHERE clause.
-P e r s o n sw h ow e i g hm o r et h a nt h ea v e r a g eo fa l lp e r s o n s S E L E C Ti d ,l a s t n a m e ,w e i g h t F R O M p e r s o n W H E R E w e i g h t> =( S E L E C Ta v g ( w e i g h t )F R O Mp e r s o n ) -a n o t h e rp o s i t i o nf o rt h es u b q u e r y O R D E RB Yl a s t n a m e ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
49/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Both examples use the table person twice. Just as well one can use different tables. There is no dependency between the table name in the subquery and in the surrounding query. This applies to all classes of correlated and non-correlated subqueries. The subqueries may retrieve any value from any other table, e.g. the number of contacts. This first two examples show non-correlated subqueries, which means, that the subqueries are independent from the queries in which they are embedded. They are executed only once. But often an application faces a situation, where the subquery must use values from the outside query (similar to subroutines which uses parameters). This kind of subquery is called a correlated subquery. As an example the next query lists persons together with the average weight of their family.
The subselect gets one row of the surrounding SELECT after the next as an parameter with the name 'p'. Within the subselect all columns of the row 'p' are known and may be used. Here the family name from the outside row is used in the subquery to find all persons within the family and the average weight of the family members. Be careful: Correlated subqueries are executed once per row of the surrounding query. Therefore they are much more costly than non-correlated subqueries. There might exist an equivalent solution using JOIN or GROUP BY which works with better performance. The query optimizer of the DBMS internally might rearrange the given subquery into one of the equivalent forms. But this does not work in all cases. The distinction between correlated and non-correlated subqueries is universal. It applies also to the other subquery classes.
Row Subquery
This example retrieves one or more persons, whose firstname is the lowest (in the sense of the lexical order) of all firstnames and whose lastname is the lowest of all lastnames. Because of the AND condition it might be the case that no person is found.
-O n er e s u l t i n gr o w :E l i a sB a k e r S E L E C T* F R O M p e r s o n W H E R E ( f i r s t n a m e ,l a s t n a m e )=( S E L E C TM I N ( f i r s t n a m e ) ,M I N ( l a s t n a m e )F R O Mp e r s o n ) ;
Within the subquery the lowest first- and lastnames are retrieved. The use of the m i n ( )function garanties that not more than one row with two columns will arise therefore it is a row subquery. In the surrounding query this intermediate result is compared with each row of the complete table person or - if present - an index is used. It's a fortune that the command retrieves a row. In most cases the lowest first- and lastname results from different persons. But also in those cases the command is syntactically correct and will not throw any exception. In the next example persons with the lowest first- and lastnames within every family are retrieved. To do so, it is neccessary to use a correlated row subquery.
-7r o w s ,o n ep e rf a m i l y S E L E C T* F R O M p e r s o np W H E R E( f i r s t n a m e ,l a s t n a m e )= ( S E L E C TM I N ( f i r s t n a m e ) ,M I N ( l a s t n a m e )F R O Mp e r s o ns qW H E R Ep . l a s t n a m e=s q . l a s t n a m e ) ;
Again, there are the two incarnations of table person, one with the alias name 'p' in the surrounding query and one with the alias name 'sq' in the subquery. The subquery is called once per resulting row of the surrounding query, because the 'p.lastname' may change with every row of 'p'. Within every family there is as least one person which achievs the condition - it is also conceivable that several persons achiev the condition.
Table Subquery
The next example retrievs persons who have a hobby. The class of the subquery is: non-correlated table subquery (used as a condition in the IN predicate).
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
50/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
S E L E C T* F R O M p e r s o n W H E R E i dI N ( S E L E C Tp e r s o n _ i dF R O Mc o n t a c t ) ; -t h es u b q u e r y
The subquery creates multiple rows with one column for each of them. This constitutes a new, intermediate table. Therefore this example is a table subquery. The IN operator is able to act on this intermediate table. In contrast, it is not possible to use operators like '=' or '>' on this kind of intermediate result. In this cases the SQL compiler will recognize an syntax error. The next example is an extention of the first one. It adds a correlation criterion between the query and the subquery by requesting the lastname within an emailaddress.
The last comparision after the AND is a little bit complex. It uses the functions CONCAT() and UPPER() as well as the predicate LIKE, but this is not of interest for the actual topic 'subquery'. The important part is that the subquery refers to 'p.lastname' of the surrounding query. Only Mr. Goldstein meets the criterion that his e-mail address contains his lastname when the two columns are compared case-insensitive. Remark: CONCAT() concatenates two strings. UPPER() converts a string to upper-case. LIKE in combination with the '%' sign looks for one string within another. Next, there is an example where a non-correlated table subquery is object to a join operation.
Another Example
The example shows a solution for a common problem. Sometimes there are rows describing an outdated stage of entities. Those rows - for one logical entity differ from each other in some columns and there is an additional column version to track the time flow. Here is the example table booking and its data.
-T h et a b l eh o l d sa c t u a la n dh i s t o r i c a lv a l u e s C R E A T ET A B L Eb o o k i n g( -i d e n t i f y i n gc o l u m n s i d D E C I M A L N O TN U L L , b o o k i n g _ n u m b e rD E C I M A L N O TN U L L , v e r s i o n D E C I M A L N O TN U L L , -d e s c r i b i n gc o l u m n s s t a t e C H A R ( 1 0 ) N O TN U L L , e n t e r _ t s T I M E S T A M P N O TN U L L , e n t e r _ b y C H A R ( 2 0 ) N O TN U L L , -. . . -s e l e c to n eo ft h ed e f i n e dc o l u m n sa st h eP r i m a r yK e y C O N S T R A I N Tb o o k i n g _ p kP R I M A R YK E Y( i d ) , -f o r b i dd u p l i c a t er e c o r d i n g s C O N S T R A I N Tb o o k i n g _ u n i q u eU N I Q U E( b o o k i n g _ n u m b e r ,v e r s i o n ) ) ; -A d dd a t a I N S E R TI N T Ob o o k i n gV A L U E S( 1 ,4 7 1 1 ,1 ,' c r e a t e d ' , T I M E S T A M P ' 2 0 1 4 0 2 0 21 0 : 0 1 : 0 1 ' ,' E m i l y ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 2 ,4 7 1 1 ,2 ,' m o d i f i e d ' , T I M E S T A M P ' 2 0 1 4 0 2 0 31 1 : 1 0 : 0 1 ' ,' E m i l y ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 3 ,4 7 1 1 ,3 ,' c a n c e l e d ' , T I M E S T A M P ' 2 0 1 4 0 2 1 00 9 : 0 1 : 0 1 ' ,' J o h n ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 4 ,4 7 1 2 ,1 ,' c r e a t e d ' , T I M E S T A M P ' 2 0 1 4 0 3 1 01 2 : 1 2 : 1 2 ' ,' E m i l y ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 5 ,4 7 1 2 ,2 ,' d e l i v e r e d ' ,T I M E S T A M P ' 2 0 1 4 0 3 1 20 6 : 0 1 : 0 0 ' ,' C h a r l e s ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 6 ,4 7 1 3 ,1 ,' c r e a t e d ' , T I M E S T A M P ' 2 0 1 4 0 3 1 10 8 : 5 0 : 0 2 ' ,' E m i l y ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 7 ,4 7 1 3 ,2 ,' c a n c e l e d ' , T I M E S T A M P ' 2 0 1 4 0 3 1 20 8 : 4 0 : 1 2 ' ,' E m i l y ' ) ; I N S E R TI N T Ob o o k i n gV A L U E S( 8 ,4 7 1 3 ,3 ,' r e o p e n d ' , T I M E S T A M P ' 2 0 1 4 0 3 1 31 0 : 0 4 : 3 2 ' ,' J a c k ' ) ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
51/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The problem is to retrieve all actual rows, which are those with the highest version number within each booking. Bookings are considered to be the same, if they have the same booking_number. The first solution uses a non-correlated table subquery.
S E L E C T* F R O M b o o k i n gb W H E R E ( b o o k i n g _ n u m b e r ,v e r s i o n )I N ( S E L E C Tb o o k i n g _ n u m b e r ,M A X ( v e r s i o n )F R O Mb o o k i n gs qG R O U PB Yb o o k i n g _ n u m b e r )-t h es u b q u e r y O R D E RB Yb o o k i n g _ n u m b e r ;
The subquery creates a list of booking numbers together with their highest version. This list is used by the surrounding query to retrieve the required rows with all its columns. The second solution uses a correlated scalar value subquery.
S E L E C T* F R O M b o o k i n gb W H E R E v e r s i o n= ( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n gs qW H E R Es q . b o o k i n g _ n u m b e r=b . b o o k i n g _ n u m b e r ) O R D E RB Yb o o k i n g _ n u m b e r ;
The surrounding query retrievs all rows of the table. For each of them it calls the subquery, which retrieves the highest version within this booking_number. In most cases this highest version differs from the version of the actual row and because of the '=' operator those rows are not part of the result. Only those, whose version is equal to the value determined in the subquery (and whose booking_number is the same as those used in the subquery) are part of the final result. A variation of the introducing question may be to retrieve only historical rows (all versions except the highest one) for one special booking.
S E L E C T* F R O M b o o k i n gb W H E R E v e r s i o n! = ( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n gs qW H E R Es q . b o o k i n g _ n u m b e r=b . b o o k i n g _ n u m b e r ) A N D b o o k i n g _ n u m b e r=4 7 1 1 O R D E RB Yv e r s i o n ;
The surrounding query restricts the rows to those of one special booking. The subquery is called only for those rows. It's easy to run into pitfalls:
-U n e x p e c t e dr e s u l t ! S E L E C T* F R O M b o o k i n gb W H E R E v e r s i o n! =( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n g ) A N D b o o k i n g _ n u m b e r=4 7 1 1 O R D E RB Yv e r s i o n ;
The above query returns all versions of booking 4711 including the actual one! To get the expected result, it's necessary to 'link' the surrounding query and the subquery together.
Exercises
Find the booking with the most versions. Click to see solution
-T h es u b s e l e c tr e t u r ne x a c t l yO N Es i n g l ev a l u e .T h e r e f o ri t ' sa( n o n c o r r e l a t e d )s i n g l ev a l u es u b q u e r y .
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
52/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
-B u tt h i si so n l yai n t e r m e d i a t er e s u l t .T h ef i n a lr e s u l tm a yc o n t a i ns e v e r a lr o w s ,w h i c hi sn o tt h ec a s ei no u re x a m p l ed a t a b a s e ! S E L E C T* F R O M b o o k i n g W H E R E v e r s i o n=( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n g ) ;
Find all bookings with are canceled (in the latest version). Click to see solution
-I t ' sn e c e s s a r yt ol i n kt h es u b q u e r yw i t ht h es u r r o u n d i n gq u e r y . S E L E C T* F R O M b o o k i n gb W H E R E v e r s i o n= ( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n gs qW H E R Es q . b o o k i n g _ n u m b e r=b . b o o k i n g _ n u m b e r ) A N D s t a t e=' c a n c e l e d ' ; -A d d i t i o n a l l yw i t h i nt h er e s u l t i n gr o w st h e r em u s tb eac o r r e l a t i o nb e t w e e nt h ev e r s i o na n dt h es t a t e . -T h i si sa c c o m p l i s h e dw i t ht h eA N Dk e yw o r da tt h el e v e lo ft h es u r r o u n d i n gq u e r y .I ft h eA N Dw o r k sw i t h i n -t h es u b q u e r y ,t h er e s u l td o e sn o tm e e tt h ee x p e c t a t i o n s . S E L E C T* F R O M b o o k i n gb W H E R E v e r s i o n= ( S E L E C TM A X ( v e r s i o n )F R O Mb o o k i n gs qW H E R Es q . b o o k i n g _ n u m b e r=b . b o o k i n g _ n u m b e rA N Ds t a t e=' c a n c e l e d ' ) ;
Create a list of all persons together with the number of persons which are born in the same city as they itself. Click to see solution
-T h es u b s e l e c tu s e st h ep l a c e _ o f _ b i r t ho ft h eo u t s i d er o w .T h e r e f o r ei t ' sac o r r e l a t e ds u b q u e r y . S E L E C Tf i r s t n a m e , l a s t n a m e , p l a c e _ o f _ b i r t h , ( S E L E C TC O U N T ( * )F R O Mp e r s o ns qW H E R Ep . p l a c e _ o f _ b i r t h=s q . p l a c e _ o f _ b i r t h )c n t-a na r b i t r a r yn a m ef o rt h ea d d i t i o n a lc o l u m n F R O M p e r s o np ;
Create a list of all persons together with the number of their contact information. Click to see solution
-T h es u b s e l e c tu s e st h eI Do ft h eo u t s i d er o w .T h e r e f o r ei t ' sac o r r e l a t e ds u b q u e r y . S E L E C Tf i r s t n a m e , l a s t n a m e , ( S E L E C TC O U N T ( * )F R O Mc o n t a c tcW H E R Ep . i d=c . p e r s o n _ i d )c n t-a na r b i t r a r yn a m ef o rt h ea d d i t i o n a lc o l u m n F R O M p e r s o np ;
Create a list of all persons together with the number of their e-mail-addresses. Click to see solution
S E L E C Tf i r s t n a m e , l a s t n a m e , ( S E L E C TC O U N T ( * ) F R O M c o n t a c tc W H E R E p . i d=c . p e r s o n _ i d A N D c o n t a c t _ t y p e=' e m a i l ' -T h es u b s e l e c ti sac o m p l e t eS E L E C T .T h e r e f o ra l le l e m e n t so f -a' r e g u l a r 'S E L E C Tm a yb eu s e d :J o i n ,f u n c t i o n s ,. . .a n d :S U B S E L E C T )c n t -a na r b i t r a r yn a m eo ft h ea d d i t i o n a lc o l u m n F R O M p e r s o np ;
Create a list of all persons together with the number of their contact information. (Same question as above.) Replace the subquery by a JOIN construct. Click to see solution
-S t e p1( f o rd e m o n s t r a t i o np u r p o s eo n l y ) :T or e t r i e v eA L Lp e r s o n s ,i t ' sn e c e s s a r yt ou s ea nO U T E RJ O I N S E L E C Tf i r s t n a m e , l a s t n a m e , c . c o n t a c t _ t y p e F R O M p e r s o np L E F TO U T E RJ O I Nc o n t a c tcO Np . i d=c . p e r s o n _ i d ; -S t e p2( c o m p l e t es o l u t i o n ) :A d dt h ec o u n t e r .T od os o ,t h er e s u l tm u s tb eg r o u p e d . S E L E C Tf i r s t n a m e , l a s t n a m e , C O U N T ( c . c o n t a c t _ t y p e ) F R O M p e r s o np
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
53/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
L E F TO U T E RJ O I Nc o n t a c tcO Np . i d=c . p e r s o n _ i d G R O U PB Yf i r s t n a m e ,l a s t n a m e ;
For which persons there are NO contact information? Click to see solution
-T h es u b q u e r yr e t u r n sm o r et h a no n er o w .T h e r e f o r ei t ' sat a b l es u b q u e r y . S E L E C Tf i r s t n a m e ,l a s t n a m e F R O M p e r s o n W H E R E i dN O TI N( S E L E C Tp e r s o n _ i dF R O Mc o n t a c t ) ; -t h es u b q u e r y
Often users and applications request information in a form which differs from the structure of existing tables. To achieve those requests the SELECT command offers plenty possibilities: projections, joins, group by clause and so on. If there are always the same requests, what is the case in particular for applications, or if the table structure intentionally should be hidden from the application-level, views can be defined. Furthermore the access rights to views may be different from those to tables. Views look like a table. They have columns of a certain data type, which can be retrieved in the same way as columns of a table. But views are only definitions, they don't have data of its own! Their data is always the data of a table or is based on another view. A view is a different sight to the stored data or somewhat like a predefined SELECT.
Create a View
One creates a view by specify its name, column names - which is optionally - and especially the SELECT command on which the view is based. Within this SELECT all elements are allowed in the same way as in a standalone SELECT command. If no column names are specified the column names of the SELECT are used.
C R E A T EV I E W< v i e w _ n a m e >[ ( c o l u m n _ n a m e ,. . . ) ]A S S E L E C T. . . -a su s u a l ;
As indicated in the above 'order by' example it is possible to use all columns of the view (but not all of the table!) within any part of SELECTs to the view: in the projection, the WHERE, ORDER BY, GROUP BY and HAVING clauses, in function calls and so on.
-S E L E C T so nv i e w sh a v ei d e n t i c a ls y n t a xa sS E L E C T so nt a b l e s S E L E C TC O U N T ( l a s t n a m e ) ,l a s t n a m e F R O M p e r s o n _ v i e w _ 1 G R O U PB Yl a s t n a m e O R D E RB Yl a s t n a m e ;
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Next there is a renaming of a column. The column name lastname of the table will be familyname in the view.
-f i r s tt e c h n i q u e :l i s tt h ed e s i r e dc o l u m nn a m e sw i t h i np a r e n t h e s i sa f t e rt h ev i e wn a m e C R E A T EV I E Wp e r s o n _ v i e w _ 2 a( f i r s t n a m e ,f a m i l y n a m e ,d a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h ,w e i g h t )A S S E L E C T f i r s t n a m e ,l a s t n a m e , d a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h ,w e i g h t F R O M p e r s o n ; -s e c o n dt e c h n i q u e :r e n a m et h ec o l u m ni nt h eS E L E C Tp a r t C R E A T EV I E Wp e r s o n _ v i e w _ 2 bA S S E L E C Tf i r s t n a m e ,l a s t n a m eA Sf a m i l y n a m e ,d a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h ,w e i g h t F R O M p e r s o n ; -H i n t :t e c h n i q u e1o v e r w r i t e st e c h n i q u e2 -A c c e s st op e r s o n . l a s t n a m ei sp o s s i b l ev i ap e r s o n _ v i e w _ 2 a . f a m i l y n a m eo rp e r s o n _ v i e w _ 2 b . f a m i l y n a m e . -T h eo b j e c t sp e r s o n . f a m i l y n a m e ,p e r s o n _ v i e w _ 2 a . l a s t n a m eo rp e r s o n _ v i e w _ 2 b . l a s t n a m ed o e sn o te x i s t !
This view contains only persons born in San Francisco or Richland. All other persons are hidden. Therefore the following SELECT retrieves nothing although there are persons in the table which fulfil the condition.
In this example the elaborated construct 'GROUP BY / HAVING' is hidden from users and applications.
Example 5: Join
Next, there is an example where a view contains columns out of serveral tables. To do so a JOIN is neccessary. The view contains the name of persons in combination with the available contact information. As an INNER JOIN is used, some persons occur multiple, others not at all.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
55/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The columns person.id an contact.person_id are used during the definition of the view. But they are not part of the projection and hence not available for SELECTs to the view. Hint: The syntax and semantic of join operations is explained on a separate page.
D R O PV I E Wp e r s o n _ v i e w _ 1 ; D R O PV I E Wp e r s o n _ v i e w _ 2 a ; D R O PV I E Wp e r s o n _ v i e w _ 2 b ; D R O PV I E Wp e r s o n _ v i e w _ 3 ; D R O PV I E Wp e r s o n _ v i e w _ 4 ; D R O PV I E Wp e r s o n _ v i e w _ 5 ;
Exercises
Create a view 'hobby_view_1' which contains all columns of table 'hobby' except 'id'. Rename column 'remark' to 'explanation'. Create two different solutions. Click to see solution
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
56/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
C R E A T EV I E Wh o b b y _ v i e w _ 1 aA S S E L E C Th o b b y n a m e ,r e m a r kA Se x p l a n a t i o n F R O M h o b b y ; -V e r i f i c a t i o n S E L E C T*F R O Mh o b b y _ v i e w _ 1 a ; C R E A T EV I E Wh o b b y _ v i e w _ 1 b( h o b b y n a m e ,e x p l a n a t i o n )A S S E L E C Th o b b y n a m e ,r e m a r k F R O M h o b b y ; -V e r i f i c a t i o n S E L E C T*F R O Mh o b b y _ v i e w _ 1 b ;
Create a view 'hobby_view_2' with the same criteria as in the previous example. The only difference is that the length of the explanation column is limited to 30 character. Hint: use the function substr(<column name>, 1, 30) to determine the first 30 characters - she is not part of the SQL standard but works in plenty implementation. Click to see solution
C R E A T EV I E Wh o b b y _ v i e w _ 2A S S E L E C Th o b b y n a m e ,s u b s t r ( r e m a r k ,1 ,3 0 )A Se x p l a n a t i o n F R O M h o b b y ; -V e r i f i c a t i o n S E L E C T*F R O Mh o b b y _ v i e w _ 2 ;
Create a view 'contact_view_3' which contains all rows of table contact with the exception of the 'icq' rows. Count the number of the view rows and compare it with the number of rows in the table 'contact'. Click to see solution
C R E A T EV I E Wc o n t a c t _ v i e w _ 3A S S E L E C T* F R O M c o n t a c t W H E R E c o n t a c t _ t y p e! =' i c q ' ; -a na l t e r n a t eo p e r a t o rw i t ht h es a m es e m a n t i ca s' ! = 'i s' < > ' -V e r i f i c a t i o n S E L E C T' v i e w ' , C O U N T ( * )F R O Mc o n t a c t _ v i e w _ 3 U N I O N S E L E C T' t a b l e ' ,C O U N T ( * )F R O Mc o n t a c t ;
Create a view 'contact_view_4' which contains one row per contact type with its notation and the number of occurences. Afterwords select those which occur more than once. Click to see solution
C R E A T EV I E Wc o n t a c t _ v i e w _ 4A S S E L E C Tc o n t a c t _ t y p e ,C O U N T ( * )A Sc n t F R O M c o n t a c t G R O U PB Yc o n t a c t _ t y p e ; -V e r i f i c a t i o n S E L E C T* F R O M c o n t a c t _ v i e w _ 4 ; -U s ec o l u m n so fav i e ww i t ht h es a m es y n t a xa sc o l u m no fat a b l e . S E L E C T* F R O M c o n t a c t _ v i e w _ 4 W H E R E c n t>2 ;
Create a view 'person_view_6' which contains first- and lastname of persons plus the number of persons with the same name as the person itself (family name). Hint: the solution uses a correlated subquery. Click to see solution
C R E A T EV I E Wp e r s o n _ v i e w _ 6A S S E L E C Tf i r s t n a m e ,l a s t n a m e ,( S E L E C TC O U N T ( * )F R O Mp e r s o ns qW H E R Es q . l a s t n a m e=p . l a s t n a m e )A Sc n t _ f a m i l y F R O M p e r s o np ; -V e r i f i c a t i o n S E L E C T* F R O M p e r s o n _ v i e w _ 6 ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
57/110
4/2/2014
D R O PV I E Wh o b b y _ v i e w _ 1 a ; D R O PV I E Wh o b b y _ v i e w _ 1 b ; D R O PV I E Wh o b b y _ v i e w _ 2 ; D R O PV I E Wc o n t a c t _ v i e w _ 3 ; D R O PV I E Wc o n t a c t _ v i e w _ 4 ; D R O PV I E Wp e r s o n _ v i e w _ 6 ;
Structured Query Language/Print version - Wikibooks, open books for an open world
The basic syntax and semantic of the INSERT command is described on the page INSERT. There are examples how to insert single rows with fixed values into a table. The present page describes how to dynamise the command by the use of subqueries.
Next, the values to be inserted may be evaluated by a scalar value subquery. This means, that single values may be computed at runtime based on the rows of the same or another table.
-C o u n tt h en u m b e ro fr o w st od e t e r m i n et h en e x tI D .C a u t i o n :T h i sh a n d l i n go fI D si sa b s o l u t l yN O Tr e c o m m e n d e df o rr e a la p p l i c a t i o n s ! I N S E R TI N T Op e r s o n(i d , f i r s t n a m e , l a s t n a m e , d a t e _ o f _ b i r t h , p l a c e _ o f _ b i r t h ,s s n , w e i g h t ) V A L U E S ( ( S E L E C TC O U N T ( * )+1 0 0 0F R O Mp e r s o n ) , -T h es c a l a rv a l u es u b q u e r y .I tc o m p u t e so n es i n g l ev a l u e ,i nt h i sc a s et h en e wI D . -V A L U E S ( ( S e l e c t*F R O M( S E L E C TC O U N T ( * )+1 0 0 0F R O Mp e r s o n )t m p ) ,-M y S Q Li n s i s t si nu s i n ga ni n t e r m e d i a t et a b l e ' L a r r y ,n o .? ' , ' G o l d s t e i n ' ,C U R R E N T _ D A T E , ' D a l l a s ' , ' 0 7 8 0 5 1 1 2 0 ' ,9 5 ) ; C O M M I T ;
-T h es t a t e m e n td o u b l e st h en u m b e ro fr o w sw i t h i nt h et a b l e .I to m i t si nt h et a b l es u b q u e r yt h eW H E R Ec l a u s ea n dt h e r e f o r e -i tr e a d sa l le x i s t i n gr o w s .C a u t i o n :T h i sh a n d l i n go fI D si sa b s o l u t l yN O Tr e c o m m e n d e df o rr e a la p p l i c a t i o n s ! I N S E R TI N T Op e r s o n( i d , f i r s t n a m e ,l a s t n a m e ,d a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h ,s s n ,w e i g h t ) S E L E C T i d+1 1 0 0 , f i r s t n a m e ,l a s t n a m e ,d a t e _ o f _ b i r t h ,p l a c e _ o f _ b i r t h ,s s n ,w e i g h t F R O M p e r s o n ; C O M M I T ;
The syntax has change in such a way that the key word 'VALUES' with its list of values is replaced by a complete subquery (often named 'subselect') which starts with the key word 'SELECT'. Of course the number and type of the selected columns must correlate with the number and type of the columns of the specified column list behind the 'INSERT INTO' key word. Within the subquery the complete power of the SELECT statement may be used: JOIN, WHERE, GROUP BY, ORDER BY and especially other subqueries in a recursive manner. Therefore there is a wide range of use cases: create rows with increased version numbers, with percentage increased salary, with the actual timestamp, fixed values from rows of the same or another table, ... .
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
58/110
4/2/2014
C O M M I T ;
Structured Query Language/Print version - Wikibooks, open books for an open world
The technique shown at Structured Query Language/Example_Database_Data#Grow_up which multiplies existing data, e.g. for testing purpose, is based on such table subqueries.
Exercises
Insert a new person with id 1301, firstname 'Mr. Mean', lastname is the lowest lastname (in the sense of the character encoding, use min() function). Its weight is the average weight of all persons (use avg() function). Click to see solution
-T w oc o l u m n sa r ec o m p u t e dd u r i n gr u n t i m e I N S E R TI N T Op e r s o n( i d , f i r s t n a m e , l a s t n a m e ,w e i g h t ) V A L U E S ( 1 3 0 1 , ' M r .M e a n ' , ( S E L E C TM I N ( l a s t n a m e )F R O Mp e r s o n ) , ( S E L E C TA V G ( w e i g h t ) F R O Mp e r s o n ) -t h eM y S Q Lv e r s i o nw i t hi t si n t e r m e d i a t et a b l e s ( S E L E C T*F R O M( S E L E C TM I N ( l a s t n a m e )F R O Mp e r s o n )t m p 1 ) , ( S E L E C T*F R O M( S E L E C TA V G ( w e i g h t ) F R O Mp e r s o n )t m p 2 ) ) ; C O M M I T ; -C h e c ky o u rr e s u l t S E L E C T*F R O Mp e r s o nW H E R Ei d=1 3 0 1 ;
Insert one additional person per family (=lastname) with firstname 'An extraordinary family member', lastname is the family name. Incorporate only the rows from the original example database with id <= 10. Click to see solution
-T w oc o l u m n sa r ec o m p u t e dd u r i n gr u n t i m e .T h en u m b e ro fi n v o l v e dr o w si sd e l i m i t e db yt h eW H E R Ec l a u s e . I N S E R TI N T Op e r s o n( i d , f i r s t n a m e , l a s t n a m e ) -h e r es t a r t st h es u b q u e r y S E L E C TM A X ( i d )+1 3 1 0 , -i nt h i sc a s et h em a x ( )f u n c t i o nw o r k sp e rg r o u p ' A ne x t r a o r d i n a r yf a m i l ym e m b e r ' , l a s t n a m e F R O M p e r s o n W H E R E i d< =1 0 G R O U PB Yl a s t n a m e ; C O M M I T ; -C h e c ky o u rr e s u l t S E L E C T*F R O Mp e r s o nW H E R Ei d>1 3 1 0 ;
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The page in hand offers two additional technics as an extention to the UPDATE command shown on one of the previous pages: Computing values, which are assigned to a column, at runtime. Using complex subqueries as search conditions in the WHERE clause.
The subquery may use values of the row, which is actually updated. In the next example persons receive the mean weight of their family. To compute this mean weight, it is necessary to use the column 'lastname' of the actual processed row.
-T h es u b q u e r yi sa' c o r r e l a t e d 's c a l a rv a l u es u b q u e r y . U P D A T Ep e r s o npS E T -' p . l a s t n a m e 'r e f e r st ot h el a s t n a m eo ft h ea c t u a lr o w .T h es u b q u e r yb e a r sa l lr o w si nm i n d ,n o to n l ys u c hw i t h' i d> =5 ' . w e i g h t=( S E L E C TA V G ( w e i g h t )F R O Mp e r s o ns qW H E R Es q . l a s t n a m e=p . l a s t n a m e ) -Ah i n tt oM y S Q Lu s e r s :M y S Q Ld o e sn o ts u p p o r tU P D A T Ei nc o m b i n a t i o nw i t hac o r r e l a t e ds u b q u e r y -t ot h es a m et a b l e .D i f f e r e n tt a b l e sw o r k .M y S Q Lh a sad i f f e r e n t ,n o n s t a n d a r dc o n c e p t :m u l t i t a b l eu p d a t e . W H E R E i d> =5 ; -C h e c kt h er e s u l t S E L E C T*F R O Mp e r s o n ; -r e v o k et h ec h a n g e s R O L L B A C K ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
60/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The command performs an UPDATE in the table person, but the affected rows are identified by a subquery in table contact . This technique of grabbing information from other tables offers very flexible strategies to modify the data. It is no error to select 0 rows in the subquery. In this case the DBMS executes the UPDATE command as usual and throws no exception. (The same holds true for subqueries in SELECT or DELETE statements.)
Exercises
Assign the firstname 'Short firstname' to all persons which have a firstname with less than 5 characters. Click to see solution
-H i n t :S o m ei m p l e m e n t a t i o n su s ead i f f e r e n tf u n c t i o nn a m e :l e n g t h ( )o rl e n ( ) . U P D A T Ep e r s o n S E T f i r s t n a m e=' S h o r tf i r s t n a m e ' W H E R E C H A R A C T E R _ L E N G T H ( f i r s t n a m e )<5 ; -C h e c kt h er e s u l t S E L E C T*F R O Mp e r s o n ; -r e v o k et h ec h a n g e s R O L L B A C K ;
Assign the firstname 'No hobby' to all persons which have no hobby. Click to see solution
U P D A T Ep e r s o n S E T f i r s t n a m e=' N oh o b b y ' W H E R E i dN O TI N ( S E L E C Tp e r s o n _ i d F R O M p e r s o n _ h o b b y ) ; -C h e c kt h er e s u l t S E L E C T*F R O Mp e r s o n ; -r e v o k et h ec h a n g e s R O L L B A C K ;
Assign the firstname 'Sportsman' to all persons performing one of the hobbies 'Underwater Diving' or 'Yoga'. Click to see solution
U P D A T Ep e r s o n S E T f i r s t n a m e=' S p o r t s m a n ' W H E R E i dI N -T h es u b q u e r ym u s tj o i nt ot h et a b l e' h o b b y 't os e et h e i rc o l u m n' h o b b y n a m e ' . ( S E L E C Tp h . p e r s o n _ i d F R O M p e r s o n _ h o b b yp h J O I N h o b b y h O Np h . h o b b y _ i d=h . i d A N D h . h o b b y n a m eI N( ' U n d e r w a t e rD i v i n g ' ,' Y o g a ' ) ) ; -C h e c kt h er e s u l t S E L E C T*F R O Mp e r s o n ; -r e v o k et h ec h a n g e s R O L L B A C K ;
In many cases applications want to store rows in the database without knowing whether this rows previously exist in the database or not. If the rows exist, they must use the UPDATE command, if not, the INSERT command. To do so the following construct is often used:
-p s e u d o c o d e I F( S E L E C TC O U N T ( * )=0. . . )T H E N I N S E R T. . . E L S E U P D A T E. . . ;
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
There are two roundtrips between application and DBMS, either SELECT + INSERT or SELECT + UPDATE. The application must transfer one row after the other. A 'bulk storing' is not possible because the evaluation of the criterion which decides between INSERT and UPDATE may lead to different results from row to row. The syntax is spread across three SQL statements. This is error-prone. To overcome the disadvantages the SQL standard defines a MERGE command, which contains the complete code shown above in one single statement. The MERGE performs an INSERT or an UPDATE depending on the existence of individual rows at the target table.
-D e f i n et a r g e t ,s o u r c e ,m a t c hc r i t e r i o n ,I N S E R Ta n dU P D A T Ew i t h i no n es i n g l ec o m m a n d M E R G EI N T O < t a r g e t _ t a b l e > < t a r g e t _ t a b l e _ a l i a s > -d e n o t et h et a r g e tt a b l e U S I N G< s o u r c e _ t a b l e > < s o u r c e _ t a b l e _ a l i a s > -d e n o t et h es o u r c et a b l e O N ( < m a t c h _ c r i t e r i o n > ) -d e f i n et h e' m a t c hc r i t e r i o n 'w h i c hc o m p a r e st h es o u r c ea n d -t a r g e tr o w sw i t ht h es a m es y n t a xa si na n yW H E R Ec l a u s e W H E NM A T C H E DT H E N U P D A T ES E Tc o l u m n 1=v a l u e 1[ ,c o l u m n 2=v a l u e 2. . . ] -av a r i a n to ft h er e g u l a rU P D A T Ec o m m a n d W H E NN O TM A T C H E DT H E N I N S E R T( c o l u m n 1[ ,c o l u m n 2. . . ] )V A L U E S( v a l u e 1[ ,v a l u e 2. . . ] )-av a r i a n to ft h er e g u l a rI N S E R Tc o m m a n d ;
Description
The target table is named after the MERGE INTO key word, the source table after the USING key word. The comparision between target rows and source rows, which is necessary to decide between INSERT and UPDATE, is specified after the ON key word with a syntax, which is identical to the syntax of a WHERE clause. If this comparision matches, the UPDATE will be performed, else the INSERT. In simple cases the comparision compares Primary Key or Foreign Key columns. But it is also possible to use very sophisticated conditions on any column. In the 'MATCHED' case a variant of the UPDATE follows. It differs from the regular UPDATE command in that it has no table name (the table name is already denoted after the MERGE INTO) and no WHERE clause (it uses the match criterion after the ON key word). In the 'NOT MATCHED' case a variant of the INSERT follows. For the same reason as before the target table is not named within the INSERT.
Example
Create a table 'hobby_shadow' to store some of the 'hobby' rows. The subsequent MERGE command shall perform an INSERT or an UPDATE depending on the existence of correlating rows.
-s t o r ee v e r ys e c o n dr o wi nan e wt a b l e' h o b b y _ s h a d o w ' C R E A T ET A B L Eh o b b y _ s h a d o wA SS E L E C T*F R O Mh o b b yW H E R EM O D ( i d ,2 )=0 ; S E L E C T*F R O Mh o b b y _ s h a d o w ; -I N S E R T/U P D A T Ed e p e n d i n go nt h ec o l u m n' i d ' . M E R G EI N T O h o b b y _ s h a d o w t -t h et a r g e t U S I N G( S E L E C Ti d ,h o b b y n a m e ,r e m a r k F R O M h o b b y ) s -t h es o u r c e O N ( t . i d=s . i d ) -t h e' m a t c hc r i t e r i o n ' W H E NM A T C H E DT H E N U P D A T ES E Tr e m a r k=c o n c a t ( s . r e m a r k ,'M e r g e/U p d a t e ' ) W H E NN O TM A T C H E DT H E N I N S E R T( i d ,h o b b y n a m e ,r e m a r k )V A L U E S( s . i d ,s . h o b b y n a m e ,c o n c a t ( s . r e m a r k ,'M e r g e/I n s e r t ' ) ) ; C O M M I T ; -C h e c kt h er e s u l t S E L E C T*F R O Mh o b b y _ s h a d o w ;
The MERGE command handls all rows, but there is only 1 roundtrip between the application and the DBMS. Some of the rows are handled by the INSERT part of MERGE, others by its UPDATE part. This distinction may be observed by the last part of the column 'remark'.
Use Case
Typical use cases for the MERGE command are ETL processes. Often those processes have to aggregate some values for a grouping criterion (eg: a product line) over a time period. The first access per product line and period has to insert new rows with given values, subsequent accesses have to update them by increasing values.
Extentions
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 62/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The SQL standard defines some more features within the MERGE command. WHEN clause The WHEN MATCHED and WHEN NOT MATCHED clauses may be extended by an optional query expression like A N D( p l a c e _ o f _ b i r t h=' D a l l a s ' ) . As a consequence, it's possible to use a series of WHEN MATCHED / WHEN NOT MATCHED clauses.
. . . W H E NM A T C H E DA N D( t . h o b b y _ n a m eI N( ' F i s h i n g ' ,' U n d e r w a t e rD i v i n g ' ) )T H E N U P D A T ES E Tr e m a r k=c o n c a t ( ' W a t e rs p o r t s :' ,t . r e m a r k ) W H E NM A T C H E DA N D( t . h o b b y _ n a m eI N( ' A s t r o n o m y ' ,' M i c r o s c o p y ' ,' L i t e r a t u r e ' ) )T H E N U P D A T ES E Tr e m a r k=c o n c a t ( ' S e m i p r o f e s s i o n a ll e i s u r ea c t i v i t y :' ,t . r e m a r k ) W H E NM A T C H E DT H E N U P D A T ES E Tr e m a r k=c o n c a t ( ' L e i s u r ea c t i v i t y :' ,t . r e m a r k ) . . . -T h es a m ei sp o s s i b l ew i t hW H E NN O TM A T C H E Di nc o m b i n a t i o nw i t hI N S E R T
DELETE Within a WHEN MATCHED clause it is possible to use a DELETE command instead of an UPDATE to remove the matched row. This feature may be combined with the previous presented extension by an optional query expression. In the SQL standard the DELETE command is not applicable to the WHEN NOT MATCHED clause.
-U p d a t e' F i s h i n g 'a n d' U n d e r w a t e rD i v i n g ' .D e l e t ea l lo t h e r sw h i c hh a v eam a t c hb e t w e e ns o u r c ea n dt a r g e t . . . . W H E NM A T C H E DA N D( t . h o b b y _ n a m eI N( ' F i s h i n g ' ,' U n d e r w a t e rD i v i n g ' ) )T H E N U P D A T ES E Tr e m a r k=c o n c a t ( ' W a t e rs p o r t s :' ,t . r e m a r k ) W H E NM A T C H E DT H E N D E L E T E . . .
Caveat
The MERGE command is clearly defined by standard SQL. The command itself as well as the extensions described before are implemented by a lot of DBMS. Deviating from the standard most implementations unfortunatelly use different and/or additional keywords and - sometimes - different concepts. Even the intoductive key words MERGE INTO may differ from the standard.
Exercises
A) Create a new table 'contact_merge' with the same structure as 'contact'. B) Copy row number 3 from 'contact' to 'contact_merge'. C) Use the MERGE command to insert/update all E-Mail-adresses from 'contact' to 'contact_merge' and add the e-mail-protocol name to the contact values (prepend column contact_value by the string 'mailto:'). Click to see solution
-C r e a t et a b l ea n dc o p yo n er o w C R E A T ET A B L Ec o n t a c t _ m e r g eA SS E L E C T*F R O Mc o n t a c tW H E R Ei d=3 ; S E L E C T*F R O Mc o n t a c t _ m e r g e ; -I N S E R T/U P D A T Ed e p e n d i n go nt h ec o l u m n' i d ' . M E R G EI N T O c o n t a c t _ m e r g e t -t h et a r g e t U S I N G( S E L E C Ti d ,p e r s o n _ i d ,c o n t a c t _ t y p e ,c o n t a c t _ v a l u e F R O M c o n t a c t W H E R E c o n t a c t _ t y p e=' e m a i l ' ) s -t h es o u r c e O N ( t . i d=s . i d ) -t h e' m a t c hc r i t e r i o n ' W H E NM A T C H E DT H E N U P D A T ES E Tc o n t a c t _ v a l u e=c o n c a t ( ' m a i l t o : ' ,t . c o n t a c t _ v a l u e ) W H E NN O TM A T C H E DT H E N I N S E R T( i d ,p e r s o n _ i d ,c o n t a c t _ t y p e ,c o n t a c t _ v a l u e )V A L U E S( s . i d ,s . p e r s o n _ i d ,s . c o n t a c t _ t y p e ,c o n c a t ( ' m a i l t o : ' ,s . c o n t a c t _ v a l u e ) ) ; C O M M I T ; -C h e c kt h er e s u l t S E L E C T*F R O Mc o n t a c t _ m e r g e ;
Because the DELETE command deletes rows as a whole and not partly, the syntax is very simple. Its structure was shown on a previous page. The page on hand offers only one addition: The WHERE clause isn't limited to simple conditions like 'id = 10' but may contain a subquery. This gives the command much more flexibility.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 63/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The use of subqueries as part of a DELETE command is identical to its use within an UPDATE or SELECT command. There is another command for the deletion of rows. The TRUNCATE command is very similar to DELETE. TRUNCATE deletes all rows of a table and shows better performance. But it has no mechanism to choose individual rows.
Example
The example command deletes contact information from persons which are born in San Francisco.
Correlated subqueries in combination with DELETE commands are not supported by all implementations. It often happens that the DBMS rejects DELETE commands because Foreign Key constraints will be violated during its execution. E.g.: if the command tries to delete a person to whom a contact or hobby information is known, the command fails (as a whole). To overcame such situations there are different strategies: Delete all dependent rows prior to the intended row. Define the Foreing Key constraint as DEFERRED (it will be check not before COMMIT) and delete the depending rows before or after the intended one. Define the Foreing Key constraint as CASCADE. In this case the depending rows will be deleted automatically.
Exercise
Delete hobby information for family Goldstein. Click to see solution
D E L E T EF R O Mp e r s o n _ h o b b y W H E R E p e r s o n _ i dI N ( S E L E C Ti d F R O M p e r s o n W H E R E l a s t n a m e=' G o l d s t e i n ' ) ; -R e f r a i nf r o md e l e t i n gt h eh o b b yi t s e l f-b e c a u s e : a )T h eh o b b ym a yb ea l l o c a t e dt oad i f f e r e n tp e r s o n . b )A f t e rt h ei n f o r m a t i o ni np e r s o n _ h o b b yi sd e l e t e d ,t h e r ei sn ol o n g e rt h ep o s s i b i l i t yt og e t t oo l da s s i g n m e n tb e t w e e np e r s o na n dh o b b y . -I t ' so n l yat e s t .R e s t o r et h er o w s . R O L L B A C K ;
The TRUNCATE TABLE command deletes all rows of a table without causing any triggered action. Unlike the DELETE command it contains no WHERE clause to specify individual rows. With respect to the TRUNCATE TABLE command most DBMS show significant better performance than with DELETE command. This results from the facts the DBMS can empty the table (and its indexes) as a whole. It's not necessary to access individual rows. There is - per definition - no WHERE clause. No trigger action will be launched - per definition. The transaction locks the complete table. If there is an FK-constraint from table t1 to t2, the command ' T R U N C A T ET A B L Et 2 'will fail. This holds true independent from the question whether any row of t1 refers actually to one of the rows of t2 or not. The DBMS checks only the existence of the FK-constraint definition. The syntax of the TRUNCATE TABLE command is very simple.
T R U N C A T ET A B L E< t a b l e n a m e > ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
64/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Example
-D e l e t eA L Lr o w so ft h et a b l e' m y T a b l e ' T R U N C A T ET A B L Em y T a b l e ; -I nm o s tD B M SR O L L B A C Ki sn o tp o s s i b l e-i no p p o s i t et os i t u a t i o n sw i t haD E L E T Ec o m m a n d .
An Analogy
To illustrate the difference between the TRUNCATE TABLE command and the DELETE command (without a WHERE clause) one can imagine a trucker, who wants to empty a trailer full of sand at a construction site. To do so he has two possibilities. Either he empties the trailer in that he tilts him - this corresponds to the TRUNCATE TABLE command. Or he climbs onto the trailer and throws down one grain of sand after the next - this corresponds to the DELETE command.
Exercises
Delete all rows of table 'person_hobby' using the DELETE command. Verify that there are no rows left in 'person_hobby'. Delete all rows of table 'hobby' using the TRUNCATE TABLE command. What will happen? (Consider that there is an FK constraint from the table empty 'person_hobby' to 'hobby'.) Click to see solution
-D e l e t ea l lr o w so f' p e r s o n _ h o b b y 'w i t haD E L E T Ec o m m a n d D E L E T EF R O Mp e r s o n _ h o b b y ; C O M M I T ; -A r et h e r ea n yr o w s ? S E L E C TC O U N T ( * )F R O Mp e r s o n _ h o b b y ; -T r yT R U N C A T ET A B L Ec o m m a n d : T R U N C A T ET A B L Eh o b b y ; -A ne x c e p t i o nw i l lb et h r o w n .A l t h o u g ht h e r ei sn or o wi n' p e r s o n _ h o b b y 'r e f e r i n gar o wi n' h o b b y ' , -t h ed e f i n i t i o no ft h eF Kc o n s t r a i n te x i s t s .T h i si st h er e a s o nf o rt h ee x c e p t i o n .
What will happen in the above example, if the TRUNCATE TABLE command is replaced by a DELETE command? Click to see solution
-A st h e r ei sn or o wi n' p e r s o n _ h o b b y 'r e f e r i n gt o' h o b b y ' ,t h eD E L E T Ec o m m a n dd e l e t e sa l lr o w si n' h o b b y ' . D E L E T EF R O Mh o b b y ; C O M M I T ;
The original data of the example database can be reconstructed as shown on the example database data page. Advanced Topics One of the basic steps during database development cycles is the fixing of decisions about the table structure. To do so there is the CREATE TABLE statement with which developers define tables together with their columns and constraints. Because a lot of features may be activated by the command, its syntax is a little bit complex. This page shows the most important parts. The syntax is not straight forward. At some points it is possible to use alternative formulations to express the same purpose, e.g. the Primary Key may be defined within the column definition as a column constraint, at the end of the command as a table constraint or as a separate stand-alone command 'ALTER TABLE ADD CONSTRAINT ...;' .
C R E A T ET A B L E< t a b l e n a m e >( < c o l u m n _ n a m e >< d a t a _ t y p e >< d e f a u l t _ v a l u e >< i d e n t i t y _ s p e c i f i c a t i o n >< c o l u m n _ c o n s t r a i n t > , < c o l u m n _ n a m e >< d a t a _ t y p e >< d e f a u l t _ v a l u e > < c o l u m n _ c o n s t r a i n t > , . . . , < t a b l e _ c o n s t r a i n t > , < t a b l e _ c o n s t r a i n t > , . . . ) ;
General Description
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
65/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
After the introductory key words CREATE TABLE the tablename is specified. Within a pair of parentheses a list of column definitions follows. Each column is defined by its name, data type, an optional default value and optional constraints for this individual column. After the list of column definitions developers can specifiy table constraints like Primary and Foreign Keys, Unique conditions and general column conditions. An first example was shown at the page Create a simple Table and a second one here:
C R E A T ET A B L Et e s t _ t a b l e( -d e f i n ec o l u m n s( n a m e/t y p e/d e f a u l tv a l u e/c o l u m nc o n s t r a i n t i d D E C I M A L P R I M A R YK E Y , p a r t _ n u m b e r C H A R ( 1 0 ) D E F A U L T' n / a ' N O TN U L L , p a r t _ n a m e V A R C H A R ( 5 0 0 ) , s t a t e D E C I M A L D E F A U L T1 , -d e f i n et a b l ec o n s t r a i n t s( e g :' n / a 's h a l lc o r r e l a t ew i t hN U L L ) C O N S T R A I N Tt e s t _ c h e c kC H E C K( ( p a r t _ n u m b e r =' n / a 'A N Dp a r t _ n a m eI S N U L L )O R ( p a r t _ n u m b e r! =' n / a 'A N Dp a r t _ n a m eI SN O TN U L L ) ) ) ;
The table consists of 4 columns. All of them have a data type and some a default value. The column id acts as the Primary Key. The table constraint test_check garanties that part_name is mandatory if part_number is recorded.
Column Definition
Data Type
The standard defines a lot of predefined data types: character strings of fixed and variable size, character large objects (CLOB), binary strings of fixed and variable size, binary large objects (BLOB), numeric, boolean, datetime, interval, xml. Beyond there are complex types like: ROW, REF(erence), ARRAY, MULTISET and user-definded types (UDT). The predefined data types are explained on the next page. To keep things simple we use on this page only CHAR, VARCHAR and DECIMAL.
Default Value
A column can have a default value. Its data type corresponds to the type of the column. It may be a constant value like the number -1 or the string 'n/a', or it is a system variable or a function call to determine dynamic values like the username or the actual timestamp. The default clause affects those INSERT and MERGE commands, which do not specify the column. In our example database the person table has the column weight with the default value 0. If we omit this column in an INSERT command, the DBMS will store the value 0.
-T h i sI N S E R Tc o m m a n do m i t st h e' w e i g h t 'c o l u m n .T h e r e f o r et h ev a l u e' 0 '( w h i c hi sd i f f e r e n tf r o m -t h eN U L Lv a l u e )i ss t o r e di nt h ew e i g h tc o l u m n . I N S E R TI N T Op e r s o n( i d ,f i r s t n a m e ,l a s t n a m e , d a t e _ o f _ b i r t h , p l a c e _ o f _ b i r t h ,s s n ) V A L U E S ( 1 1 ,' L a r r y ' , ' G o l d s t e i n ' ,D A T E ' 1 9 7 0 1 1 2 0 ' ,' D a l l a s ' , ' 0 7 8 0 5 1 1 2 0 ' ) ; C O M M I T ; -T h i sS E L E C Tr e t r i e v e st h er o w. . . S E L E C T* F R O M p e r s o n W H E R E i d=1 1 A N D w e i g h t=0 ; -. . .b u tn o tt h i so n e : S E L E C T* F R O M p e r s o n W H E R E i d=1 1 A N D w e i g h tI SN U L L ;
Identity Specification
The identity specification serves for the generation of a series of unique values which acts as the Primary Key to the tables rows. The standard defines the syntax as: "GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY". Unfortunatelly most DBMS vendors do not support this formulation. Instead they offer different syntaxes and even different concepts to generate primary key values. Some use a combination of generators/sequences and triggers, others a special data type or different key words. An overview about the wide spread of implementations is available in the wikibook SQL Dialects Reference: Auto-increment_column.
Column Constraint
The column constraint clause specifies conditions which all values must meet. There are different column constraint types: NOT NULL Primary Key
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 66/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Unique Foreign Key Check values The NOT NULL phrase defines, that it is not allowed to store the NULL value in the column.
-T h ec o l u m nc o l _ 1i sp e rd e f i n i t i o nn o ta l l o w e dt oh o l dt h eN U L Lv a l u e C R E A T ET A B L Et 1( c o l _ 1D E C I M A LN O TN U L L ) ; -T h i sI N S E R Tc o m m a n dw i l lf a i l I N S E R TI N T Ot 1 ( c o l _ 1 )V A L U E S ( N U L L ) ; -T h es a m ea p p l i e st ot h ef o l l o w i n gU P D A T Ec o m m a n d I N S E R TI N T Ot 1 ( c o l _ 1 )V A L U E S ( 5 ) ; U P D A T Et 1S E Tc o l _ 1=N U L L ;
The PRIMARY KEY phrase defines that the column acts as the Primary Key of the table. This implies that the column is not allowed to store a NULL value and that the values of all rows are distinct from each other.
The UNIQUE constraint has a similar meaning as the PRIMARY KEY phrase. But there are two slightly differences. First, the values of different rows of a UNIQUE column are not allowed to be equal, which is the same as with PK. But they are allowed to hold the NULL value, which is different from PK. The existence of NULL values has an implication. As the term null = null never evaluates to true (it evaluates to unknown) there may exist multiple rows with the NULL value in a column which is defined to be UNIQUE. Second, only one PK definition per table is allowed. In contrast, there may be many UNIQUE constraints (on different columns).
C R E A T ET A B L Et 3( c o l _ 1D E C I M A LU N I Q U E ) ; -w o r k sw e l l I N S E R TI N T Ot 3 ( c o l _ 1 )V A L U E S ( 5 ) ; -f a i l sb e c a u s et h e r ei sa n o t h e rr o ww i t hv a l u e5 I N S E R TI N T Ot 3 ( c o l _ 1 )V A L U E S ( 5 ) ; -w o r k sw e l l I N S E R TI N T Ot 3 ( c o l _ 1 )V A L U E S ( N U L L ) ; -w o r k sa l s o I N S E R TI N T Ot 3 ( c o l _ 1 )V A L U E S ( N U L L ) ; -c h e c kt h er e s u l t s S E L E C T*F R O Mt 3 ;
The FOREIGN KEY condition defines that the column can hold only those values, which are also stored in a different column of (the same or) another table. This different column has to be UNIQUE or a Primary Key, whereas the values of the foreign key column itself may hold identical values for multiple rows. The consequence is that one cannot create a row with a certain value in this column before there isn't a row with exactly this certain value in the referred table. In our example database we have a contact table whose column person_id referes to the id of persons. It makes sense that one cannot store contact values before storing the appropriate person. Foreign Keys are the technic to realise 1:m relationships.
-At a b l ew i t hac o l u m nw h i c hr e f e r e st ot h e' i d 'c o l u m no ft a b l e' p e r s o n ' C R E A T ET A B L Et 4( c o l _ 1D E C I M A LR E F E R E N C E Sp e r s o n ( i d ) ) ; -T h i sI N S E R Tw o r k sa si nt a b l e' p e r s o n 'o fo u re x a m p l ed a t a b a s et h e r ei sar o ww i t hi d=3 . I N S E R TI N T Ot 4 ( c o l _ 1 )V A L U E S ( 3 ) ; -T h i ss t a t e m e n tw i l lf a i la si n' p e r s o n 't h e r ei sn or o ww i t hi d=9 9 .
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
67/110
4/2/2014
I N S E R TI N T Ot 4 ( c o l _ 1 )V A L U E S ( 9 9 ) ;
Structured Query Language/Print version - Wikibooks, open books for an open world
Column checks inspect the values of the column whether they meet the defined criterion. Within such column checks only the actual column is visible. If a condition covers two or more colums (eg.: col_1 > col_2) a table check must be used.
Table Constraint
Table constraints defines rules which are mandatory for the table as a whole. Their sematic and syntax overlaps partially with the previous shown column constraints. Table constraints are defined after the definition of all columns. The syntax starts with the key word CONSTRAINT and includes the possibility to denominate them with a meaningful name, t6_pk , t6_uk and t6_fk in the next example. In the case of any exception most DBMS shows this name as part of the error message - and if you havn't defined one it uses its internal naming conventions which may be very cryptic.
C R E A T ET A B L Et 7( c o l _ 1D E C I M A L , c o l _ 2D E C I M A L , C O N S T R A I N Tt 7 _ c o l _ 1 _ n n C H E C K( c o l _ 1I SN O TN U L L ) , C O N S T R A I N Tt 7 _ c o l _ 2 _ c h e c kC H E C K( c o l _ 2B E T W E E N1A N D1 0 ) ) ;
C R E A T ET A B L Et 8( c o l _ 1D E C I M A L , c o l _ 2D E C I M A L , c o l _ 3D E C I M A L , c o l _ 4D E C I M A L , -c o l _ 1c a nh o l do n l yt h o s ev a l u e sw h i c ha r eg r e a t e rt h a nc o l _ 2 C O N S T R A I N Tt 8 _ c h e c k _ 1C H E C K( c o l _ 1>c o l _ 2 ) , -I fc o l _ 3i sN U L L ,c o l _ 4m u s tb eN U L La l s o C O N S T R A I N Tt 8 _ c h e c k _ 2C H E C K( ( c o l _ 3I S N U L LA N Dc o l _ 4I S N U L L )O R ( c o l _ 3I SN O TN U L LA N Dc o l _ 4I SN O TN U L L ) ) ) ; -T h i st w oI N S E R T sw o r ka st h e ym e e ta l lc o n d i t i o n s I N S E R TI N T Ot 8V A L U E S ( 1 ,0 ,N U L L ,N U L L ) ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
68/110
4/2/2014
I N S E R TI N T Ot 8V A L U E S ( 2 ,0 ,5 ,5 ) ;
Structured Query Language/Print version - Wikibooks, open books for an open world
-A g a i n :M y S Q Li g n o r e sc h e c kc o n d i t i o n ss i l e n t l y -T h i sI N S E R Tf a i l sb e c a u s ec o l _ 1i sn o tg r e a t e rt h a nc o l _ 2 I N S E R TI N T Ot 8V A L U E S ( 3 ,6 ,N U L L ,N U L L ) ; -T h i sI N S E R Tf a i l sb e c a u s ec o l _ 3i sn o tn u l la n dc o l _ 4i sn u l l I N S E R TI N T Ot 8V A L U E S ( 4 ,0 ,5 ,N U L L ) ;
Clean Up
D R O PT A B L Et 1 ; D R O PT A B L Et 2 ; D R O PT A B L Et 3 ; D R O PT A B L Et 4 ; D R O PT A B L Et 5 ; D R O PT A B L Et 6 ; D R O PT A B L Et 7 ; D R O PT A B L Et 8 ;
Exercises
Create a table 'company' with columns 'id' (numeric, primary key), 'name' (strings of variable size up to 200), 'isin' (strings of length 12, not nullable, unique values). Create a solution with column constraints only and another one with table constraints only. Click to see solution
-c o l u m nc o n s t r a i n t so n l y C R E A T ET A B L Ec o m p a n y _ 1( i d D E C I M A LP R I M A R YK E Y , n a m eV A R C H A R ( 2 0 0 ) , i s i nC H A R ( 1 2 )N O TN U L LU N I Q U E ) ; -t a b l ec o n s t r a i n t so n l y C R E A T ET A B L Ec o m p a n y _ 2( i d D E C I M A L , n a m eV A R C H A R ( 2 0 0 ) , i s i nC H A R ( 5 ) , C O N S T R A I N Tc o m p a n y _ 2 _ p kP R I M A R YK E Y( i d ) , C O N S T R A I N Tc o m p a n y _ 2 _ u kU N I Q U E ( i s i n ) , C O N S T R A I N Tc o m p a n y _ 2 _ c h e c k _ i s i nC H E C K( i s i nI SN O TN U L L ) ) ;
Create a table 'accessory' with columns 'id' (numeric, primary key), 'name' (strings of variable size up to 200, unique), 'hobby_id' (decimal, not nullable, foreing key to column 'id' of table 'hobby'). Create a solution with column constraints only and another one with table constraints only. Click to see solution
-c o l u m nc o n s t r a i n t so n l y C R E A T ET A B L Ea c c e s s o r y _ 1( i d D E C I M A LP R I M A R YK E Y , n a m e V A R C H A R ( 2 0 0 )U N I Q U E , h o b b y _ i dD E C I M A LN O TN U L LR E F E R E N C E Sh o b b y ( i d ) ) ; -t a b l ec o n s t r a i n t so n l y C R E A T ET A B L Ea c c e s s o r y _ 2( i d D E C I M A L , n a m e V A R C H A R ( 2 0 0 ) , h o b b y _ i dD E C I M A L , C O N S T R A I N Ta c c e s s o r y _ 2 _ p kP R I M A R YK E Y( i d ) , C O N S T R A I N Ta c c e s s o r y _ 2 _ u kU N I Q U E ( n a m e ) , C O N S T R A I N Ta c c e s s o r y _ 2 _ c h e c k _ 1 C H E C K( h o b b y _ i dI SN O TN U L L ) , C O N S T R A I N Ta c c e s s o r y _ 2 _ f kF O R E I G NK E Y( h o b b y _ i d )R E F E R E N C E Sh o b b y ( i d ) ) ; -T e s ts o m el e g a la n di l l e g a lv a l u e s I N S E R TI N T Oa c c e s s o r y _ 1V A L U E S( 1 ,' F i s h i n g r o d ' ,2 ) ; C O M M I T ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
69/110
4/2/2014
-. . .
Structured Query Language/Print version - Wikibooks, open books for an open world
Classic Track
The main drive behind a relational database is to increase accuracy by increasing the efficiency with which data is stored. For example, the names of each of the millions of people who immigrated to the United States through Ellis Island at the turn of the 20th century were recorded by hand on large sheets of paper; people from the city of London had their country of origin entered as England, or Great Britain, or United Kingdom, or U.K., or UK, or Engl., etc. Multiple ways of recording the same information leads to future confusion when there is a need to simply know how many people came from the country now known as the United Kingdom. The modern solution to this problem is the database. A single entry is made for each country, for example, in a reference list that might be called the Country table. When someone needs to indicate the United Kingdom, he only has one choice available to him from the list: a single entry called "United Kingdom". In this example, "United Kingdom" is the unique representation of a country, and any further information about this country can use the same term from the same list to refer to the same country. For example, a list of telephone country codes and a list of European castles both need to refer to countries; by using the same Country table to provide this identical information to both of the new lists, we've established new relationships among different lists that only have one item in common: country. A relational database, therefore, is simply a collection of lists that share some common pieces of information.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
70/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
id_employee the primary key an integer firstname a column lastname phone mail And the company employees would be stored like this: employee id_employee firstname 1 2 3 4 5
a column value
phone
The data stored in a table is called entities. As a table is usually represented as an array, the data attributes (first name, last name...) are called columns and the records (the employees) are called rows. i d _ e m p l o y e eis a database specific technical identifier called a primary key. It is used to link the entities from a table to another. To do so, it must be unique for each row. A primary key is usually underlined. Any unique attribute (for instance, the mail) or group of attributes (for instance, the first name and last name) can be the table primary key but it is recommended to use an additional technical id (id_employee) for primary key. Let's create a second table called p r o j e c twhich stores the company projects:
employee id_employee an integer firstname lastname phone mail a string of characters a string of characters 10 numbers a string of characters
employee id_employee firstname 1 2 3 4 5 Big John Linus Jimmy Larry lastname BOSS DOE WALES PAGE phone mail id_project 1 2 3 name Google Linux project created_on ended_on # manager 1998-09-08 NULL 1991-01-01 NULL 5 3 4 936854270 [email protected] 936854271 [email protected] 936854273 [email protected] 936854274 [email protected]
i d _ p r o j e c tis
the primary key of the project table and m a n a g e ris a foreign key. A foreign key is a technical id which is equal to one of the primary keys stored in another table (here, the employee table). Doing this, the Google project is linked to the employee Larry PAGE. This link is called a relationship. A foreign key is usually preceded by a sharp. Note that several projects can point to a common manager so an employee can be the manager of several projects. Now, we want to create, not a single link, but multiple links. So we create a junction table. A junction table is a table that isn't used to store data but links the entities of other tables. Let's create a table called m e m b e r swhich links employees to project:
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
71/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
employee id_employee an integer firstname lastname phone mail a string of characters a string of characters 10 numbers a string of characters members # id_employee an integer # id_project an integer name
project id_project an integer a string of characters created_on a date ended_on a date # manager an integer
And the employees and the projects can be linked like this:
employee id_employee firstname 1 2 3 4 5 6 7 Big John Linus Jimmy Larry Max Jenny lastname BOSS DOE TORVALDS WALES PAGE THE GOOGLER THE WIKIPEDIAN phone mail id_project 1 2 3 name Google Linux Wikipedia project created_on ended_on 1998-0908 1991-0101 2001-0101 NULL NULL NULL # manager 5 3 4 936854270 [email protected] 936854271 [email protected] 936854272 [email protected] 936854273 [email protected] 936854274 [email protected] 936854275 [email protected] jenny.the936854276 [email protected]
An employee can be associated to several projects (John DOE with Google and Wikipedia) and a project can be associated to several employees (Wikipedia with Jimmy, John and Jenny), which is impossible with just a foreign key. A junction table hasn't its own primary key. Its primary key is the couple of foreign keys, as this couple is unique. A junction table can link more than two entity tables by containing more columns.
Relationships
So let's list the different types of relationships: One to one, One to many (for instance, the manager of a project), Many to many (for instance, the members of the projects). For each type of relationships, there is a way to link the entities : One to many relationship: create a foreign key from an entity table to the other, Many to many relationship: create a junction table, One to one relationship: just merge the two tables. Now you know how to design a database schema and to put the data of your information system into it. Data Query Language is used to extract data from the database. It doesn't modify any data in the database. It describes only one query: SELECT.
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Each column has a type. Here are the standard SQL data types: Data type VARCHAR(n) CHAR(n) SMALLINT INTEGER FLOAT DATE TIME TIMESTAMP BLOB Explanation A string with a maximum length of n A string with a fixed length of n A 16 bits signed integer A 32 bits signed integer A decimal floating point A date (YYYY-MM-DD) A date and hour Any binary data Allowed values
[ 0 9 a z A Z ] + { n } [ 0 9 a z A Z ] { n } \ ? [ 0 9 ] + \ ? [ 0 9 ] + \ ? [ 0 9 ] + [ \ . [ 0 9 ] + ] ?
NUMBER(n,[d]) A number with n digits (and d decimal digits if mentioned) \ ? [ 0 9 ] + [ \ . [ 0 9 ] + ] ? A time period of sixty minutes; one twenty-fourth of a day [ 0 2 ] [ 0 9 ] \ : [ 0 5 ] [ 0 9 ] \ : [ 0 5 ] [ 0 9 ]
[ 0 9 ] +
[ 0 9 ] [ 0 9 ] [ 0 9 ] [ 0 9 ] \ [ 0 1 ] [ 0 9 ] \ [ 0 3 ] [ 0 9 ] 2009-03-24
Any
SELECT query
The exhaustive syntax of the SELECT query is as follows:
S E L E C T [A L L |D I S T I N C T ]< C O L U M Nn a m e > [ [A S ]< a l i a s > ] [ , [A L L |D I S T I N C T ]< C O L U M Nn a m e > [ [A S ]< a l i a s > ] ] * F R O M< t a b l e > [ [A S ]< a l i a s > | [ [F U L L |L E F T |R I G H T ]O U T E R |I N N E R ]J O I N< t a b l e >O N< e x p r e s s i o n > ] [ ,< t a b l e > [ [A S ]< a l i a s > | [ [F U L L |L E F T |R I G H T ]O U T E R |I N N E R ]J O I N< t a b l e >O N< e x p r e s s i o n > ] ] * [ W H E R E< p r e d i c a t e > [ {A N D |O R }< p r e d i c a t e > ] * ] [ G R O U PB Y< C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * [ H A V I N G< p r e d i c a t e > [ {A N D |O R }< p r e d i c a t e > ] ] * ] ] [ O R D E RB Y< C O L U M Nn a m e > [A S C |D E S C ] [ ,< C O L U M Nn a m e > [A S C |D E S C ] ] * ] [ F E T C HF I R S T< c o u n t >R O W SO N L Y ] ;
First query
Let's create the table r e u n i o nwith many columns: reunion id_reunion INTEGER name priority planned date hour duration VARCHAR(20) CHAR(1) SMALLINT DATE TIME INTEGER description VARCHAR(255)
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
73/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
reunion id_reunion 1 2 3 4 5 6 name Planning Progress Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B 1 1 1 0 1 1 date hour duration # id_office 35 13 41 27 7 11 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120
Let's do a simple query. The following query just returns the content of the reunion table: Query:
S E L E C T* F R O Mr e u n i o n ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | 6 | L e a r n i n g | An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l e d .| B | 1 | 2 0 0 9 0 9 2 1| 1 6 : 0 0 : 0 0| 1 2 0 | 1 1 | 7 8 5 2 7 8 . . . 3 7 5 2 8 | -
The form of the result depends on the client application. It can be returned as a text output (backend), a HTML page (thin client), a program object (middleware) etc... The statements, queries, clauses (SELECT, FROM...), instructions and operators are not case sensitive but they are commonly written in uppercase for readability. The SELECT and FROM clauses are the two required clauses of a SELECT query: FROM : list the tables the query uses to return the data, SELECT : list the data to return.
WHERE clause
The WHERE clause doesn't influence the columns the query returns but the rows. It filters the rows applying predicates on it. A predicate specifies conditions that can be true or false. SQL can handle conditions whose result is unknown. For example, the following query returns the reunions which have a B priority level: Query:
S E L E C T* F R O Mr e u n i o n W H E R Er e u n i o n . p r i o r i t y=' B ' ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | 6 | L e a r n i n g | An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l e d .| B | 1 | 2 0 0 9 0 9 2 1| 1 6 : 0 0 : 0 0| 1 2 0 | 1 1 | 7 8 5 2 7 8 . . . 3 7 5 2 8 | -
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
74/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Predicate Compared to the second operand, the first operand can be : equal : = different : < > lesser : < lesser or equal : < = greater : > greater or equal : > = The following query returns the reunions which have another priority level than B: Query:
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | -
Operators The WHERE clause can have several conditions using the operators AND (all the conditions must be true) and OR (only one condition needs to be true). The operator OR is inclusive (several conditions can be true). The order of evaluation can be indicated with brackets. NOT inverts a condition. The following query returns the reunions which have a B priority level and last more than an hour or which take place on 2008/05/12: Query:
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 6 | L e a r n i n g | An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l e d .| B | 1 | 2 0 0 9 0 9 2 1| 1 6 : 0 0 : 0 0| 1 2 0 | 1 1 | 7 8 5 2 7 8 . . . 3 7 5 2 8 | -
LIKE LIKE allows simplified regular expression matching. It can be applied on the text columns (CHAR, VARCHAR,...). Alphanumerical characters only match identical text, %is a wildcard that matches any text, _is a wildcard that matches any single character, The following query returns the reunions which end with "ing" and which contain " the " in its description: Query:
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
75/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | -
BETWEEN and IN BETWEEN matches a range of values that can be numbers, dates or times. IN matches a list of allowed values. The following query returns the reunions which take place between 2008-04-01 and 2009-04-01 and have an A, B or D priority level: Query:
S E L E C T* F R O Mr e u n i o n W H E R ED A T EB E T W E E N' 2 0 0 8 0 4 0 1 'A N D' 2 0 0 9 0 4 0 1 'A N Dp r i o r i t yI N( ' A ' ,' B ' ,' D ' ) ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | -
EXISTS EXISTS is usually used with a subselect. This predicate is true if the list (i.e. the result set of a subselect) is not empty. This keyword allows to filter the returned rows using data that are not directly associated to the returned rows (i.e. they are not joined, not linked, not related... to the returned rows) so you can not use junction in this case. For instance, we want to retrieve all the reunions for which there is at least one reunion two times longer: Query:
S E L E C T* F R O Mr e u n i o nr 1 W H E R EE X I S T S( S E L E C Tr 2 . i d _ r e u n i o n F R O Mr e u n i o nr 2 W H E R Er 2 . d u r a t i o n=r 1 . d u r a t i o n*2 ) ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | -
The duration of another reunion is used in this query whereas there is no join, no link and no relationship between the two rows. This condition can not be done without EXISTS. Note that the subselect uses the alias r1 whereas this alias is defined in the main query. EXISTS is also used to match a lack of data. Let's remember the employee table and the members table:
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 76/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
members employee id_employee firstname 1 2 3 4 5 6 7 Big John Linus Jimmy Larry Max Jenny DOE TORVALDS WALES PAGE THE GOOGLER lastname BOSS phone mail 936854270 [email protected] 936854271 [email protected] 936854272 [email protected] 936854273 [email protected] 936854274 [email protected] 936854275 [email protected] # id_employee # id_project 3 2 4 5 2 6 7 2 1 3 1 3 1 3
The following query returns the employees who are not linked to any project (i.e. the ones there is no relationship for them in the members table): Query:
S E L E C T* F R O Me m p l o y e e se W H E R EN O TE X I S T S( S E L E C Tm . i d _ e m p l o y e e F R O Mm e m b e r sm W H E R Em . i d _ e m p l o y e e=e . i d _ e m p l o y e e ) ;
Result:
| | | i d _ e m p l o y e e| f i r s t n a m e| l a s t n a m e| p h o n e | m a i l | | | | | | | | 1 | B i g | B O S S | 9 3 6 8 5 4 2 7 0| b i g . b o s s @ c o m p a n y . c o m| | |
IS NULL IS NULL tests if a column is filled. It is often used for foreign key columns.
FROM clause
The FROM clause defines the tables that are used for the query but it can also join tables. A JOIN builds a super table with the columns of two tables to be used for the query. To explain what a join is, we consider two archaic tables without primary keys nor foreign keys:
table_1 common_value specific_value_1 red grey white purple purple black 9999 6666 0000 7777 2222 8888 green yellow black red red blue
We want to associate values from columns of different tables matching values on a given column in each table. FULL OUTER JOIN A JOIN is made matching a column on a table to a column on the other table. After a FULL OUTER JOIN, for a given value (red), for a given row with this value on one table ([ red | 9999 ]), one row is created for each row that matches on the other table ([ red | OOOOOO ] and [ red | LLLLLL ]). If a value exists in only one table, then a row is created and is completed with NULL columns.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 77/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
9999 9999 6666 0000 7777 2222 8888 NULL NULL NULL
OOOOOO LLLLLL NULL NULL NULL NULL FFFFFF HHHHHH PPPPPP RRRRRR
RIGHT OUTER JOIN The RIGHT OUTER JOIN is like the FULL OUTER JOIN but it doesn't create row for values that don't exist on the left table.
LEFT OUTER JOIN The LEFT OUTER JOIN is like the FULL OUTER JOIN but it doesn't create row for values that don't exist on the right table.
INNER JOIN The INNER JOIN is like the FULL OUTER JOIN but it creates row only for values that exist on both the left table and the right table.
red black
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
78/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Alias The FROM clause can declare several tables, separated by ,and aliases can be defined for table name with the keyword AS, which allows the user to make several joins with the same tables. The following query is equivalent to the INNER JOIN above: Query:
S E L E C T* F R O Mt a b l e _ 1A St 1 ,t a b l e _ 2A St 2 W H E R Et 1 . c o m m o n _ v a l u e=t 2 . c o m m o n _ v a l u e
SELECT clause
The SELECT clause doesn't influence the data processed by the query but the data returned to the user. *return all the data processed after joining and filtering. Otherwise, the SELECT clause lists expressions separated by , . The expressions can be a table name, a table name and a column name separated by a dot or simply a column name if it is not ambiguous. The SELECT clause also allows evaluated expressions like addition, subtraction, concatenation, ... An expression can be followed by an alias with the keyword AS. The keyword AS can be omitted. Here is an example: Query:
Result:
| | | i d _ r e u n i o n| n | p| p l a n| r e u n i o n _ l e n g t h| | | | | | | | 1 | P l a n n i n g:W en e e dt op l a nt h ep r o j e c t . | A| 1 0 | 7 0 | | 2 | P r o g r e s s:W h a tw eh a v ed o n e . | C| 1 0 | 4 0 | | 3 | C h a n g e:W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B| 1 0 | 1 0 0 | | 4 | P r e s e n t a t i o n:P r e s e n t a t i o no ft h ep r o j e c t . | D| 0 | 1 3 0 | | 5 | R e p o r t i n g:E x p l a n a t i o nt ot h en e wb e g i n n e r . | B| 1 0 | 7 0 | | 6 | L e a r n i n g:An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l . . .| B| 1 0 | 1 3 0 | | |
S E L E C TC O U N T ( * )*1 0A Sc ,M A X ( D A T E )A Sl a t e s t _ d a t e ,M I N ( r e u n i o n . D A T E )o l d e s t _ d a t e F R O Mr e u n i o n ;
Result:
| | | c | l a t e s t _ d a t e| o l d e s t _ d a t e| | | | | | 6 0| 2 0 0 9 0 9 2 1 | 2 0 0 8 0 3 2 4 | | |
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
79/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
ORDER BY clause
The ORDER BY clause sorts the rows returned by the query by one or several columns. The sort is done with the first column mentioned. The second column is used to sort the rows which have the same value in the first column and so on. The keywords ASC or DESC can be added after each column. ASC indicates an ascending sort. DESC indicates a descending sort. Default is a descending sort. Let's do two simple requests, the first sorting by only one column and the second sorting by two columns: Query:
S E L E C T* F R O Mr e u n i o n O R D E RB Yp r i o r i t yA S C ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | 6 | L e a r n i n g | An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l e d .| B | 1 | 2 0 0 9 0 9 2 1| 1 6 : 0 0 : 0 0| 1 2 0 | 1 1 | 7 8 5 2 7 8 . . . 3 7 5 2 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | -
Query:
S E L E C T* F R O Mr e u n i o n O R D E RB Yp r i o r i t yA S C ,d u r a t i o nD E S C ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 6 | L e a r n i n g | An e ws o f t w a r ev e r s i o nh a sb e e ni n s t a l l e d .| B | 1 | 2 0 0 9 0 9 2 1| 1 6 : 0 0 : 0 0| 1 2 0 | 1 1 | 7 8 5 2 7 8 . . . 3 7 5 2 8 | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4 | 5 | R e p o r t i n g | E x p l a n a t i o nt ot h en e wb e g i n n e r . | B | 1 | 2 0 0 9 0 3 1 5| 1 4 : 0 0 : 0 0| 6 0 | 7 | 1 9 7 3 9 . . . 3 7 7 1 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | -
GROUP BY clause
The GROUP BY clause is used for aggregation operations. It gathers the rows into groups, for instance, all the rows that have the same value in a given column. After gathering rows into groups, any aggregation operation is applied on each group instead of a unique big group of rows. As a consequence, an aggregation operation will return as many result as the number of groups. Groups can be formed with all the rows that have the same value for a given column or the same combination of values for several given columns. For instance, we want to know the number of reunions for each type of priority: Query:
S E L E C TC O U N T ( * )A SN U M B E R ,p r i o r i t y F R O Mr e u n i o n G R O U PB Yp r i o r i t y ;
Result:
| | | n u m b e r| p r i o r i t y| | | | | 1 | A | | 3 | B |
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
80/110
4/2/2014
| 1 | C | | 1 | D | | |
Structured Query Language/Print version - Wikibooks, open books for an open world
Due to the GROUP BY clause, the aggregation function count(*) doesn't return a global count but a count for each priority level (A, B, C and D). Query:
S E L E C TC O U N T ( * )A SN U M B E R ,p l a n n e d ,d u r a t i o n F R O Mr e u n i o n G R O U PB Yp l a n n e d ,d u r a t i o n ;
Result:
| | | n u m b e r| p l a n n e d| d u r a t i o n| | | | | | 1 | 0 | 1 2 0 | | 1 | 1 | 3 0 | | 2 | 1 | 6 0 | | 1 | 1 | 9 0 | | 1 | 1 | 1 2 0 | | |
Note that there are four groups with 1 for the column p l a n n e dand there are two groups with 120 for the column d u r a t i o n . However, you can see that there is no group with the same combination of values from the two columns.
HAVING clause
The HAVING clause is used with the GROUP BY clause. The HAVING clause contains a predicate and removes from the returned rows the groups for which the predicate is false. For example, we want to retrieve only the priorities for which there are at least two reunions with the same priority level: Query:
S E L E C Tp r i o r i t y F R O Mr e u n i o n G R O U PB Yp r i o r i t y H A V I N GC O U N T ( * )>1 ;
Result:
| | | p r i o r i t y| | | | B | | |
S E L E C T* F R O Mr e u n i o n F E T C HF I R S T4R O W SO N L Y ;
Result:
| | i d _ r e u n i o n| n a m e | d e s c r i p t i o n | p r i o r i t y| p l a n n e d| d a t e | h o u r | d u r a t i o n| i d _ o f f i c e| p d f _ r e p o r t | | | | | | | | | | | 1 | P l a n n i n g | W en e e dt op l a nt h ep r o j e c t . | A | 1 | 2 0 0 8 0 3 2 4| 1 0 : 3 0 : 0 0| 6 0 | 3 5 | 4 8 6 4 4 . . . 8 4 6 3 4 8 | 2 | P r o g r e s s | W h a tw eh a v ed o n e . | C | 1 | 2 0 0 8 0 5 1 2| 1 4 : 0 0 : 0 0| 3 0 | 1 3 | 9 8 6 2 . . . 1 5 6 7 6 | 3 | C h a n g e | W h a tw en e e dt oc h a n g ei nt h ep r o j e c t . | B | 1 | 2 0 0 8 0 6 0 3| 9 : 3 0 : 0 0 | 9 0 | 4 1 | 3 4 8 7 6 . . . 4 8 4 6 5 4
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
81/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
| 4 | P r e s e n t a t i o n| P r e s e n t a t i o no ft h ep r o j e c t . | D | 0 | 2 0 0 8 0 9 1 1| 1 5 : 3 0 : 0 0| 1 2 0 | 2 7 | N U L L | -
This clause is often used not to return useless rows for test or to improve the performance. Now you can explore all the data of an already existing database.
SQL Functions
COUNT AVG MIN MAX SUM Eg:
S E L E C T' ' ' C O U N T ( * ) ' ' 'F R O Mr e u n i o n
returns the number of rows in the table reunion. --See also: [[1] (http://en.wikibooks.org/wiki/Oracle_Programming/SQL_Cheatsheet)] Data Manipulation Language is used to modify the records in the database. It never modifies the schema of the database (table features, relationships, ...). It describes three statements: INSERT, UPDATE and DELETE.
INSERT statement
The exhaustive syntax of the INSERT statement is as follows:
I N S E R TI N T O< T A B L En a m e > [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] { V A L U E S( < v a l u e > [ ,< v a l u e > ] * ) | S E L E C T[ A L L|D I S T I N C T ]< C O L U M Nn a m e >[ ,[ A L L|D I S T I N C T ]< C O L U M Nn a m e > ] * F R O M< t a b l e >[ [ A S|= ]< a l i a s >|[ [ F U L L|L E F T|R I G H T ]O U T E R|I N N E R ]J O I N< t a b l e >O N< e x p r e s s i o n > ] [ ,< t a b l e >[ [ A S|= ]< a l i a s >|[ [ F U L L|L E F T|R I G H T ]O U T E R|I N N E R ]J O I N< t a b l e >O N< e x p r e s s i o n > ] ] * [ W H E R E< p r e d i c a t e >[ { A N D|O R }< p r e d i c a t e > ] * ] [ G R O U PB Y< C O L U M Nn a m e >[ ,< C O L U M Nn a m e > ] * [ H A V I N G< p r e d i c a t e >[ { A N D|O R }< p r e d i c a t e > ] ] * ] ] [ O R D E RB Y< C O L U M Nn a m e >[ A S C|D E S C ][ ,< C O L U M Nn a m e >[ A S C|D E S C ] ] * ] [ L I M I T< c o u n t > ] } ;
The INSERT statement is used to add new records (rows) in a table. For instance, we want to add a new reunion: Its primary key is 7, Its name is "Job interview", Its description is "Meeting with Mr. SPENCER", Its priority is B, Its planned, Its date is on October 28, 2009, Its hour is 18:30:00, Its duration is 30, Its office technical id is 23, There is no pdf report.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
82/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
reunion id_reunion 1 2 3 4 5 6 Query: name Planning Progress Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B 1 1 1 0 1 1 date hour duration # id_office 35 13 41 27 7 11 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120
The table after the statement: reunion id_reunion 1 2 3 4 5 6 7 name Planning Progress Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B 1 1 1 0 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30
The INTO clause contains the name of the table where the record needs to be inserted. It can be followed by a list of columns in brackets. The VALUES clause contains the values to insert in brackets. If the column names are omitted, the VALUES clause must contains as many values as the number of columns of the table. The values are inserted in the table columns in the same order that the order in which the columns have been declared in the table. If the column names are mentioned, there must be as many column names as values. The values are respectively inserted into the named columns. If a column in the table is omitted, a NULL value is inserted instead. The VALUES clause can be replaced by an inner SELECT statement. In this case, the INSERT statement can insert several rows in the table. For example, we want to plan twice all the reunion with a B priority level, one year later: The table before the statement: reunion id_reunion 1 2 3 4 5 6 7 Query: name Planning Progress Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B 1 1 1 0 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
83/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The table after the statement: reunion id_reunion 1 2 3 4 5 6 7 10 12 13 14 name Planning Progress Change Reporting Learning Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B B B B 1 1 1 0 1 1 1 1 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 41 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30 2009-06-03 9:30:00 90 2010-03-15 14:00:00 60 2010-09-21 16:00:00 120 2010-10-28 18:30:00 30
A new software version has been installed. B What we need to change in the project. Explanation to the new beginner.
UPDATE statement
The exhaustive syntax of the UPDATE statement is as follows:
U P D A T E< t a b l en a m e > S E T< c o l u m nn a m e >=< v a l u e > [ ,< c o l u m nn a m e >=< v a l u e > ] * W H E R E< p r e d i c a t e >[ { A N D|O R }< p r e d i c a t e > ] * ;
The UPDATE statement is used to modify already existent records in a table. The UPDATE clause is followed by the table name in which the rows need to be changed. The SET clause is followed by couples of column name and value. The values will be inserted in the given columns. The WHERE clause contains predicates. If the predicates are true for an existent row, this row will be modified. For instance, we want to change the date, the hour and the description of the reunion with id 14:
The table before the statement: reunion id_reunion 1 2 3 4 5 6 7 10 12 13 14 Query: name Planning Progress Change Reporting Learning Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B B B B 1 1 1 0 1 1 1 1 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 41 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30 2009-06-03 9:30:00 90 2010-03-15 14:00:00 60 2010-09-21 16:00:00 120 2010-10-28 18:30:00 30
A new software version has been installed. B What we need to change in the project. Explanation to the new beginner.
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
reunion id_reunion 1 2 3 4 5 6 7 10 12 13 14 name Planning Progress Change Reporting Learning Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B B B B 1 1 1 0 1 1 1 1 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 41 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30 2009-06-03 9:30:00 90 2010-03-15 14:00:00 60 2010-09-21 16:00:00 120 2010-02-11 08:00:00 30
A new software version has been installed. B What we need to change in the project. Explanation to the new beginner.
DELETE statement
The exhaustive syntax of the DELETE statement is as follows:
D E L E T EF R O M< t a b l en a m e > [ W H E R E< p r e d i c a t e >[ { A N D|O R }< p r e d i c a t e > ] * ] ;
The DELETE statement is used to remove specific rows in a table with conditions. The FROM clause is followed by the table name in which the rows need to be removed. The WHERE clause contains predicates. If the predicates are true for an row, this row will be removed. If the predicates are false for all the rows, the statement do nothing. A DELETE statement without WHERE clause empties the table. For example, we want to remove all the reunions that last two hours:
The table before the statement: reunion id_reunion 1 2 3 4 5 6 7 10 12 13 14 Query: name Planning Progress Change Reporting Learning Change Reporting Learning description We need to plan the project. What we have done. What we need to change in the project. Explanation to the new beginner. priority planned A C B D B B B B B 1 1 1 0 1 1 1 1 1 1 1 date hour duration # id_office 35 13 41 27 7 11 23 41 7 11 23 19739...37718 785278...37528 pdf_report 48644...846348 9862...15676 34876...4846548 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2008-09-11 15:30:00 120 2009-03-15 14:00:00 60 2009-09-21 16:00:00 120 2009-10-28 18:30:00 30 2009-06-03 9:30:00 90 2010-03-15 14:00:00 60 2010-09-21 16:00:00 120 2010-02-11 08:00:00 30
A new software version has been installed. B What we need to change in the project. Explanation to the new beginner.
D E L E T EF R O Mr e u n i o n W H E R Ed u r a t i o n=1 2 0 ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
85/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
reunion id_reunion 1 2 3 5 7 10 12 14 name Planning Progress Change Reporting Change Reporting description We need to plan the project. What we have done. Explanation to the new beginner. priority planned A C B B B B 1 1 1 1 1 1 1 1 date hour duration # id_office 35 13 41 7 23 41 7 23 pdf_report 48644...846348 9862...15676 34876...4846548 19739...37718 2008-03-24 10:30:00 60 2008-05-12 14:00:00 30 2008-06-03 9:30:00 90 2009-03-15 14:00:00 60 2009-10-28 18:30:00 30 2009-06-03 9:30:00 90 2010-03-15 14:00:00 60 2010-02-11 08:00:00 30
Job interview Meeting with Mr. SPENCER Explanation to the new beginner.
Now you can use an already existing database schema to handle your own data. Data Definition Language is used to modify the schema of the database. It will never impact the user rights for the database. Otherwise, it can erase records in some tables. It describes three statements: CREATE, ALTER and DROP.
CREATE statement
The exhaustive syntax of the CREATE statement for the tables is as follows:
C R E A T ET A B L E< T A B L En a m e > ( < C O L U M Nn a m e >< C O L U M Nt y p e > [N O TN U L L ] [P R I M A R YK E Y |D E F A U L T< v a l u e > ] [ ,< C O L U M Nn a m e >< C O L U M Nt y p e > [N O TN U L L ] [P R I M A R YK E Y |D E F A U L T< v a l u e [ , [C O N S T R A I N T< C O N S T R A I N Tn a m e > ] { P R I M A R YK E Y( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) | U N I Q U E( [ V A L U E | < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ] ) | F O R E I G NK E Y( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * )R E F E R E N C E S< T A B L En a m e >( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) [O ND E L E T EC A S C A D E ] [O NU P D A T EC A S C A D E | C H E C K( < p r e d i c a t e > [ {A N D |O R }< p r e d i c a t e > ] * ) } ] * ) ;
The CREATE statement is used to create a new table with no record. Let's create the table o f f i c e . The records in the o f f i c etable will contain a technical id, the name of the office, a description, the number of available places, the availability and the date for the next office security control: Query:
C R E A T ET A B L Eo f f i c e ( i d _ o f f i c eI N T E G E RP R I M A R YK E YN O TN U L L , n a m eV A R C H A R ( 2 0 )N O TN U L L , d e s c r i p t i o nV A R C H A R ( 2 5 5 ) , p l a c e _ n u m b e rI N T E G E RN O TN U L L , a v a i l a b l eS M A L L I N TN O TN U L LD E F A U L T1 , n e x t _ i n s p e c t i o nD A T EN O TN U L L ) ;
The table after the statement: office id_office name description available INTEGER VARCHAR(20) VARCHAR(255) SMALLINT
place_number INTEGER next_inspection DATE Now the table o f f i c ecan be used and filled as the tables r e u n i o n ,e m p l o y e e ,p r o j e c tand m e m b e r s :
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
86/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
office
id_office 1 2 3 4 5 6 7 8
name Show room Big room Open space Hall Reunion room Actual office Coffee machine The biggest room.
description
place_number available next_inspection 100 200 50 20 20 5 5 1 1 1 1 1 0 1 1 2011-03-24 2010-06-03 2011-03-15 2010-10-28 2010-05-12 2010-06-03 2011-03-15 2011-02-11
The developer open space. The entrance. This office is under construction. The room where you can pause.
Temporary office The office used while the actual is under construction. 5
The statement starts with CREATE TABLE, to indicate that what we want to create is a table. It's followed by the name of the table (i.e. o f f i c e ). The name of the table is followed by parentheses which describe all the columns of the table. The descriptions of the columns are separated by a comma. Each description contains the column name (for instance, id_office), the column type (INTEGER, VARCHAR, CHAR, DATE, etc...), an optional nullability information (nothing to indicate that the column can be null or NOT NULL to indicate that the column can't be null) and the optional keyword DEFAULT followed by a default value or the optional keyword PRIMARY KEY to indicate that the column is a primary key. If no default value is defined, NULL is the default value. If NOT NULL is defined, the column can't have NULL as default value. You can see that the column i d _ o f f i c ehas been defined as a primary key, the column d e s c r i p t i o ncan be null and the column a v a i l a b l ehas 1as default value.
ALTER statement
The exhaustive syntax of the ALTER statement for the tables is as follows:
A L T E RT A B L E< T A B L En a m e > { A D D [C O L U M N ]< C O L U M Nn a m e >< C O L U M Nt y p e > [N O TN U L L ] [P R I M A R YK E Y |D E F A U L T< v a l u e > ] | A L T E R [C O L U M N ]< C O L U M Nn a m e > [S E TD E F A U L T< D E F A U L To p t i o n > |D R O PD E F A U L T ] | D R O P [C O L U M N ]< C O L U M Nn a m e > | A D D [C O N S T R A I N T< C O N S T R A I N Tn a m e > ] { P R I M A R YK E Y( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) | U N I Q U E( [ V A L U E | < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ] ) | F O R E I G NK E Y( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * )R E F E R E N C E S< T A B L En a m e >( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) [O ND E L E T EC A S C A D E ] [O NU P D A T EC A S C A D E | C H E C K( < p r e d i c a t e > [ {A N D |O R }< p r e d i c a t e > ] * ) } | D R O PC O N S T R A I N T< C O N S T R A I N Tn a m e > } ;
The ALTER statement is used to modify a table. It can be used on a table with records in it.
A L T E RT A B L Eo f f i c eA D DC O N S T R A I N Tu n i q u e _ n a m e _ a n d _ d e s c r i p t i o nU N I Q U E( n a m e ,d e s c r i p t i o n ) ;
Now we can not insert a row with the same name and description of an already existing row and we can not update a row with the same name and description of another row. However, we can insert a row with only the same name or only the same description.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 87/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
A L T E RT A B L Eo f f i c eD R O PC O N S T R A I N Tu n i q u e _ n a m e _ a n d _ d e s c r i p t i o n ;
Now we can insert a row with the same name and description of an already existing row and we can update a row with the same name and description of another row once again.
Temporary office The office used while the actual is under construction. 5
A L T E RT A B L Eo f f i c eA D Dh a s _ v i d e o _ p r o j e c t o rS M A L L I N TD E F A U L T0 ;
The table after the statement: office id_office 1 2 3 4 5 6 7 8 name Show room Big room Open space Hall Reunion room Actual office Coffee machine This office is under construction. The room where you can pause. The biggest room. The developer open space. The entrance. description place_number available next_inspection has_video_projector 100 200 50 20 20 5 5 1 1 1 1 1 0 1 1 2011-03-24 2010-06-03 2011-03-15 2010-10-28 2010-05-12 2010-06-03 2011-03-15 2011-02-11 0 0 0 0 0 0 0 0
Temporary office The office used while the actual is under construction. 5
The column h a s _ v i d e o _ p r o j e c t o rhas been added at the end. The column has been filled with the default value.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
88/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
office
id_office 1 2 3 4 5 6 7 8 Query:
name Show room Big room Open space Hall Reunion room Actual office Coffee machine The biggest room.
description
place_number available next_inspection has_video_projector 100 200 50 20 20 5 5 1 1 1 1 1 0 1 1 2011-03-24 2010-06-03 2011-03-15 2010-10-28 2010-05-12 2010-06-03 2011-03-15 2011-02-11 0 0 0 0 0 0 0 0
The developer open space. The entrance. This office is under construction. The room where you can pause.
Temporary office The office used while the actual is under construction. 5
A L T E RT A B L Eo f f i c eD R O PC O L U M Nn e x t _ i n s p e c t i o n ;
The table after the statement: office id_office 1 2 3 4 5 6 7 8 name Show room Big room Open space Hall Reunion room Actual office Coffee machine This office is under construction. The room where you can pause. The biggest room. The developer open space. The entrance. description place_number available has_video_projector 100 200 50 20 20 5 5 1 1 1 1 1 0 1 1 0 0 0 0 0 0 0 0
Temporary office The office used while the actual is under construction. 5
The column n e x t _ i n s p e c t i o nhas been removed. If you want to remove a column, you need to remove any constraint applied on it (for instance, you could not remove the name or the description column if there is still the unique_name_and_description unicity constraint).
DROP statement
The exhaustive syntax of the DROP statement for the tables is as follows:
D R O PT A B L E< T A B L En a m e > ;
The DROP statement is used to remove table. Now you can use a database for any type of data. Data Control Language is used to modify the user rights for the database. It describes two statements: GRANT and REVOKE.
GRANT statement
The exhaustive syntax of the GRANT statement is as follows:
G R A N T
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
89/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
{ A L LP R I V I L E G E SO N [T A B L E ]< T A B L EO RV I E Wn a m e > | { S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } [ ,{ S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } ] *O N [T A B L E ]< T A B L EO RV I E Wn a m e > | U S A G EO N { D O M A I N< D O M A I Nn a m e > | C O L L A T I O N< c o l l a t i o nn a m e > | C H A R A C T E RS E T< c h a r s e tn a m e > | T R A N S L A T I O N< t r a n s l a t i o nn a m e > } | R E F E R E N C E S< C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] *O N< T A B L En a m e > } [ , { A L LP R I V I L E G E SO N [T A B L E ]< T A B L EO RV I E Wn a m e > | { S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } [, { S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } ] *O N [T A B L E ]< T A B L EO RV I E Wn a m e > | U S A G EO N { D O M A I N< D O M A I Nn a m e > | C O L L A T I O N< c o l l a t i o nn a m e > | C H A R A C T E RS E T< c h a r s e tn a m e > | T R A N S L A T I O N< t r a n s l a t i o nn a m e > } | R E F E R E N C E S< C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] *O N< T A B L En a m e > } ] *T O{ P U B L I C | < U S E Rn a m e > } [ ,{ P U B L I C | < U S E Rn a m e > } ] * [W I T HG R A N TO P T I O N ] ;
The GRANT statement is used to give a privilege to someone. Any SQL operations are done using a user name. The user name are created by the database management system.
DBA
Developer 1
Developer 2
Developer 3
User 1
User 2
The privileges apply on the tables (i.e. e m p l o y e e ,o f f i c e , etc...), the views, their columns, the domain, the collation, the charset and the translation.
The privileges can allow to process SELECT ("s"), INSERT ("i"), UPDATE ("u") and DELETE ("d") statements (not CREATE, ALTER or DROP statements). Let's say that only the DataBase Administrator has the privileges.
Developer 1 employee
Developer 2 employee
Developer 3 employee
User 1 employee
User 2 employee
office ...
office ...
office ...
office ...
office ...
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
90/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
For each privilege ("s", "i", "u" and "d"), there is also a meta-privilege ("S", "I", "U" and "D") : a user can send a privilege to another user. Let's say that only the DataBase Administrator has the meta-privileges.
Developer 1 employee
Developer 2 employee
Developer 3 employee
User 1 employee
User 2 employee
office
office
office
office
office
...
...
...
...
...
G R A N TS E L E C TO Ne m p l o y e eT OD E V E L O P E R _ 1 ;
DBA
Developer 1 employee s
Developer 2 employee
Developer 3 employee
User 1 employee
User 2 employee
office
office
office
office
office
...
...
...
...
...
SELECT indicates that we want to sent the SELECT privilege. The keyword ON followed by e m p l o y e e indicates that the privilege applies on the table e m p l o y e e . The keyword TO followed by D E V E L O P E R _ 1indicates that the privilege has been sent to DEVELOPER_1. The DBA wants to allow DEVELOPER_2 and DEVELOPER_3 to insert, update and delete rows on the table o f f i c e :
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
91/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
G R A N TI N S E R T ,U P D A T E ,D E L E T EO No f f i c eT OD E V E L O P E R _ 2D E V E L O P E R _ 3 ;
Developer 1 employee s
Developer 2 employee
Developer 3 employee
User 1 employee
User 2 employee
office
office i u d
office i u d ...
office
office
...
...
...
...
Whereas you can send several privileges on a table to several users at once, you can't send privileges on several tables at once. If you want to send all the privileges (SELECT, INSERT, UPDATE and DELETE), you can replace the list of privileges by the keywords ALL PRIVILEGES. Now, the DBA wants to allow USER_1 to insert on the table e m p l o y e eand allow him to send this privilege to other users:
G R A N TI N S E R TO Ne m p l o y e eT OU S E R _ 1W I T HG R A N TO P T I O N ;
Developer 1 employee s
Developer 2 employee
Developer 3 employee
User 1 employee S s
User 2 employee
office
office i u d
office i u d ...
office
office
...
...
...
...
92/110
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The keyword WITH GRANT OPTION indicates that we want to send privileges with the meta-privileges to the user. Now, USER_1 can send the SELECT privilege on the table e m p l o y e eto the other users. Let's say that USER_1 wants to allow anyone to process SELECT on the table e m p l o y e e :
G R A N TS E L E C TO NT A B L Ee m p l o y e eT OP U B L I C ;
Developer 1 employee s
Developer 2 employee s
Developer 3 employee s
User 1 employee S s
User 2 employee s
office
office i u d
office i u d ...
office
office
...
...
...
...
The keyword PUBLIC indicates that we want to send privileges to all the users and the new future ones. Let's say that DEVELOPER_3 tries to allow USER_2 to insert records into the table o f f i c e :
G R A N TI N S E R TO NT A B L Eo f f i c eT OU S E R _ 2 ;
Developer 3
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
93/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Developer 1 employee s
Developer 2 employee s
User 1 employee S s
User 2 employee s
office
office i u d
office
office
...
...
The operation has been refused because DEVELOPER_3 hasn't enough privileges.
G R A N TI N S E R T( n a m e ,d e s c r i p t i o n )O NT A B L Eo f f i c eT OU S E R _ 2 ; G R A N TU P D A T E( i d _ o f f i c e ,n a m e )O NT A B L Eo f f i c eT OU S E R _ 2 ;
For INSERT, make all the columns that the user can't fill have default values, are automatically generated or are filled by a trigger before the insertion. Otherwise, the privilege is just useless.
REVOKE statement
The exhaustive syntax of the REVOKE statement is as follows:
R E V O K E [G R A N TO P T I O NF O R ] { A L LP R I V I L E G E SO N [T A B L E ]< T A B L EO RV I E Wn a m e > | { S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } [ ,{ S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } ] *O N [T A B L E ]< T A B L EO RV I E Wn a m e > | U S A G EO N { D O M A I N< D O M A I Nn a m e > | C O L L A T I O N< c o l l a t i o nn a m e > | C H A R A C T E RS E T< c h a r s e tn a m e > | T R A N S L A T I O N< t r a n s l a t i o nn a m e > } | R E F E R E N C E S< C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] *O N< T A B L En a m e > } [ , { { S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } [ ,{ S E L E C T | D E L E T E | { I N S E R T | U P D A T E } [( < C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] * ) ] } ] *O N [T A B L E ]< T A B L EO RV I E Wn a m e > | U S A G EO N { D O M A I N< D O M A I Nn a m e > | C O L L A T I O N< c o l l a t i o nn a m e > | C H A R A C T E RS E T< c h a r s e tn a m e > | T R A N S L A T I O N< t r a n s l a t i o nn a m e > } | R E F E R E N C E S< C O L U M Nn a m e > [ ,< C O L U M Nn a m e > ] *O N< T A B L En a m e > } ] *F R O M{ P U B L I C | < U S E Rn a m e > } [ ,{ P U B L I C | < U S E Rn a m e > } ] * [R E S T R I C T |C A S C A D E ]
The REVOKE statement is used to take back privileges granted to someone. This revocation may be more complicated than you expect. To completely remove a privilege to a user, this privilege must be taken back by all the users that have sent the privilege. For instance, the DBA wants to remove the INSERT and DELETE privileges on the table e m p l o y e eto DEVELOPER_2 and DEVELOPER_3:
R E V O K EI N S E R T ,D E L E T EO NT A B L Eo f f i c eF R O MD E V E L O P E R _ 2 ,D E V E L O P E R _ 3 ;
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
94/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
DBA
Developer 1 employee s
Developer 2 employee s
Developer 3 employee s
User 1 employee S s
User 2 employee s
office
office u
office u ...
office
office
...
...
...
...
If you remove a privilege to a user who was also sent the related meta-privilege (for example, SELECT privilege to USER_1), the operation also removes the meta-privilege. To remove only meta-privileges, add the keywords GRANT OPTION FOR:
R E V O K EG R A N TO P T I O NF O RS E L E C TO NT A B L Ee m p l o y e eF R O MU S E R _ 1 ;
DBA
Developer 1 employee s
Developer 2 employee s
Developer 3 employee s
User 1 employee s
User 2 employee s
office
office u
office u ...
office
office
...
...
...
...
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
It is not recommended to use *in a SELECT clause, due to performance issues. You should only return columns you want to use. As a consequence, you should replace any c o u n t ( * )by a count on one column only.
1 . S E L E C Ti d _ r e u n i o n 2 . F R O Mr e u n i o n 3 . W H E R Ed u r a t i o n-6 0< =0 ;
It forces the rDBMS to compute the value for each line, which is very expensive. You should rather compute yourself the values with literals (0 + 6 0in this case):
1 . S E L E C Ti d _ r e u n i o n 2 . F R O Mr e u n i o n 3 . W H E R Ed u r a t i o n< =6 0 ;
Index
If you often select records sorting or filtering by a given column, you may add an index on this column. The database behavior should not change. The index may make query faster. However, don't add useless indexes as it makes insertion a little bit slower. The exhaustive syntax of the CREATE statement for the indexes is as follows:
The keyword UNIQUE indicates that all the group of values in the columns must be distinct.
Appendices
ACID An acronym for the 4 properties atomicity, consistency, isolation and durability. Any transaction must conform to them. Atomicity means that either all or no data modification will take place. Consistency ensures that transactions transforms the database from one valid state to another valid state. Isolation requires that transactions will not affect each other, even if they run at the same time. Durability means that the modifications will keep into the database even if the system crashs immediately after the transaction. q.v.: ACID A set of properties (name, datatype, size, ...) used to characterize the data items of entities. A group of attributes constructs an entity-type (or table), i.e.: all values of a certain column must conform to the same attributes. Attributes are optionally complemented by constraints.
96/110
Attribute
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Aggregation of one or more physical blocks of a mass device. Usually a block contains numerous rows of one or more tables. Sometimes one row is distributed across several blocks. q.v.: dirty block A certain language element as part of a statement. E.g.: the WHERE clause defines seach criterias. A set of values of a single table which resides on the same position within its rows. Similar to attributes constraints define rules at a higher level, data items must conform to. E.g.: nullability, primary and foreign key, uniqueness, default value, user-defined-criterias like S T A T U S<1 0 . A cursor is a mechanism by which the rows of a table may be acted on (e.g., returned to a host programming language) one at a time. A set of tables. Those tables contain user data and the Data Dictionary.
Database Management A set of computer programs that controls the creation, maintenance and usage of the database. q.v.: DBMS System (DBMS) Data Dictionary (DD) A set of predefined tables where the DBMS stores information about all user defined objects (tables, views, constraints, ...).
Data Control Language A class of statements which defines the access rights to data, e.g: G R A N T. . . ,R E V O K E ,. . .. (DCL) Data Definition Language (DDL) A class of statements which defines logical and physical design of a database, e.g.: C R E A T ET A B L E. . ..
Data Manipulation A class of statements which retrieves and manipulates data, e.g.: S E L E C T. . . ,I N S E R T. . . ,U P D A T E. . . ,D E L E T E. . . ,C O M M I T , Language R O L L B A C K . (DML) Dirty Block Entity Entity-type Expression Foreign key A block whose content has changed in memory, but is still not written to disc. An identifiable object like an employee or a department . An entity is an instance of an entity-type. Usually there are many instances of a certain entity-type. Every entity is stored in one row. Entities of same entity-type are stored in rows of the same table. So entities are a logical construct and rows a physical implementation. A group of attributes describing the structure of entities. As entities of same entity-type are stored in rows of the same table it can be said, that an entity-type describes a table. (Many people tend to use the term entity as a synonym for entity-type.) A certain language element as part of a statement. It can produce either scalar values or a table. A value used to reference a primary key. Its value will match a primary key value outside own table. An index is a construct containing copies of original values and backreferences to their original rows. It's purpose is the provision of a fast access to the original data. To achieve this, an index contains some kind of collocation. Remark: Indexes are not part of the SQL standard. Nevertheless they are part of nearly every DBMS. Junction table Normalization If more than one row of table T1 refers to more than one row of table T2 (many-to-many relationship) you need an intermediate table to store this relationship. The rows of the intermediate table contains the primary keys of T1 and T2 as values. q.v.: Junction_table Tables should conform to special rules - namely First-, Second- and Third-Normal Form. The process of rearranging columns over tables is called normalization. If no value is stored in the a column of a row, we say it stores the null value. So, NULL is a special value that is used to indicate the absence of any data value. For example it makes a difference whether a temperature is measured and stored as 0 degrees or whether the temperature is not measured and hence not stored. One consequence of the existence of null values is that SQL knows not only the boolean values TRUE and FALSE but also a third one: UNKNOWN. A language element of the WHERE clause which specifies conditions that evaluates to the SQL three-valued logic (true/false/unknown). Predicates are used to find rows. A value or a set of values used to identify a single row uniquely. An often used statement which retrieves data from the database. It is introduced by the keyword SELECT and usually contains a predicate. A reference between two different or the same entity. References are not implemented as links. They base upon the values of the entities. A method (and a mathematical theory) to model data as tables (relations), the relationships among each other and all operations on the data. One record in a table containing information about one single entity. A row has exactly one value for each of its columns - in accordance with
97/110
Index
NULL
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
First Normal Form. This value may be NULL. Statement Table (=Relation) A single command which is executed by the DBMS. There are 3 main classes of statements: DML, DDL and DCL. A set of rows of a certain entity-type, i.e. all rows of a certain table have the same structure.
Three Value SQL knows three boolean values: TRUE, FALSE and UNKNOWN. See: NULL. q.v.: 3VL Logic (3VL) Transaction Value View A logical unit of work consisting of one or more modifications to the database. The ACID criterium must be achieved. A transaction is either saved by the C O M M I Tstatement or completely canceled by the R O L L B A C Kstatement. Implementation of a single data item within a certain column of a certain row. (You can think of a cell within a spreadsheet.) A virtual table containing only its definition and no real data. The definition consists of a query to one or more real tables or views. Queries to the view are processed as queries to the underlying real tables.
Some of the above terms correlate to each other at the logical and implemention level. Logical Design entity-type entity data item Implementation table row column value
SQL return codes are used for the diagnosis of programming failures as a result of SQL calls by DB2 programs. An important feature of DB2 programs is the error processing. The error diagnostic containing the SQL return code is held in the field SQLCODE within the DB2 SQLCA block.
SQLCA
The SQL communications area (SQLCA) structure is used within the DB2 program to return error information to the application program. This information in the SQLCA and the SQLCODE field is updated after every API call for the SQL statement.
SQLCODE
The SQLCODE field contains the SQL return code. The code can be zero (0), negative or positive.
0m e a n ss u c c e s s f u le x e c u t i o n . N e g a t i v em e a n su n s u c c e s s f u le x e c u t i o nw i t ha ne r r o r . A ne x a m p l ei s9 1 1w h i c hm e a n sat i m e o u th a so c c u r r e dw i t har o l l b a c k . P o s i t i v em e a n ss u c c e s s f u le x e c u t i o nw i t haw a r n i n g . A ne x a m p l ei s+ 1 0 0w h i c hm e a n sn or o w sf o u n d .
I fy o uh a v ea nS Q Lc o d ew i t hal e t t e ri ni tl o o ka tL e t t e rC o d e sb e l o w .
Zero (Successful)
0 S u c c e s s f u l
o SucessfulBold text
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
98/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
0 6 0I n v a l i dt y p eS p e c i f i c a t i o n :" S p e c " 0 7 9Q U A L I F I E RF O RD E C L A R E DG L O B A LT E M P O R A R YT A B L Et a b l e n a m eM U S TB ES E S S I O N ,N O Tq u a l i f i e r 0 8 4U n a c c e p t a b l eS Q LS t a t e m e n t . 0 9 7T H EU S EO FL O N GV A R C H A RO RL O N GV A R G R A P H I CI SN O TA L L O W E DI NT H I SC O N T E X T 1 0 1S t a t e m e n ti sT o oL o n g ,o rT o oC o m p l e x . 1 0 2S t r i n gc o n s t a n ti st o ol o n g . 1 0 3L i t e r a li sa ni n v a l i dN u m e r i cL i t e r a l . 1 0 4I l l e g a lS y m b o lt o k e n . 1 0 5I n v a l i dS t r i n g . 1 0 7T h eN a m e ," N A M E "i sT o oL o n g ,M a x i m u mA l l o w a b l es i z ei s" S I Z E " . 1 0 8T H EN A M En a m eI SQ U A L I F I E DI N C O R R E C T L Y 1 0 9" C L A U S E "c l a u s ei sn o tp e r m i t t e d . 1 1 0I n v a l i dH e x a d e c i m a lL i t e r a lB e g i n n i n g" S T R I N G " 1 1 1AC o l u m nF u n c t i o nd o e sn o ti n c l u d eac o l u m nn a m e . 1 1 2T h eO p e r a n do faC o l u m nf u n c t i o ni sA n o t h e rC o l u m nF u n c t i o n . 1 1 3I n v a l i dC h a r a c t e rf o u n di nN a m e :" N A M E " ,R e a s o nC o d e -" R E A S O N C O D E " . 1 1 4T H EL O C A T I O NN A M El o c a t i o nD O E SN O TM A T C HT H EC U R R E N TS E R V E R 1 1 5AP R E D I C A T EI sI n v a l i db e c a u s et h ec o m p a r i s o no p e r a t o r" O P E R A T O R "i sf o l l o w e db ya' p a r e n t h e s i z e dl i s t 'o r" B yA n y " o r" A l l "w i t ho u taS u b q u e r y 1 1 7T h en u m b e ro fv a l u e si nt h eI N S E R Td o e sn o tm a t c ht h en u m b e ro fc o l u m n s . 1 1 8T H EO B J E C TT A B L EO RV I E WO FT H ED E L E T EO RU P D A T ES T A T E M E N TI SA L S OI D E N T I F I E DI NAF R O MC L A U S E 1 1 9AC O L U M NI D E N T I F I E DI NAH A V I N GC L A U S EI SN O TI N C L U D E DI NT H EG R O U PB YC L A U S E 1 2 0AW H E R EC L A U S E ,S E TC L A U S E ,V A L U E SC L A U S E ,O RAS E TH O S T V A R I A B L ES T A T E M E N TI N C L U D E SAC O L U M NF U N C T I O N 1 2 1T H EC O L U M Nn a m eI SI D E N T I F I E DM O R ET H A NO N C EI NT H EI N S E R TO RU P D A T EO RS E TT R A N S I T I O NV A R I A B L ES T A T E M E N T 1 2 2AS E L E C TS T A T E M E N TW I T HN OG R O U PB YC L A U S EC O N T A I N SAC O L U M NN A M EA N DAC O L U M NF U N C T I O NI NT H ES E L E C TC L A U S EO RA C O L U M NN A M EI SC O N T A I N E DI NT H ES E L E C TC L A U S EB U TN O TI NT H EG R O U PB YC L A U S E 1 2 3T H EP A R A M E T E RI NP O S I T I O NnI NT H EF U N C T I O Nn a m eM U S TB EAC O N S T A N TO RK E Y W O R D 1 2 5A NI N T E G E RI NT H EO R D E RB YC L A U S ED O E SN O TI D E N T I F YAC O L U M NO FT H ER E S U L T 1 2 6T H ES E L E C TS T A T E M E N TC O N T A I N SB O T HA NU P D A T EC L A U S EA N DA NO R D E RB YC L A U S E 1 2 7D I S T I N C TI SS P E C I F I E DM O R ET H A NO N C EI NAS U B S E L E C T 1 2 8I N V A L I DU S EO FN U L LI NAP R E D I C A T E 1 2 9T H ES T A T E M E N TC O N T A I N ST O OM A N YT A B L EN A M E S 1 3 0T H EE S C A P EC L A U S EC O N S I S T SO FM O R ET H A NO N EC H A R A C T E R ,O RT H ES T R I N GP A T T E R NC O N T A I N SA NI N V A L I DO C C U R R E N C EO FT H E E S C A P EC H A R A C T E R 1 3 1S T A T E M E N TW I T HL I K EP R E D I C A T EH A SI N C O M P A T I B L ED A T AT Y P E S 1 3 2A NO P E R A N DO Fv a l u eI SN O TV A L I D 1 3 3AC O L U M NF U N C T I O NI NAS U B Q U E R YO FAH A V I N GC L A U S EI SI N V A L I DB E C A U S EA L LC O L U M NR E F E R E N C E SI NI T SA R G U M E N TA R E N O TC O R R E L A T E DT OT H EG R O U PB YR E S U L TT H A TT H EH A V I N GC L A U S EI SA P P L I E DT O 1 3 4I M P R O P E RU S EO FL O N GS T R I N GC O L U M Nc o l u m n n a m eO RA NE X P R E S S I O NT H A TR E S O L V E ST OAL O N GS T R I N G 1 3 6S O R TC A N N O TB EE X E C U T E DB E C A U S ET H ES O R TK E YL E N G T HI SG R E A T E RT H A N4 0 0 0B Y T E S 1 3 7T H EL E N G T HR E S U L T I N GF R O Mo p e r a t i o nI SG R E A T E RT H A Nm a x i m u m l e n g t h 1 3 8T H ES E C O N DO RT H I R DA R G U M E N TO FT H ES U B S T RF U N C T I O NI SO U TO FR A N G E 1 4 2T H ES Q LS T A T E M E N TI SN O TS U P P O R T E D 1 4 4I N V A L I DS E C T I O NN U M B E Rn u m b e r 1 4 7A L T E RF U N C T I O Nf u n c t i o n n a m eF A I L E DB E C A U S ES O U R C EF U N C T I O N SC A N N O TB EA L T E R E D 1 4 8T H ES O U R C ET A B L Es o u r c e n a m eC A N N O TB ER E N A M E DO RA L T E R E D 1 5 0T H EO B J E C TO FT H EI N S E R T ,D E L E T E ,O RU P D A T ES T A T E M E N TI SAV I E WO RT R A N S I T I O NT A B L EF O RW H I C HT H ER E Q U E S T E D O P E R A T I O NI SN O TP E R M I T T E D 1 5 1T H EU P D A T ES T A T E M E N TI SI N V A L I DB E C A U S ET H EC A T A L O GD E S C R I P T I O NO FC O L U M Nc o l u m n n a m eI N D I C A T E ST H A TI TC A N N O TB E U P D A T E D 1 5 2T H ED R O Pc l a u s eC L A U S EI NT H EA L T E RS T A T E M E N TI SI N V A L I DB E C A U S Ec o n s t r a i n t n a m eI SAc o n s t r a i n t t y p e 1 5 3T H ES T A T E M E N TI SI N V A L I DB E C A U S ET H EV I E WO RT A B L ED E F I N I T I O ND O E SN O TI N C L U D EAU N I Q U EN A M EF O RE A C HC O L U M N 1 5 4T H ES T A T E M E N TF A I L E DB E C A U S EV I E WO RT A B L ED E F I N I T I O NI SN O TV A L I D 1 5 6T H ES T A T E M E N TD O E SN O TI D E N T I F YAT A B L E 1 5 7O N L YAT A B L EN A M EC A NB ES P E C I F I E DI NAF O R E I G NK E YC L A U S E .o b j e c t n a m eI SN O TT H EN A M EO FAT A B L E . 1 5 8T H EN U M B E RO FC O L U M N SS P E C I F I E DF O RT H EV I E WI SN O TT H ES A M EA ST H EN U M B E RO FC O L U M N SS P E C I F I E DB YT H ES E L E C T C L A U S E ,O RT H EN U M B E RO FC O L U M N SS P E C I F I E DI NT H EC O R R E L A T I O NC L A U S EI NAF R O MC L A U S EI SN O TT H ES A M EA ST H E N U M B E RO FC O L U M N SI NT H EC O R R E S P O N D I N GT A B L E ,V I E W ,T A B L EE X P R E S S I O N ,O RT A B L EF U N C T I O N 1 5 9D R O PO RC O M M E N TO No b j e c tI D E N T I F I E SA ( N )o b j e c t t y p e 1R A T H E RT H A NA ( N )o b j e c t t y p e 2 1 6 0T H EW I T HC H E C KO P T I O NC A N N O TB EU S E DF O RT H ES P E C I F I E DV I E W 1 6 1T H EI N S E R TO RU P D A T EI SN O TA L L O W E DB E C A U S EAR E S U L T I N GR O WD O E SN O TS A T I S F YT H EV I E WD E F I N I T I O N 1 6 4a u t h i d 1D O E SN O TH A V ET H EP R I V I L E G ET OC R E A T EAV I E WW I T HQ U A L I F I C A T I O Na u t h o r i z a t i o n I D 1 7 0T H EN U M B E RO FA R G U M E N T SS P E C I F I E DF O Rf u n c t i o n n a m eI SI N V A L I D 1 7 1T H ED A T AT Y P E ,L E N G T H ,O RV A L U EO FA R G U M E N Tn nO Ff u n c t i o n n a m eI SI N V A L I D 1 7 3U RI SS P E C I F I E DO NT H EW I T HC L A U S EB U TT H EC U R S O RI SN O TR E A D O N L Y 1 8 0T H ED A T E ,T I M E ,O RT I M E S T A M PV A L U Ev a l u eI SI N V A L I D 1 8 1T H ES T R I N GR E P R E S E N T A T I O NO FAD A T E T I M EV A L U EI SN O TAV A L I DD A T E T I M EV A L U E 1 8 2A NA R I T H M E T I CE X P R E S S I O NW I T HAD A T E T I M EV A L U EI SI N V A L I D 1 8 3A NA R I T H M E T I CO P E R A T I O NO NAD A T EO RT I M E S T A M PH A SAR E S U L TT H A TI SN O TW I T H I NT H EV A L I DR A N G EO FD A T E S 1 8 4A NA R I T H M E T I CE X P R E S S I O NW I T HAD A T E T I M EV A L U EC O N T A I N SAP A R A M E T E RM A R K E R 1 8 5T H EL O C A LF O R M A TO P T I O NH A SB E E NU S E DW I T HAD A T EO RT I M EA N DN OL O C A LE X I TH A SB E E NI N S T A L L E D 1 8 6T H EL O C A LD A T EL E N G T HO RL O C A LT I M EL E N G T HH A SB E E NI N C R E A S E DA N DE X E C U T I N GP R O G R A MR E L I E SO NT H EO L DL E N G T H 1 8 7AR E F E R E N C ET OAC U R R E N TD A T E / T I M ES P E C I A LR E G I S T E RI SI N V A L I DB E C A U S ET H EM V ST O DC L O C KI SB A DO RT H EM V SP A R M T Z I SO U TO FR A N G E 1 8 8T H ES T R I N GR E P R E S E N T A T I O NO FAN A M EI SI N V A L I D 1 8 9C C S I Dc c s i dI SU N K N O W NO RI N V A L I DF O RT H ED A T AT Y P EO RS U B T Y P E 1 9 0A T T R I B U T E SO FC O L U M Nc o l u m n n a m eI NT A B L Et a b l e n a m eA R EN O TC O M P A T I B L EW I T HT H EE X I S T I N GC O L U M N 1 9 1AS T R I N GC A N N O TB EU S E DB E C A U S EI TI SI N V A L I DM I X E DD A T A 1 9 7Q U A L I F I E DC O L U M NN A M E SI NO R D E RB YC L A U S EN O TP E R M I T T E DW H E NU N I O NO RU N I O NA L LS P E C I F I E D 1 9 8T H EO P E R A N DO FT H EP R E P A R EO RE X E C U T EI M M E D I A T ES T A T E M E N TI SB L A N KO RE M P T Y 1 9 9I l l e g a lu s eo ft h es p e c i f i e dk e y w o r d . 2 0 3AR E F E R E N C ET OC O L U M Nc o l u m n n a m eI SA M B I G U O U S 2 0 4O b j e c tn o td e f i n e dt oD B 2 . 2 0 5C o l u m nn a m en o ti nt a b l e . 2 0 6C o l u m nd o e sn o te x i s ti na n yt a b l eo ft h eS E L E C T . 2 0 8T H EO R D E RB YC L A U S EI SI N V A L I DB E C A U S EC O L U M Nn a m eI SN O TP A R TO FT H ER E S U L TT A B L E 2 1 2n a m eI SS P E C I F I E DM O R ET H A NO N C EI NT H ER E F E R E N C I N GC L A U S EO FAT R I G G E RD E F I N I T I O N 2 1 4A NE X P R E S S I O NI NT H EF O L L O W I N GP O S I T I O N ,O RS T A R T I N GW I T Hp o s i t i o n o r e x p r e s s i o n s t a r tI NT H Ec l a u s e t y p eC L A U S E I SN O TV A L I D .R E A S O NC O D E=r e a s o n c o d e 2 1 6N o tt h es a m en u m b e ro fe x p r e s s i o n so nb o t hs i d e so ft h ec o m p a r i s o ni naS E L E C T. 2 1 9T H ER E Q U I R E DE X P L A N A T I O NT A B L Et a b l e n a m eD O E SN O TE X I S T 2 2 0T H EC O L U M Nc o l u m n n a m eI NE X P L A N A T I O NT A B L Et a b l e n a m eI SN O TD E F I N E DP R O P E R L Y
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
99/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
100/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
C L A U S EO RI SM I S S I N GT H E 4 5 0U S E R D E F I N E DF U N C T I O NO RS T O R E DP R O C E D U R En a m e ,P A R A M E T E RN U M B E Rp a r m n u m ,O V E R L A Y E DS T O R A G EB E Y O N DI T SD E C L A R E D L E N G T H . 4 5 1T H Ed a t a i t e mD E F I N I T I O N ,I NT H EC R E A T EF U N C T I O NF O Rf u n c t i o n n a m eC O N T A I N SD A T AT Y P Et y p eW H I C HI SN O T A P P R O P R I A T EF O RA NE X T E R N A LF U N C T I O NW R I T T E NI NT H EG I V E NL A N G U A G E 4 5 3T H E R EI SAP R O B L E MW I T HT H ER E T U R N SC L A U S EI NT H EC R E A T EF U N C T I O NS T A T E M E N TF O Rf u n c t i o n n a m e 4 5 4T H ES I G N A T U R EP R O V I D E DI NT H EC R E A T EF U N C T I O NS T A T E M E N TF O Rf u n c t i o n n a m eM A T C H E ST H ES I G N A T U R EO FS O M EO T H E R F U N C T I O NA L R E A D YE X I S T I N GI NT H ES C H E M A 4 5 5I NC R E A T EF U N C T I O NF O Rf u n c t i o n n a m e ,T H ES C H E M AN A M Es c h e m a n a m e 1P R O V I D E DF O RT H ES P E C I F I CN A M ED O E SN O TM A T C H T H ES C H E M AN A M Es c h e m a n a m e 2O FT H EF U N C T I O N 4 5 6I NC R E A T EF U N C T I O NF O Rf u n c t i o n n a m e ,T H ES P E C I F I CN A M Es p e c i f i c n a m eA L R E A D YE X I S T SI NT H ES C H E M A 4 5 7AF U N C T I O NO RD I S T I N C TT Y P EC A N N O TB EC A L L E Dn a m eS I N C EI TI SR E S E R V E DF O RS Y S T E MU S E 4 5 8I NAR E F E R E N C ET OF U N C T I O Nf u n c t i o n n a m eB YS I G N A T U R E ,AM A T C H I N GF U N C T I O NC O U L DN O TB EF O U N D 4 6 1AV A L U EW I T HD A T AT Y P Es o u r c e d a t a t y p eC A N N O TB EC A S TT OT Y P Et a r g e t d a t a t y p e 4 6 3E X T E R N A LR O U T I N Er o u t i n e n a m e( S P E C I F I CN A M Es p e c i f i c n a m e )H A SR E T U R N E DA NI N V A L I DS Q L S T A T Es q l s t a t e ,W I T H D I A G N O S T I CT E X Tt e x t 4 6 9S Q LC A L LS T A T E M E N TM U S TS P E C I F YA NO U T P U TH O S TV A R I A B L EF O RP A R A M E T E Rn u m b e r 4 7 0S Q LC A L LS T A T E M E N TS P E C I F I E DAN U L LV A L U EF O RI N P U TP A R A M E T E Rn u m b e r ,B U TT H ES T O R E DP R O C E D U R ED O E SN O TS U P P O R T N U L LV A L U E S . 4 7 1I N V O C A T I O NO FF U N C T I O NO RP R O C E D U R En a m eF A I L E DD U ET OR E A S O Nr c 4 7 2C U R S O Rc u r s o r n a m eW A SL E F TO P E NB YE X T E R N A LF U N C T I O Nf u n c t i o n n a m e( S P E C I F I CN A M Es p e c i f i c n a m e ) 4 7 3AU S E RD E F I N E DD A T AT Y P EC A N N O TB EC A L L E DT H ES A M EN A M EA SAS Y S T E MP R E D E F I N E DT Y P E( B U I L T I NT Y P E ) 4 7 5T H ER E S U L TT Y P Et y p e1O FT H ES O U R C EF U N C T I O NC A N N O TB EC A S TT OT H ER E T U R N ST Y P Et y p e2O FT H EU S E R D E F I N E D F U N C T I O Nf u n c t i o n n a m e 4 7 6R E F E R E N C ET OF U N C T I O Nf u n c t i o n n a m eW A SN A M E DW I T H O U TAS I G N A T U R E ,B U TT H EF U N C T I O NI SN O TU N I Q U EW I T H I NI T SS C H E M A 4 7 8D R O PO RR E V O K EO NO B J E C TT Y P Et y p e 1C A N N O TB EP R O C E S S E DB E C A U S EO B J E C Tn a m eO FT Y P Et y p e 2I SD E P E N D E N TO NI T 4 8 0T H EP R O C E D U R Ep r o c e d u r e n a m eH A SN O TY E TB E E NC A L L E D 4 8 2T h ep r o c e d u r er e t u r n e dn ol o c a t o r s . 4 8 3I NC R E A T EF U N C T I O NF O Rf u n c t i o n n a m eS T A T E M E N T ,T H EN U M B E RO FP A R A M E T E R SD O E SN O TM A T C HT H EN U M B E RO FP A R A M E T E R S O FT H ES O U R C EF U N C T I O N 4 8 7o b j e c t t y p eo b j e c t n a m eA T T E M P T E DT OE X E C U T EA NS Q LS T A T E M E N TW H E NT H ED E F I N I T I O NO FT H EF U N C T I O NO RP R O C E D U R ED I D N O TS P E C I F YT H I SA C T I O N 4 9 0N U M B E Rn u m b e rD I R E C T L YS P E C I F I E DI NA NS Q LS T A T E M E N TI SO U T S I D ET H ER A N G EO FA L L O W A B L EV A L U E SI NT H I SC O N T E X T ( m i n v a l ,m a x v a l ) 4 9 1C R E A T ES T A T E M E N TF O RU S E R D E F I N E DF U N C T I O Nf u n c t i o n n a m eM U S TH A V EAR E T U R N SC L A U S EA N D :T H EE X T E R N A LC L A U S EW I T H O T H E RR E Q U I R E DK E Y W O R D S ;T H ER E T U R NS T A T E M E N TA N DP A R A M E T E RN A M E S ;O RT H ES O U R C EC L A U S E 4 9 2T H EC R E A T EF U N C T I O NF O Rf u n c t i o n n a m eH A SAP R O B L E MW I T HP A R A M E T E RN U M B E Rn u m b e r .I TM A YI N V O L V EAM I S M A T C HW I T HA S O U R C EF U N C T I O N 4 9 5E S T I M A T E DP R O C E S S O RC O S TO Fe s t i m a t e a m o u n t 1P R O C E S S O RS E C O N D S( e s t i m a t e a m o u n t 2S E R V I C EU N I T S )I NC O S TC A T E G O R Y c o s t c a t e g o r yE X C E E D SAR E S O U R C EL I M I TE R R O RT H R E S H O L DO Fl i m i t -a m o u n tS E R V I C EU N I T S 4 9 6T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S EI TR E F E R E N C E SAR E S U L TS E TT H A TW A SN O TC R E A T E DB YT H EC U R R E N TS E R V E R 4 9 7T H EM A X I M U ML I M I TO FI N T E R N A LI D E N T I F I E R SH A SB E E NE X C E E D E DF O RD A T A B A S Ed a t a b a s e n a m e 4 9 9C U R S O Rc u r s o r n a m eH A SA L R E A D YB E E NA S S I G N E DT OT H I SO RA N O T H E RR E S U L TS E TF R O MP R O C E D U R Ep r o c e d u r e n a m e .
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
101/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
5 5 3a u t h i dS P E C I F I E DI SN O TO N EO FT H EV A L I DA U T H O R I Z A T I O NI D S 5 5 4A NA U T H O R I Z A T I O NI DC A N N O TG R A N TAP R I V I L E G ET OI T S E L F 5 5 5A NA U T H O R I Z A T I O NI DC A N N O TR E V O K EAP R I V I L E G EF R O MI T S E L F 5 5 6a u t h i d 2C A N N O TH A V ET H Ep r i v i l e g eP R I V I L E G Eo n _ o b j e c tR E V O K E DB Ya u t h i d 1B E C A U S ET H ER E V O K E ED O E SN O TP O S S E S ST H E P R I V I L E G EO RT H ER E V O K E RD I DN O TM A K ET H EG R A N T 5 5 7I N C O N S I S T E N TG R A N T / R E V O K EK E Y W O R Dk e y w o r d .P E R M I T T E DK E Y W O R D SA R Ek e y w o r d l i s t 5 5 8I N V A L I DC L A U S EO RC O M B I N A T I O NO FC L A U S E SO NAG R A N TO RR E V O K E 5 5 9A L LA U T H O R I Z A T I O NF U N C T I O N SH A V EB E E ND I S A B L E D 5 6 7b i n d t y p eA U T H O R I Z A T I O NE R R O RU S I N Ga u t h i dA U T H O R I T YP A C K A G E=p a c k a g e n a m eP R I V I L E G E=p r i v i l e g e 5 7 1T H ES T A T E M E N TW O U L DR E S U L TI NAM U L T I P L ES I T EU P D A T E 5 7 3T A B L Et a b l e n a m eD O E SN O TH A V EAU N I Q U EK E YW I T HT H ES P E C I F I E DC O L U M NN A M E S 5 7 4T H ES P E C I F I E DD E F A U L TV A L U EO RI D E N T I T YA T T R I B U T EV A L U EC O N F L I C T SW I T HT H ED E F I N I T I O NO FC O L U M Nc o l u m n n a m e 5 7 7o b j e c t t y p eo b j e c t n a m eA T T E M P T E DT OM O D I F YD A T AW H E NT H ED E F I N I T I O NO FT H EF U N C T I O NO RP R O C E D U R ED I DN O TS P E C I F Y T H I SA C T I O N 5 7 9o b j e c t t y p eo b j e c t n a m eA T T E M P T E DT OR E A DD A T AW H E NT H ED E F I N I T I O NO FT H EF U N C T I O NO RP R O C E D U R ED I DN O TS P E C I F Y T H I SA C T I O N 5 8 0T H ER E S U L T E X P R E S S I O N SO FAC A S EE X P R E S S I O NC A N N O TA L LB EN U L L 5 8 1T H ED A T AT Y P E SO FT H ER E S U L T E X P R E S S I O N SO FAC A S EE X P R E S S I O NA R EN O TC O M P A T I B L E 5 8 2T H ES E A R C H C O N D I T I O NI NAS E A R C H E D W H E N C L A U S EC A N N O TB EAQ U A N T I F I E DP R E D I C A T E ,I NP R E D I C A T E ,O RA NE X I S T S P R E D I C A T E . 5 8 3T H EU S EO FF U N C T I O Nf u n c t i o n n a m eI SI N V A L I DB E C A U S EI TI SN O TD E T E R M I N I S T I CO RH A SA NE X T E R N A LA C T I O N 5 8 5T H ES C H E M AN A M Es c h e m a n a m eC A N N O TA P P E A RM O R ET H A NO N C EI NT H EC U R R E N TP A T H 5 8 6T H ET O T A LL E N G T HO FT H EC U R R E N TP A T HS P E C I A LR E G I S T E RC A N N O TE X C E E D2 5 4C H A R A C T E R S 5 8 7AL I S TO Fi t e m r e f e r e n c e sA R EN O TI NT H ES A M EF A M I L Y 5 9 0P A R A M E T E RN A M Ep a r a m e t e r n a m eI SN O TU N I Q U EI NT H EC R E A T EF O RR O U T I N Er o u t i n e n a m e 5 9 2N O TA U T H O R I Z E DT OC R E A T EF U N C T I O N SO RP R O C E D U R E SI NW L ME N V I R O N M E N Te n v n a m e 5 9 3N O TN U L LM U S TB ES P E C I F I E DF O RR O W I DO RD I S T I N C TT Y P EC O L U M Nc o l u m n n a m e 6 0 1T H EN A M EO FT H EO B J E C TT OB EC R E A T E DO RT H ET A R G E TO FAR E N A M ES T A T E M E N TI SI D E N T I C A LT OT H EE X I S T I N GN A M En a m eO F T H EO B J E C TT Y P Eo b j t y p e 6 0 2T O OM A N YC O L U M N SS P E C I F I E DI NAC R E A T EI N D E X 6 0 3AU N I Q U EI N D E XC A N N O TB EC R E A T E DB E C A U S ET H ET A B L EC O N T A I N SR O W SW H I C HA R ED U P L I C A T E SW I T HR E S P E C TT OT H EV A L U E S O FT H EI D E N T I F I E DC O L U M N S 6 0 4AD A T AT Y P ED E F I N I T I O NS P E C I F I E SA NI N V A L I DL E N G T H ,P R E C I S I O N ,O RS C A L EA T T R I B U T E 6 0 7O P E R A T I O NO RO P T I O No p e r a t i o nI SN O TD E F I N E DF O RT H I SO B J E C T 6 1 1O N L YL O C K M A X0C A NB ES P E C I F I E DW H E NT H EL O C KS I Z EO FT H ET A B L E S P A C EI ST A B L E S P A C EO RT A B L E 6 1 2c o l u m n n a m eI SAD U P L I C A T EC O L U M NN A M E 6 1 3T H EP R I M A R YK E YO RAU N I Q U EC O N S T R A I N TI ST O OL O N GO RH A ST O OM A N YC O L U M N S 6 1 4T H EI N D E XC A N N O TB EC R E A T E DO RT H EL E N G T HO FAC O L U M NC A N N O TB EC H A N G E DB E C A U S ET H ES U MO FT H EI N T E R N A LL E N G T H SO F T H EI D E N T I F I E DC O L U M N SI SG R E A T E RT H A NT H EA L L O W A B L EM A X I M U M 6 1 5o p e r a t i o n t y p eI SN O TA L L O W E DO NAP A C K A G EI NU S E 6 1 6o b j t y p e 1o b j n a m e 1C A N N O TB ED R O P P E DB E C A U S EI TI SR E F E R E N C E DB Yo b j t y p e 2o b j n a m e 2 6 1 7AT Y P E1I N D E XI SN O TV A L I DF O RT A B L Et a b l e n a m e 6 1 8O P E R A T I O No p e r a t i o nI SN O TA L L O W E DO NS Y S T E MD A T A B A S E S 6 1 9O P E R A T I O ND I S A L L O W E DB E C A U S ET H ED A T A B A S EI SN O TS T O P P E D 6 2 0K E Y W O R Dk e y w o r dI Ns t m tt y p eS T A T E M E N TI SN O TP E R M I T T E DF O RAs p a c et y p eS P A C EI NT H Ed a t a b a s et y p eD A T A B A S E 6 2 1D U P L I C A T ED B I Dd b i dW A SD E T E C T E DA N DP R E V I O U S L YA S S I G N E DT Od a t a b a s e n a m e 6 2 2F O RM I X E DD A T AI SI N V A L I DB E C A U S ET H EM I X E DD A T AI N S T A L LO P T I O NI SN O 6 2 3AC L U S T E R I N GI N D E XA L R E A D YE X I S T SO NT A B L Et a b l e n a m e 6 2 4T A B L Et a b l e n a m eA L R E A D YH A SAP R I M A R YK E YO RU N I Q U EK E YC O N S T R A I N TW I T HS P E C I F I E DC O L U M N S 6 2 5T A B L Et a b l e n a m eD O E SN O TH A V EA NI N D E XT OE N F O R C ET H EU N I Q U E N E S SO FT H EP R I M A R YO RU N I Q U EK E Y 6 2 6T H EA L T E RS T A T E M E N TI SN O TE X E C U T A B L EB E C A U S ET H EP A G ES E TI SN O TS T O P P E D 6 2 7T H EA L T E RS T A T E M E N TI SI N V A L I DB E C A U S ET H EP A G E S E TH A SU S E R M A N A G E DD A T AS E T S 6 2 8T H EC L A U S E SA R EM U T U A L L YE X C L U S I V E 6 2 9S E TN U L LC A N N O TB ES P E C I F I E DB E C A U S EF O R E I G NK E Yn a m eC A N N O TC O N T A I NN U L LV A L U E S 6 3 0T H EW H E R EN O TN U L LS P E C I F I C A T I O NI SI N V A L I DF O RT Y P E1I N D E X E S 6 3 1F O R E I G NK E Yn a m eI ST O OL O N GO RH A ST O OM A N YC O L U M N S 6 3 2T H ET A B L EC A N N O TB ED E F I N E DA SAD E P E N D E N TO Ft a b l e n a m eB E C A U S EO FD E L E T ER U L ER E S T R I C T I O N S 6 3 3T H ED E L E T ER U L EM U S TB Ed e l e t e r u l e 6 3 4T H ED E L E T ER U L EM U S TN O TB EC A S C A D E 6 3 5T H ED E L E T ER U L E SC A N N O TB ED I F F E R E N TO RC A N N O TB ES E TN U L L 6 3 6T H EP A R T I T I O N I N GK E Y SF O RP A R T I T I O Np a r t n u mA R EN O TS P E C I F I E DI NA S C E N D I N GO RD E S C E N D I N GO R D E R 6 3 7D U P L I C A T Ek e y w o r dK E Y W O R D 6 3 8T A B L Et a b l e n a m eC A N N O TB EC R E A T E DB E C A U S EC O L U M ND E F I N I T I O NI SM I S S I N G 6 3 9AN U L L A B L EC O L U M NO FAF O R E I G NK E YW I T HAD E L E T ER U L EO FS E TN U L LC A N N O TB EAC O L U M NO FT H EK E YO FAP A R T I T I O N E D I N D E X 6 4 0L O C K S I Z ER O WC A N N O TB ES P E C I F I E DB E C A U S ET A B L EI NT H I ST A B L E S P A C EH A ST Y P E1I N D E X 6 4 3C H E C KC O N S T R A I N TE X C E E D SM A X I M U MA L L O W A B L EL E N G T H 6 4 4I N V A L I DV A L U ES P E C I F I E DF O RK E Y W O R Dk e y w o r dI Ns t m t t y p eS T A T E M E N T 6 4 6T A B L Et a b l e n a m eC A N N O TB EC R E A T E DI NS P E C I F I E DT A B L ES P A C Et a b l e s p a c e n a m eB E C A U S EI TA L R E A D YC O N T A I N SAT A B L E 6 4 7B U F F E R P O O Lb p n a m eC A N N O TB ES P E C I F I E DB E C A U S EI TH A SN O TB E E NA C T I V A T E D 6 5 0T H EA L T E RI N D E XC A N N O TB EE X E C U T E D ,R E A S O Nr e a s o n 6 5 1T A B L ED E S C R I P T I O NE X C E E D SM A X I M U MS I Z EO FO B J E C TD E S C R I P T O R . 6 5 2V I O L A T I O NO FI N S T A L L A T I O ND E F I N E DE D I TO RV A L I D A T I O NP R O C E D U R Ep r o c n a m e 6 5 3T A B L Et a b l e n a m eI NP A R T I T I O N E DT A B L ES P A C Et s p a c e n a m eI SN O TA V A I L A B L EB E C A U S EI T SP A R T I T I O N E DI N D E XH A SN O T B E E NC R E A T E D 6 5 5T H EC R E A T EO RA L T E RS T O G R O U PI SI N V A L I DB E C A U S ET H ES T O R A G EG R O U PW O U L DH A V EB O T HS P E C I F I CA N DN O N S P E C I F I C V O L U M EI D S 6 5 8Ao b j e c t t y p eC A N N O TB ED R O P P E DU S I N GT H Es t a t e m e n tS T A T E M E N T 6 6 0I N D E Xi n d e x n a m eC A N N O TB EC R E A T E DO RA L T E R E DO NP A R T I T I O N E DT A B L ES P A C Et s p a c e n a m eB E C A U S EK E YL I M I T SA R EN O T S P E C I F I E D 6 6 1I N D E Xi n d e x n a m eC A N N O TB EC R E A T E DO NP A R T I T I O N E DT A B L ES P A C Et s p a c e n a m eB E C A U S ET H EN U M B E RO FP A R T S P E C I F I C A T I O N SI SN O TE Q U A LT OT H EN U M B E RO FP A R T I T I O N SO FT H ET A B L ES P A C E 6 6 2AP A R T I T I O N E DI N D E XC A N N O TB EC R E A T E DO NAN O N P A R T I T I O N E DT A B L ES P A C Et s p a c e n a m e 6 6 3T H EN U M B E RO FK E YL I M I TV A L U E SI SE I T H E RZ E R O ,O RG R E A T E RT H A NT H EN U M B E RO FC O L U M N SI NT H EK E YO FI N D E Xi n d e x n a m e 6 6 5T H EP A R TC L A U S EO FA NA L T E RS T A T E M E N TI SO M I T T E DO RI N V A L I D 6 6 6s t m t v e r bo b j e c tC A N N O TB EE X E C U T E DB E C A U S Ef u n c t i o nI SI NP R O G R E S S 6 6 7T H EC L U S T E R I N GI N D E XF O RAP A R T I T I O N E DT A B L ES P A C EC A N N O TB EE X P L I C I T L YD R O P P E D 6 6 8T H EC O L U M NC A N N O TB EA D D E DT OT H ET A B L EB E C A U S ET H ET A B L EH A SA NE D I TP R O C E D U R E 6 6 9T H EO B J E C TC A N N O TB EE X P L I C I T L YD R O P P E D .R E A S O Nr e a s o n c o d e 6 7 0T H ER E C O R DL E N G T HO FT H ET A B L EE X C E E D ST H EP A G ES I Z EL I M I T 6 7 1T H EB U F F E R P O O LA T T R I B U T EO FT H ET A B L ES P A C EC A N N O TB EA L T E R E DA SS P E C I F I E DB E C A U S EI TW O U L DC H A N G ET H EP A G ES I Z E O FT H ET A B L ES P A C E
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
102/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
103/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
8 0 7A C C E S SD E N I E D :P A C K A G Ep a c k a g e n a m eI SN O TE N A B L E DF O RA C C E S SF R O Mc o n n e c t i o n t y p ec o n n e c t i o n n a m e 8 0 8T H EC O N N E C TS T A T E M E N TI SN O TC O N S I S T E N TW I T HT H EF I R S TC O N N E C TS T A T E M E N T 8 1 1M o r et h a no n er o wr e t r i e v e di nS E L E C TI N T O . 8 1 2T H ES Q LS T A T E M E N TC A N N O TB EP R O C E S S E DB E C A U S EAB L A N KC O L L E C T I O N I DW A SF O U N DI NT H EC U R R E N TP A C K A G E S E TS P E C I A L R E G I S T E Rw h i l et r y i n gt oF O R MAQ U A L I F I E DP A C K A G EN A M EF O RP R O G R A Mp r o g r a m n a m ec o n s i s t e n c y t o k e nU S I N GP L A Np l a n 8 1 5AG R O U PB YO RH A V I N GC L A U S EI SI M P L I C I T L YO RE X P L I C I T L YS P E C I F I E DI NAS U B S E L E C TO FAB A S I CP R E D I C A T EO RT H ES E T C L A U S EO FA NU P D A T ES T A T E M E N T 8 1 7T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S ET H ES T A T E M E N TW I L LR E S U L TI NAP R O H I B I T E DU P D A T EO P E R A T I O N . 8 1 8P l a na n dp r o g r a m :t i m e s t a m pm i s m a t c h . 8 1 9T H EV I E WC A N N O TB EP R O C E S S E DB E C A U S ET H EL E N G T HO FI T SP A R S ET R E EI NT H EC A T A L O GI SZ E R O 8 2 0T H ES Q LS T A T E M E N TC A N N O TB EP R O C E S S E DB E C A U S Ec a t a l o g t a b l eC O N T A I N SAV A L U ET H A TI SN O TV A L I DI NT H I SR E L E A S E 8 2 2T H ES Q L D AC O N T A I N SA NI N V A L I DD A T AA D D R E S SO RI N D I C A T O RV A R I A B L EA D D R E S S 8 4 0T O OM A N YI T E M SR E T U R N E DI NAS E L E C TO RI N S E R TL I S T 8 4 2AC O N N E C T I O NT Ol o c a t i o n n a m eA L R E A D YE X I S T S 8 4 3T H ES E TC O N N E C T I O NO RR E L E A S ES T A T E M E N TM U S TS P E C I F YA NE X I S T I N GC O N N E C T I O N 8 4 6I N V A L I DS P E C I F I C A T I O NO FA NI D E N T I T YC O L U M N 8 6 7I N V A L I DS P E C I F I C A T I O NO FAR O W I DC O L U M N 8 7 0T H EN U M B E RO FH O S TV A R I A B L E SI NT H ES T A T E M E N TI SN O TE Q U A LT OT H EN U M B E RO FD E S C R I P T O R S 8 7 2AV A L I DC C S I DH A SN O TY E TB E E NS P E C I F I E DF O RT H I SS U B S Y S T E M 8 7 3D A T AE N C O D E DW I T HD I F F E R E N TE N C O D I N GS C H E M E SC A N N O TB ER E F E R E N C E DI NT H ES A M ES Q LS T A T E M E N T 8 7 4T H EE N C O D I N GS C H E M ES P E C I F I E DF O RT H Eo b j e c t t y p eM U S TB ET H ES A M EA ST H EC O N T A I N I N GT A B L ES P A C EO RO T H E R P A R A M E T E R S 8 7 5o p e r a n dC A N N O TB EU S E DW I T HT H EA S C I ID A T AR E F E R E N C E D 8 7 6' o b j e c t 'C A N N O TB EC R E A T E D ,R E A S O N' r e a s o n ' 8 7 7C C S I DA S C I IO RC C S I DU N I C O D EI SN O TA L L O W E DF O RT H I SD A T A B A S EO RT A B L ES P A C E 8 7 8T H EP L A N _ T A B L EU S E DF O RE X P L A I NC A N N O TB EA S C I IO RU N I C O D E 8 7 9C R E A T Eo rA L T E RS T A T E M E N TF O Ro b j n a m eC A N N O TD E F I N EAC O L U M N ,D I S T I N C TT Y P E ,F U N C T I O NO RS T O R E DP R O C E D U R E P A R A M E T E RW I T HE N C O D I N GS C H E M Ee n c o d i n g s c h e m e 8 8 0S A V E P O I N Ts a v e p o i n t n a m eD O E SN O TE X I S TO RI SI N V A L I DI NT H I SC O N T E X T 8 8 1AS A V E P O I N TW I T HN A M Es a v e p o i n t n a m eA L R E A D YE X I S T S ,B U TT H I SS A V E P O I N TN A M EC A N N O TB ER E U S E D 8 8 2S A V E P O I N TD O E SN O TE X I S T 9 0 0T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S ET H EA P P L I C A T I O NP R O C E S SI SN O TC O N N E C T E DT OA NA P P L I C A T I O NS E R V E R 9 0 1U N S U C C E S S F U LE X E C U T I O NC A U S E DB YAS Y S T E ME R R O RT H A TD O E SN O TP R E C L U D ET H ES U C C E S S F U LE X E C U T I O NO FS U B S E Q U E N TS Q L S T A T E M E N T S 9 0 2P O I N T E RT OT H EE S S E N T I A LC O N T R O LB L O C K( C T / R D A )H A SV A L U E0 ,R E B I N DR E Q U I R E D 9 0 4U n a v a i l a b l er e s o u r c e .S o m e o n ee l s ei sl o c k i n gy o u rd a t a . 9 0 5U N S U C C E S S F U LE X E C U T I O ND U ET OR E S O U R C EL I M I TB E I N GE X C E E D E D ,R E S O U R C EN A M E=r e s o u r c e n a m eL I M I T=l i m i t a m o u n t 1 C P US E C O N D S( l i m i t a m o u n t 2S E R V I C EU N I T S )D E R I V E DF R O Ml i m i t s o u r c e 9 0 6T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S ET H I SF U N C T I O NI SD I S A B L E DD U ET OAP R I O RE R R O R 9 0 8b i n d t y p eE R R O RU S I N Ga u t h i dA U T H O R I T Y .B I N D ,R E B I N DO RA U T O R E B I N DO P E R A T I O NI SN O TA L L O W E D 9 0 9T H EO B J E C TH A SB E E ND E L E T E D 9 1 0T H ES Q LS T A T E M E N TC A N N O TA C C E S SA NO B J E C TO NW H I C HAD R O PO RA L T E RI SP E N D I N G 9 1 1R o l l b a c kh a sb e e nd o n ed u et oD e a d l o c ko rt i m e o u t . 9 1 3D e a d l o c ko rt i m e o u th a so c u r r e d . 9 1 7B I N DP A C K A G EF A I L E D 9 1 8T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S EAC O N N E C T I O NH A SB E E NL O S T 9 1 9AR O L L B A C KO P E R A T I O NI SR E Q U I R E D 9 2 2A U T H O R I Z A T I O NF A I L U R E :e r r o r t y p eE R R O R .R E A S O Nr e a s o n c o d e( A u t h o r i z a t i o nn e e d e d ) . 9 2 3C O N N E C T I O NN O TE S T A B L I S H E D :D B 2c o n d i t i o nR E A S O Nr e a s o n c o d e ,T Y P Er e s o u r c e t y p e ,N A M Er e s o u r c e n a m e 9 2 4D B 2C O N N E C T I O NI N T E R N A LE R R O R ,f u n c t i o n c o d e ,r e t u r n c o d e ,r e a s o n c o d e 9 2 5C O M M I TN O TV A L I DI NI M S ,C I C SO RR R S A FE N V I R O N M E N T 9 2 6R O L L B A C KN O TV A L I DI NI M S ,C I C SO RR R S A FE N V I R O N M E N T 9 2 7T h el a n g u a g ei n t e r f a c ew a sc a l l e db u tn oc o n n e c t i o nh a db e e nm a d e . 9 2 9F A I L U R EI NAD A T AC A P T U R EE X I T :t o k e n 9 3 9R O L L B A C KR E Q U I R E DD U ET OU N R E Q U E S T E DR O L L B A C KO FAR E M O T ES E R V E R 9 4 7T H ES Q LS T A T E M E N TF A I L E DB E C A U S EI TW I L LC H A N G EAT A B L ED E F I N E DW I T HD A T AC A P T U R EC H A N G E S ,B U TT H ED A T AC A N N O TB E P R O P A G A T E D 9 4 8D I S T R I B U T E DO P E R A T I O NI SI N V A L I D 9 5 0T H EL O C A T I O NN A M ES P E C I F I E DI NT H EC O N N E C TS T A T E M E N TI SI N V A L I DO RN O TL I S T E DI NT H EC O M M U N I C A T I O N SD A T A B A S E 9 8 1T H ES Q LS T A T E M E N TF A I L E DB E C A U S ET H ER R S A FC O N N E C T I O NI SN O TI NAS T A T ET H A TA L L O W SS Q LO P E R A T I O N S ,R E A S O N r e a s o n c o d e . 9 9 1C A L LA T T A C HW A SU N A B L ET OE S T A B L I S HA NI M P L I C I TC O N N E C TO RO P E NT OD B 2 .R C 1 =r c 1R C 2 =r c 2
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
104/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
T A B L ET H A TI SR E F E R E N C E DI NE X I S T I N GV I E WD E F I N I T I O N S 2 0 1 0 7H O S TV A R I A B L EO RP A R A M E T E RN U M B E Rp o s i t i o n n u m b e rC A N N O TB EU S E DA SS P E C I F I E DB E C A U S ER E A S O Nr e a s o n 2 0 1 0 8AR E S U L TS E TC O N T A I N SA NU N S U P P O R T E DD A T AT Y P EI NP O S I T I O NN U M B E Rp o s i t i o n n u m b e rF O RC U R S O Rc u r s o r n a m eO P E N E D B YS T O R E DP R O C E D U R Ep r o c e d u r e n a m e 2 0 1 1 0C A N N O TI M P L I C I T L YC O N N E C TT OAR E M O T ES I T EW I T HAS A V E P O I N TO U T S T A N D I N G 2 0 1 1 1C A N N O TI S S U ES A V E P O I N T ,R E L E A S ES A V E P O I N T ,R O L L B A C KT OS A V E P O I N TF R O MAT R I G G E R ,F R O MAU S E R D E F I N E DF U N C T I O N , O RF R O MAG L O B A LT R A N S A C T I O N 2 0 1 2 3C A L LT OS T O R E DP R O C E D U R Ep r o c e d u r eF A I L E DB E C A U S ET H ER E S U L TS E TR E T U R N E DF O RC U R S O Rc u r s o rI SS C R O L L A B L E ,B U T T H EC U R S O RI SN O TP O S I T I O N E DB E F O R ET H EF I R S TR O W 2 0 1 2 4O P E NC U R S O Rc u r s o rF A I L E DB E C A U S ET H EC U R S O RI SS C R O L L A B L EB U TT H EC L I E N TD O E SN O TS U P P O R TT H I S 2 0 1 2 5C A L LT OS T O R E DP R O C E D U R Ep r o c e d u r eF A I L E DB E C A U S ET H ER E S U L TS E TF O RC U R S O Rc u r s o rI SS C R O L L A B L E ,B U TT H EC L I E N T D O E SN O TS U P P O R TT H I S 2 0 1 2 6C U R S O Rc u r s o rI SD E F I N E DA SS C R O L L A B L E ,B U TT H EE N V I R O N M E N TI N V O L V E SAH O PS I T E 2 0 1 2 7V A L U ES P E C I F I E DO NF E T C HS T A T E M E N TF O RA B S O L U T EO RR E L A T I V EI ST O OL A R G EF O RD R D A 2 0 1 2 9L O C A LS P E C I A LR E G I S T E RI SN O TV A L I DA SU S E D 2 0 2 0 0T H EI N S T A L L _ J A RO RR E P L A C E _ J A RP R O C E D U R EF O Rj a r i dF A I L E DA Su r lC O U L DN O TB EL O C A T E D . 2 0 2 0 1T H EI N S T A L L _ J A R ,R E P L A C E _ J A R ,O RR E M O V E _ J A RP R O C E D U R EF O Rj a r n a m eF A I L E DA ST H EJ A RN A M EI SI N V A L I D 2 0 2 0 2T H ER E P L A C E _ J A RO RR E M O V E _ J A RP R O C E D U R EF O Rj a r n a m eF A I L E DA Sc l a s sI SI NU S E 2 0 2 0 3U S E RD E F I N E DF U N C T I O NO RP R O C E D U R En a m eH A SAJ A V AM E T H O DW I T HA NI N V A L I DS I G N A T U R E .T H EE R R O RI SA TO RN E A R P A R A M E T E Rn u m b e r .T H ES I G N A T U R EI Ss i g n a t u r e 2 0 2 0 4T H EU S E R D E F I N E DF U N C T I O NO RP R O C E D U R Er o u t i n e n a m eW A SU N A B L ET OM A PT OAS I N G L EJ A V AM E T H O D 2 0 2 0 7T H EI N S T A L L _ J A RO RR E M O V E _ J A RP R O C E D U R EF O Rj a r n a m eS P E C I F I E DT H EU S EO FAD E P L O Y M E N TD E S C R I P T O R 2 0 2 1 0T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DB E C A U S EI TW A SA TAL E V E LT H A TI SI N C O M P A T I B L EW I T HT H EC U R R E N TV A L U EO F T H EE N C O D I N GB I N DO P T I O NO RS P E C I A LR E G I S T E R 2 0 2 1 2U S E R D E F I N E DR O U T I N En a m eE N C O U N T E R E DA NE X C E P T I O NA T T E M P T I N GT OL O A DJ A V AC L A S Sc l a s s n a m eF R O MJ A Rj a r n a m e . O R I G I N A LE X C E P T I O N :e x c e p t i o n s t r i n g . 2 0 2 1 3S T O R E DP R O C E D U R Ep r o c e d u r e n a m eH A SR E T U R N E DAD Y N A M I CR E S U L TS E TO FA NI N V A L I DC L A S S .P A R A M E T E Rn u m b e rI SN O TA D B 2R E S U L TS E T 3 0 0 0 0E X E C U T I O NF A I L E DD U ET OAD I S T R I B U T I O NP R O T O C O LE R R O RT H A TW I L LN O TA F F E C TT H ES U C C E S S F U LE X E C U T I O NO F S U B S E Q U E N TC O M M A N D SO RS Q LS T A T E M E N T S :R E A S O Nr e a s o n c o d e( s u b c o d e ) 3 0 0 0 2T H ES Q LS T A T E M E N TC A N N O TB EE X E C U T E DD U ET OAP R I O RC O N D I T I O NI NAC H A I NO FS T A T E M E N T S 3 0 0 2 0E X E C U T I O NF A I L E DD U ET OAD I S T R I B U T I O NP R O T O C O LE R R O RT H A TC A U S E DD E A L L O C A T I O NO FT H EC O N V E R S A T I O N :R E A S O N < r e a s o n c o d e( s u b c o d e ) > 3 0 0 2 1E X E C U T I O NF A I L E DD U ET OAD I S T R I B U T I O NP R O T O C O LE R R O RT H A TW I L LA F F E C TT H ES U C C E S S F U LE X E C U T I O NO FS U B S E Q U E N T C O M M A N D SO RS Q LS T A T E M E N T S :M A N A G E Rm a n a g e rA TL E V E Ll e v e lN O TS U P P O R T E DE R R O R 3 0 0 3 0C O M M I TR E Q U E S TW A SU N S U C C E S S F U L ,AD I S T R I B U T I O NP R O T O C O LV I O L A T I O NH A SB E E ND E T E C T E D ,T H EC O N V E R S A T I O NH A SB E E N D E A L L O C A T E D .O R I G I N A LS Q L C O D E = o r i g i n a l s q l c o d eA N DO R I G I N A LS Q L S T A T E = o r i g i n a l s q l s t a t e 3 0 0 4 0E X E C U T I O NF A I L E DD U ET OU N A V A I L A B L ER E S O U R C E ST H A TW I L LN O TA F F E C TT H ES U C C E S S F U LE X E C U T I O NO FS U B S E Q U E N T C O M M A N D SO RS Q LS T A T E M E N T S .R E A S O Nr e a s o n c o d eT Y P EO FR E S O U R C Er e s o u r c e t y p eR E S O U R C EN A M Er e s o u r c e n a m eP R O D U C T I Dp p p v v r r mR D B N A M Er d b n a m e 3 0 0 4 1E X E C U T I O NF A I L E DD U ET OU N A V A I L A B L ER E S O U R C E ST H A TW I L LA F F E C TT H ES U C C E S S F U LE X E C U T I O NO FS U B S E Q U E N TC O M M A N D S A N DS Q LS T A T E M E N T S .R E A S O N< r e a s o n c o d e >T Y P EO FR E S O U R C E< r e s o u r c e t y p e >R E S O U R C EN A M E< r e s o u r c e n a m e >P R O D U C TI D < p p p v v r r m >R D B N A M E< r d b n a m e > 3 0 0 5 0< c o m m a n d o r S Q L s t a t e m e n t t y p eC O M M A N DO RS Q LS T A T E M E N TI N V A L I DW H I L EB I N DP R O C E S SI NP R O G R E S S 3 0 0 5 1B I N DP R O C E S SW I T HS P E C I F I E DP A C K A G EN A M EA N DC O N S I S T E N C YT O K E NN O TA C T I V E 3 0 0 5 2P R O G R A MP R E P A R A T I O NA S S U M P T I O N SA R EI N C O R R E C T 3 0 0 5 3O W N E RA U T H O R I Z A T I O NF A I L U R E 3 0 0 6 0R D BA U T H O R I Z A T I O NF A I L U R E 3 0 0 6 1R D BN O TF O U N D 3 0 0 7 0c o m m a n dC O M M A N DN O TS U P P O R T E DE R R O R 3 0 0 7 1o b j e c t t y p eO B J E C TN O TS U P P O R T E DE R R O R 3 0 0 7 2p a r a m e t e rs u b c o d eP A R A M E T E RN O TS U P P O R T E DE R R O R 3 0 0 7 3p a r a m e t e rs u b c o d eP A R A M E T E RV A L U EN O TS U P P O R T E DE R R O R 3 0 0 7 4R E P L YM E S S A G EW I T Hc o d e p o i n t( s v r c o d )N O TS U P P O R T E DE R R O R 3 0 0 8 0C O M M U N I C A T I O NE R R O Rc o d e( s u b c o d e ) 3 0 0 8 1p r o tC O M M U N I C A T I O NE R R O RD E T E C T E D .A P I = a p i ,L O C A T I O N = l o c ,F U N C T I O N = f u n c ,E R R O RC O D E S = r c 1r c 2r c 3 3 0 0 8 2C O N N E C T I O NF A I L E DF O RS E C U R I T YR E A S O Nr e a s o n c o d e( r e a s o n s t r i n g ) 3 0 0 9 0R E M O T EO P E R A T I O NI N V A L I DF O RA P P L I C A T I O NE X E C U T I O NE N V I R O N M E N T 3 0 1 0 4E R R O RI NB I N DO P T I O No p t i o nA N DB I N DV A L U Ev a l u e 3 0 1 0 5B I N DO P T I O No p t i o n 1I SN O TA L L O W E DW I T HB I N DO P T I O No p t i o n 2
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
105/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
O RE X P R E S S I O NN U M B E Rc o l n a m e o r n u mF R O Mf r o mc c s i dT Ot o c c s i d ,A N DR E S U L T I N GI NS U B S T I T U T I O NC H A R A C T E R S . + 3 3 9T H ES Q LS T A T E M E N TH A SB E E NS U C C E S S F U L L YE X E C U T E D ,B U TT H E R EM A YB ES O M EC H A R A C T E RC O N V E R S I O NI N C O N S I S T E N C I E S + 3 9 4U S E RS P E C I F I E DO P T I M I Z A T I O NH I N T SU S E DD U R I N GA C C E S SP A T HS E L E C T I O N + 3 9 5U S E RS P E C I F I E DO P T I M I Z A T I O NH I N T SA R EI N V A L I D( R E A S O NC O D E=r e a s o n c o d e ) .T H EO P T I M I Z A T I O NH I N T SA R EI G N O R E + 4 0 2L O C A T I O Nl o c a t i o nI SU N K N O W N + 4 0 3T H EL O C A LO B J E C TR E F E R E N C E DB YT H EC R E A T EA L I A SS T A T E M E N TD O E SN O TE X I S T + 4 3 4O P T I O Nk e y w o r dI SAD E P R E C A T E DF E A T U R E + 4 4 5V A L U Ev a l u eH A SB E E NT R U N C A T E D + 4 6 2E X T E R N A LF U N C T I O NO RP R O C E D U R En a m e( S P E C I F I CN A M Es p e c i f i c n a m e )H A SR E T U R N E DAW A R N I N GS Q L S T A T E ,W I T HD I A G N O S T I C T E X Tt e x t + 4 6 4P R O C E D U R Ep r o cR E T U R N E Dn u mQ U E R YR E S U L TS E T S ,W H I C HE X C E E D ST H ED E F I N E DL I M I Ti n t e g e r + 4 6 6P R O C E D U R Ep r o cR E T U R N E Dn u mQ U E R YR E S U L T SS E T S + 4 9 4N U M B E RO FR E S U L TS E T SI SG R E A T E RT H A NN U M B E RO FL O C A T O R S + 4 9 5E S T I M A T E DP R O C E S S O RC O S TO Fe s t i m a t e a m o u n t 1P R O C E S S O RS E C O N D S( e s t i m a t e a m o u n t 2S E R V I C EU N I T S )I NC O S TC A T E G O R Y c o s t c a t e g o r yE X C E E D SAR E S O U R C EL I M I TW A R N I N GT H R E S H O L DO Fl i m i t -a m o u n tS E R V I C EU N I T S + 5 3 5T H ER E S U L TO FT H EP O S I T I O N E DU P D A T EO RD E L E T EM A YD E P E N DO NT H EO R D E RO FT H ER O W S + 5 4 1T H ER E F E R E N T I A LO RU N I Q U EC O N S T R A I N Tn a m eH A SB E E NI G N O R E DB E C A U S EI TI SAD U P L I C A T E + 5 5 1a u t h i dD O E SN O TH A V ET H EP R I V I L E G ET OP E R F O R MO P E R A T I O No p e r a t i o nO NO B J E C To b j e c t n a m e + 5 5 2a u t h i dD O E SN O TH A V ET H EP R I V I L E G ET OP E R F O R MO P E R A T I O No p e r a t i o n + 5 5 8T H EW I T HG R A N TO P T I O NI SI G N O R E D + 5 6 1T H EA L T E R ,I N D E X ,R E F E R E N C E S ,A N DT R I G G E RP R I V I L E G E SC A N N O TB EG R A N T E DP U B L I CA TA L LL O C A T I O N S + 5 6 2AG R A N TO FAP R I V I L E G EW A SI G N O R E DB E C A U S ET H EG R A N T E EA L R E A D YH A ST H EP R I V I L E G EF R O MT H EG R A N T O R + 5 8 5T H ES C H E M AN A M Es c h e m a n a m eA P P E A R SM O R ET H A NO N C EI NT H EC U R R E N TP A T H + 5 9 9C O M P A R I S O NF U N C T I O N SA R EN O TC R E A T E DF O RAD I S T I N C TT Y P EB A S E DO NAL O N GS T R I N GD A T AT Y P E + 6 1 0AC R E A T E / A L T E RO NO B J E C To b j e c t n a m eH A SP L A C E DO B J E C TI Nu t i l i t yP E N D I N G + 6 4 5W H E R EN O TN U L LI SI G N O R E DB E C A U S ET H EI N D E XK E YC A N N O TC O N T A I NN U L LV A L U E S + 6 5 0T H ET A B L EB E I N GC R E A T E DO RA L T E R E DC A N N O TB E C O M EAD E P E N D E N TT A B L E + 6 5 3T A B L Et a b l e n a m eI NP A R T I T I O N E DT A B L E S P A C Et s p a c e n a m eI SN O TA V A I L A B L EB E C A U S EI T SP A R T I T I O N E DI N D E XH A S N O TB E E NC R E A T E D + 6 5 5S T O G R O U Ps t o g r o u p _ n a m eH A SB O T HS P E C I F I CA N DN O N S P E C I F I CV O L U M EI D S .I TW I L LN O TB EA L L O W E DI NF U T U R ER E L E A S E S + 6 5 8T H ES U B P A G E SV A L U EI SI G N O R E DF O RT H EC A T A L O GI N D E Xi n d e x n a m e + 6 6 4T H EI N T E R N A LL E N G T HO FT H EL I M I T K E YF I E L D SF O RT H EP A R T I T I O N E DI N D E Xi n d e x n a m eE X C E E D ST H EL E N G T HI M P O S E DB YD B 2 + 7 3 8D E F I N I T I O NC H A N G EO Fo b j e c to b j e c t _ n a m eM A YR E Q U I R ES I M I L A RC H A N G EO NR E A D O N L YS Y S T E M S + 7 9 9AS E TS T A T E M E N TR E F E R E N C E SAS P E C I A LR E G I S T E RT H A TD O E SN O TE X I S TA TT H ES E R V E RS I T E + 8 0 2T h en u l li n d i c a t o rw a ss e tt o2a sa na r i t h m e t i cs t a t e m e n td i d n ' tw o r k . + 8 0 6B I N DI S O L A T I O NL E V E LR RC O N F L I C T SW I T HT A B L E S P A C EL O C K S I Z EP A G EO RL O C K S I Z ER O WA N DL O C K M A X0 + 8 0 7T H ER E S U L TO FD E C I M A LM U L T I P L I C A T I O NM A YC A U S EO V E R F L O W + 8 6 3T H EC O N N E C T I O NW A SS U C C E S S F U LB U TO N L YS B C SW I L LB ES U P P O R T E D + 8 8 3R O L L B A C KT OS A V E P O I N TO C C U R R E DW H E NT H E R EW E R EO P E R A T I O N ST H A TC A N N O TB EU N D O N E ,O RA NO P E R A T I O NT H A TC A N N O TB E U N D O N EO C C U R R E DW H E NT H E R EW A SAS A V E P O I N TO U T S T A N D I N G + 2 0 0 0T Y P E1I N D E X E SW I T HS U B P A G E SG R E A T E RT H A N1C A N N O TB E C O M EG R O U PB U F F E RP O O LD E P E N D E N TI NAD A T AS H A R I N G E N V I R O N M E N T + 2 0 0 0 2T H EG B P C A C H ES P E C I F I C A T I O NI SI G N O R E D ,b p n a m eD O E SN O TA L L O WC A C H I N G + 2 0 0 0 7U S EO FO P T I M I Z A T I O NH I N T SI SD I S A L L O W E DB YAD B 2S U B S Y S T E MP A R A M E T E R .T H ES P E C I A LR E G I S T E R O P T I M I Z A T I O NH I N T I SS E TT OT H ED E F A U L TV A L U EO FB L A N K S . + 2 0 1 2 2D E F I N EN OO P T I O NI SN O TA P P L I C A B L EI NT H EC O N T E X TS P E C I F I E D + 2 0 1 4 1T R U N C A T I O NO FV A L U EW I T HL E N G T Hl e n g t hO C C U R R E DF O Rh v o r p a r m n u m b e r + 2 0 2 6 7O P T I O Nc l a u s eI SN O TS U P P O R T E DI NT H EC O N T E X TI NW H I C HI TW A SS P E C I F I E D + 3 0 1 0 0O P E R A T I O NC O M P L E T E DS U C C E S S F U L L YB U TAD I S T R I B U T I O NP R O T O C O LV I O L A T I O NH A SB E E ND E T E C T E D .O R I G I N A L S Q L C O D E = o r i g i n a l s q l c o d eA N DO R I G I N A LS Q L S T A T E = o r i g i n a l s q l s t a t e
0 1 2 3 4 5 6 7 8 9 } A B C D E F G H I 1 2 3 4 5 6 7 8 9 J K L M N O P Q R
External resources
A more extensive list (http://www.theamericanprogrammer.com/programming/sqlcodes.shtml) of the codes
License
GNU Free Documentation License
Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. PREAMBLE
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 106/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 107/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various partiesfor example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version 108/110
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
4/2/2014
Structured Query Language/Print version - Wikibooks, open books for an open world
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
11. RELICENSING
"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
http://en.wikibooks.org/wiki/Structured_Query_Language/Print_version
110/110