Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
615,96 KB
Nội dung
Subqueries 231 If the scalar subquery returns more than one row, the query will fail. If the scalar sub- query returns no rows, the value is NULL . Finding Total Space and Free Space Using Dictionary Views The following dictionary views are best friends of a DBA. They show the most critical aspect of the database from the user perspective—the space allocated and free. If the DBA is not monitoring the growth and free space available in the database, it is likely that they might get calls from the user community that they ran out of space in the tablespace. Let’s build a query using four dictionary views (you may need the SELECT_CATALOG_ROLE privilege to query these views). DBA_TABLESPACES ÛN : Shows the tablespace name, type, and so on. DBA_DATA_FILES ÛN : Shows the data files associated with a permanent or undo tablespace and the size of the data file. The total size of all data files associated with a tablespace gives the total size of the tablespace. DBA_TEMP_FILES ÛN : Shows the temporary files associated with a temporary tablespace and their size. DBA_FREE_SPACE ÛN : Shows the unallocated space (free space) in each tablespace. The query to get the tablespace names and type of tablespace would be as follows: column tablespace_name format a18 SELECT tablespace_name, contents FROM dba_tablespaces; TABLESPACE_NAME CONTENTS ------------------ --------- SYSTEM PERMANENT SYSAUX PERMANENT UNDOTBS1 UNDO TEMP TEMPORARY USERS PERMANENT EXAMPLE PERMANENT To find the total space allocated to each tablespace, you need to query DBA_DATA_FILES and DBA_TEMP_FILES . Since you are using a group function ( SUM ) along with a nonaggregated column ( tablespace_name ), the GROUP BY clause is a must. Notice the use of an arithmetic operation on the aggregated result to display the bytes in megabytes. SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_data_files 95127c04.indd 231 2/18/09 9:43:39 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 232 Chapter 4 N Using Joins and Subqueries GROUP BY tablespace_name; TABLESPACE_NAME MBYTES ------------------ ---------- UNDOTBS1 730 SYSAUX 800.1875 USERS 201.75 SYSTEM 710 EXAMPLE 100 SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_temp_files GROUP BY tablespace_name; TABLESPACE_NAME MBYTES ------------------ ---------- TEMP 50.0625 You can find the total free space in each tablespace using the DBA_FREE_SPACE view. Notice that the free space from temporary tablespace is not shown in this query. SELECT tablespace_name, SUM(bytes)/1048576 MBytesFree FROM dba_free_space GROUP BY tablespace_name; TABLESPACE_NAME MBYTESFREE ------------------ ---------- SYSAUX 85.25 UNDOTBS1 718.6875 USERS 180.4375 SYSTEM 8.3125 EXAMPLE 22.625 Let’s now try to display the total size of the tablespaces and their free space side-by-side using a UNION ALL query. UNION ALL is used to avoid sorting. UNION will produce the same result. SELECT tablespace_name, SUM(bytes)/1048576 MBytes, 0 MBytesFree FROM dba_data_files GROUP BY tablespace_name UNION ALL SELECT tablespace_name, SUM(bytes)/1048576 MBytes, 0 FROM dba_temp_files 95127c04.indd 232 2/18/09 9:43:39 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Subqueries 233 GROUP BY tablespace_name UNION ALL SELECT tablespace_name, 0, SUM(bytes)/1048576 FROM dba_free_space GROUP BY tablespace_name; TABLESPACE_NAME MBYTES MBYTESFREE ------------------ ---------- ---------- UNDOTBS1 730 0 SYSAUX 800.1875 0 USERS 201.75 0 SYSTEM 710 0 EXAMPLE 100 0 TEMP 50.0625 0 SYSAUX 0 85.25 UNDOTBS1 0 718.6875 USERS 0 180.4375 SYSTEM 0 8.3125 EXAMPLE 0 22.625 You got the result, but it’s not exactly as you expected. You want to see the free-space information beside each tablespace. Let’s join the results of the total space with the free space and see what happens. Here you are creating two subqueries (inline views total- space and freespace ) and joining them together using the tablespace_name column. SELECT tablespace_name, MBytes, MBytesFree FROM (SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_data_files GROUP BY tablespace_name UNION ALL SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_temp_files GROUP BY tablespace_name) totalspace JOIN (SELECT tablespace_name, 0, SUM(bytes)/1048576 MBytesFree FROM dba_free_space GROUP BY tablespace_name) freespace USING (tablespace_name); 95127c04.indd 233 2/18/09 9:43:39 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 234 Chapter 4 N Using Joins and Subqueries TABLESPACE_NAME MBYTES MBYTESFREE ------------------ ---------- ---------- SYSAUX 800.1875 85.25 UNDOTBS1 730 718.6875 USERS 201.75 180.4375 SYSTEM 710 8.3125 EXAMPLE 100 22.625 You are almost there; the only item missing is information about the temporary tablespace. Since the temporary-tablespace free-space information is not included in the freespace subquery and you used an INNER join condition, the result set did not include temporary tablespaces. Now if you change the INNER JOIN to an OUTER JOIN , you get the desired result: SELECT tablespace_name, MBytes, MBytesFree FROM (SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_data_files GROUP BY tablespace_name UNION ALL SELECT tablespace_name, SUM(bytes)/1048576 MBytes FROM dba_temp_files GROUP BY tablespace_name) totalspace LEFT OUTER JOIN (SELECT tablespace_name, 0, SUM(bytes)/1048576 MBytesFree FROM dba_free_space GROUP BY tablespace_name) freespace USING (tablespace_name) ORDER BY 1; TABLESPACE_NAME MBYTES MBYTESFREE ------------------ ---------- ---------- EXAMPLE 100 22.625 SYSAUX 800.1875 85.0625 SYSTEM 710 8.3125 TEMP 50.0625 UNDOTBS1 730 718.6875 USERS 201.75 180.4375 95127c04.indd 234 2/18/09 9:43:39 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Subqueries 235 Another method to write the same query would be to use the query you built earlier and aggregate its result using an outer query, as shown here: SELECT tsname, sum(MBytes) MBytes, sum(MBytesFree) MBytesFree FROM ( SELECT tablespace_name tsname, SUM(bytes)/1048576 MBytes, 0 MBytesFree FROM dba_data_files GROUP BY tablespace_name UNION ALL SELECT tablespace_name, SUM(bytes)/1048576 MBytes, 0 FROM dba_temp_files GROUP BY tablespace_name UNION ALL SELECT tablespace_name, 0, SUM(bytes)/1048576 FROM dba_free_space GROUP BY tablespace_name) GROUP BY tsname ORDER BY 1; TSNAME MBYTES MBYTESFREE ------------------------------ ---------- ---------- EXAMPLE 100 22.625 SYSAUX 800.1875 85.0625 SYSTEM 710 8.3125 TEMP 50.0625 0 UNDOTBS1 730 718.6875 USERS 201.75 180.4375 Multiple-Column Subqueries A subquery is multiple-column when you have more than one column in the SELECT clause of the subquery. Multiple-column subqueries are generally used to compare column condi- tions or in an UPDATE statement. Let’s consider a simple example using the STATE and CITY tables shown here: SQL> SELECT * FROM state; CNT_CODE ST_CODE ST_NAME ---------- ------- ------------ 1 TX TEXAS 1 CA CALIFORNIA 95127c04.indd 235 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 236 Chapter 4 N Using Joins and Subqueries 91 TN TAMIL NADU 1 TN TENNESSE 91 KL KERALA SQL> SELECT * FROM city; CNT_CODE ST_CODE CTY_CODE CTY_NAME ---------- ------- -------- -------------- 1 TX 1001 DALLAS 91 TN 2243 MADRAS 1 CA 8099 LOS ANGELES List the cities in Texas using a subquery on the STATE table: SELECT cty_name FROM city WHERE (cnt_code, st_code) IN (SELECT cnt_code, st_code FROM state WHERE st_name = ‘TEXAS’); CTY_NAME ---------- DALLAS Subqueries in Other DML Statements You can use subqueries in DML statements such as INSERT , UPDATE , DELETE , and MERGE . DML statements and their syntax are discussed in Chapter 5, “Manipulating Data.” The following are some examples of subqueries in DML statements: To update the salary of all employees to the maximum salary in the corresponding ÛN department (correlated subquery), use this: UPDATE employees e1 SET salary = (SELECT MAX(salary) FROM employees e2 WHERE e1.department_id = e2.department_id); To delete the records of employees whose salary is less than the average salary in the ÛN department (using a correlated subquery), use this: DELETE FROM employees e WHERE salary < (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); 95127c04.indd 236 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Subqueries 237 To insert records to a table using a subquery, use this: ÛN INSERT INTO employee_archive SELECT * FROM employees; To specify a subquery in the ÛN VALUES clause of the INSERT statement, use this: INSERT INTO departments (department_id, department_name) VALUES ((SELECT MAX(department_id) +10 FROM departments), ‘EDP’); You can also have a subquery in the INSERT , UPDATE , and DELETE statements in place of the table name. Here is an example: DELETE FROM (SELECT * FROM departments WHERE department_id < 20) WHERE department_id = 10; The subquery can have an optional WITH clause. WITH READ ONLY specifies that the subquery cannot be updated. WITH CHECK OPTION specifies that if the subquery is used in place of a table in an INSERT , UPDATE , or DELETE statement, Oracle will not allow any changes to the table that would produce rows that are not included in the subquery. Let’s look at an example: INSERT INTO (SELECT department_id, department_name FROM departments WHERE department_id < 20) VALUES (35, ‘MARKETING’); 1 row created. INSERT INTO (SELECT department_id, department_name FROM departments WHERE department_id < 20 WITH CHECK OPTION) VALUES (45, ‘EDP’) SQL> / FROM departments * ERROR at line 2: ORA-01402: view WITH CHECK OPTION where-clause violation SQL> 95127c04.indd 237 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 238 Chapter 4 N Using Joins and Subqueries Summary In this chapter, you learned to retrieve data from multiple tables. I started off discussing table joins. You also learned how to use subqueries and set operators. Joins are used to relate two or more tables (or views). In a relational database, it is com- mon to have a requirement to join data. The tables are joined by using a common column in the tables in the WHERE clause of the query. Oracle supports ISO/ANSI SQL1999 syntax for joins. Using this syntax, the tables are joined using the JOIN keyword, and a condition can be specified using the ON clause. If the join condition uses the equality operator ( = or IN ), it is known as an equality join. If any other operator is used to join the tables, it is a nonequality join. If you do not specify any join condition between the tables, the result will be a Cartesian product: each row from the first table joined to every row in the second table. To avoid Cartesian joins, there should be at least n-1 join conditions in the WHERE clause when there are n tables in the FROM clause. A table can be joined to itself. If you want to select the results from a table, even if there are no corresponding rows in the joined table, you can use the outer join operator: (+) . In the ANSI syntax, you can use the NATURAL JOIN , CROSS JOIN , LEFT JOIN , RIGHT JOIN , and FULL JOIN keywords to specify the type of join. A subquery is a query within a query. Writing subqueries is a powerful way to manipu- late data. You can write single-row and multiple-row subqueries. Single-row subqueries must return zero or one row; multiple-row subqueries return zero or more rows. IN and EXISTS are the most commonly used subquery operators. Subqueries can appear in the WHERE clause or in the FROM clause. They can also replace table names in SELECT , DELETE , INSERT , and UPDATE statements. Subqueries that return one row and one column result are known as scalar subqueries. Scalar subqueries can be used in most places where you would use an expression. Set operators are used to combine the results of more than one query into one. Each query is separate and will work on its own. Four set operators are available in Oracle: UNION , UNION ALL , MINUS , and INTERSECT . Exam Essentials Understand joins. Make sure you know the different types of joins. Understand the differ- ence between natural, cross, simple, complex, and outer joins. Know the different outer join clauses. You can specify outer joins using LEFT , RIGHT , or FULL . Know the syntax of each type of join. Be sure of the join syntax. Spend time practicing each type of join using the ANSI syntax. Understand the restrictions of using each ANSI keyword in the JOIN and their implied column-naming conventions. 95127c04.indd 238 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Exam Essentials 239 Know how to write subqueries. Understand the use and flexibility of subqueries. Practice using scalar subqueries and correlated subqueries. Understand the use of the ORDER BY clause in the subqueries. You can use the ORDER BY clause in all subqueries, except the subqueries appearing in the WHERE clause of the query. You can use the GROUP BY clause in the subqueries. Know the set operators. Understand the set operators that can be used in compound queries. Know the difference between the UNION and UNION ALL operators. Understand where you can specify the ORDER BY clause when using set operators. When using set operators to join two or more queries, the ORDER BY clause can appear only at the very end of the query. You can specify the column names as they appear in the top query or use positional notation. 95127c04.indd 239 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 240 Review Questions Review Questions 1. Which line of code has an error? A. SELECT dname, ename B. FROM emp e, dept d C. WHERE emp.deptno = dept.deptno D. ORDER BY 1, 2; 2. What will be the result of the following query? SELECT c.cust_id, c.cust_name, o.ord_date, o.prod_id FROM customers c, orders o WHERE c.cust_id = o.cust_id (+); A. List all the customer names in the CUSTOMERS table and the orders they made from the ORDERS table, even if the customer has not placed an order. B. List only the names of customers from the CUSTOMERS table who have placed an order in the ORDERS table. C. List all orders from the ORDERS table, even if there is no valid customer record in the CUSTOMERS table. D. For each record in the CUSTOMERS table, list the information from the ORDERS table. 3. The CUSTOMERS and ORDERS tables have the following data: SQL> SELECT * FROM customers; CUST_ CUST_NAME PHONE CITY ----- -------------------- --------------- ----------- A0101 Abraham Taylor Jr. Fort Worth B0134 Betty Baylor 972-555-5555 Dallas B0135 Brian King Chicago SQL> SELECT * FROM orders; ORD_DATE PROD_ID CUST_ID QUANTITY PRICE --------- ---------- ------- ---------- ---------- 20-FEB-00 1741 B0134 5 65.5 02-FEB-00 1001 B0134 25 2065.85 02-FEB-00 1001 B0135 3 247.9 When the following query is executed, what will be the value of PROD_ID and ORD_DATE for the customer Abraham Taylor Jr.? SELECT c.cust_id, c.cust_name, o.ord_date, o.prod_id FROM customers c, orders o WHERE c.cust_id = o.cust_id (+); 95127c04.indd 240 2/18/09 9:43:40 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... row Chapter 5 Manipulating Data Oracle Database 11g: SQL Fundamentals I exam objectives covered in this chapter: ÛÛ Manipulating Data NN Describe each data manipulation language (DML) statement NN Insert rows into a table NN Update rows in a table NN Delete rows from a table NN Control transactions In this chapter, I will cover how to manipulate data In an Oracle Database, this means using SQL data... clause to delete rows when certain conditions are met At the time of publishing this book, however, MERGE is not part of the Oracle Database11g SQL Fundamentals I test Table 5.1 summarizes the DML statements that Oracle supports Ta b l e 5 1 DML Statements Supported by Oracle Statement Purpose INSERT Adds rows to a table UPDATE Changes the value stored in a table DELETE Removes rows from a... data into a table, update existing data, and delete existing data from a table Because Oracle is a multiuser database and more than one user or session can change data at the same time, I will also need to cover locks and how they are used to control this concurrency I will also cover another effect of a multiuser database, which is that data can change during the execution of statements You can exercise... table, with a minimum of p database calls The syntax for the multiple-table INSERT statement is as shown here: INSERT [ALL | FIRST] {WHEN THEN INTO … … …} [ELSE } Using DML Statements 257 The keyword ALL tells Oracle to evaluate each and every WHEN clause, whether or not any evaluate to TRUE In contrast, the FIRST keyword tells Oracle to stop evaluating WHEN... and require significant rollback segment space If you are deleting all rows from a table, consider using the TRUNCATE statement, as described in the next section TRUNCATE is not included in the Oracle Database11g SQL Fundamentals I exam, but I’ve included it here for completeness Truncating a Table Truncating a table can accomplish the same task as deleting if you’re deleting all rows from the table,... Though the MERGE statement is not part of the test, to complete the DML discussion I will give you an introduction to the MERGE statement MERGE is a very powerful statement available in Oracle 11g (it was introduced in Oracle 9i) that can insert or update rows based on a condition The statement also has an option to delete rows when certain conditions are met The MERGE statement has a join specification... SQL that is employed to change data in a database table Since SQL is English-like, meaning it’s not cryptic like C or Perl, the statements used to perform data manipulation are easy to remember The INSERT statement is used to add new rows to a table The UPDATE statement is used modify rows in a table, and the DELETE statement is used to remove rows from a table Oracle also has the MERGE statement to... statement? By the way, the table has about 2 million rows Though the developer thought he was updating only one row in the ORDER_HEADER table and querying only three rows from the ORDER_TRANSACTIONS table, Oracle was in fact updating all the 2 million rows in the table Why? Using DML Statements 263 Look carefully at the UPDATE statement; it is missing a WHERE clause for the UPDATE statement The WHERE clause... enclose character and datetime values in single quotes For date values, if the value is not in the default date format, you may have to use the TO_ DATE function When you enclose a value in single quotes, Oracle considers it character data and performs an implicit conversion if the column datatype is not a character; hence, do not enclose numeric values in single quotes 254 Chapter 5 Manipulating Data... will remove all rows from a table However, TRUNCATE is not DML—it is DDL, and therefore, it has different characteristics from the DELETE statement DDL is the subset of SQL that is employed to define database objects One of the key differences between DML and DDL is that DDL statements will implicitly perform a commit, not only affecting the change in object definition but also committing any pending . of the database from the user perspective—the space allocated and free. If the DBA is not monitoring the growth and free space available in the database, . subquery is used in place of a table in an INSERT , UPDATE , or DELETE statement, Oracle will not allow any changes to the table that would produce rows that