Source Topic: http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands
SQL Tutorials :
https://www.youtube.com/watch?v=y7nX0UF2AJ8&list=PL617DE313A1E79EDB
Structured Query Language (SQL) declarative languages that are nonprocedural and describe what should be done
SQL Tutorials :
https://www.youtube.com/watch?v=y7nX0UF2AJ8&list=PL617DE313A1E79EDB
What are the difference between DDL, DML and DCL commands?
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
- CREATE - to create objects in the database
- ALTER - alters the structure of the database
- DROP - delete objects from the database
- TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
- COMMENT - add comments to the data dictionary
- RENAME - rename an object
[oracle@localhost ~]$ sqlplus / as sysdba
SQL> startup
ORACLE instance started.
Total System Global Area 456146944 bytes
Fixed Size 1344840 bytes
Variable Size 348129976 bytes
Database Buffers 100663296 bytes
Redo Buffers 6008832 bytes
Database mounted.
Database opened.
SQL> connect system/oracle
Connected.
SQL> connect hr/oracle
Connected.
SQL> create table plants (
2 plant_id number primary key,
3 common_name varchar2 (15)
4 );
Table created.
SQL> insert into plants values (1, 'African Violet');
1 row created.
SQL> insert into plants values (2, 'Amaryllis');
1 row created.
1 row created.
SQL> insert into plants values (2, 'Amaryllis');
1 row created.
SQL> alter table plants add (
2 latin_name varchar2 (40)
3 );
Table altered.
SQL> desc plants
Name Null? Type
----------------------------------------- -------- ----------------------------
PLANT_ID NOT NULL NUMBER
COMMON_NAME VARCHAR2(15)
LATIN_NAME VARCHAR2(40)
2 latin_name varchar2 (40)
3 );
Table altered.
SQL> desc plants
Name Null? Type
----------------------------------------- -------- ----------------------------
PLANT_ID NOT NULL NUMBER
COMMON_NAME VARCHAR2(15)
LATIN_NAME VARCHAR2(40)
SQL> grant select on plants to scott;
Grant succeeded.
SQL> connect scott/oracle
Connected.
SQL> select * from hr.plants;
PLANT_ID COMMON_NAME LATIN_NAME
---------- --------------- ----------------------------------------
1 African Violet
2 Amaryllis
SQL> connect hr/oracle
Connected.
SQL> revoke select on plants from scott;
Revoke succeeded.
SQL> connect scott/oracle
Connected.
SQL> select * from hr.plants;
select * from hr.plants
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> connect hr/oracle
Connected.
SQL> drop table plants;
Table dropped.
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
- SELECT - retrieve data from the a database
- INSERT - insert data into a table
- UPDATE - updates existing data within a table
- DELETE - deletes all records from a table, the space for the records remain
- MERGE - UPSERT operation (insert or update)
- CALL - call a PL/SQL or Java subprogram
- EXPLAIN PLAN - explain access path to data
- LOCK TABLE - control concurrency
SQL> show user
USER is "HR"
SQL> select * from employees;
SQL> INSERT INTO employees (employee_id, last_name, email, job_id, hire_date, salary) VALUES (1234, 'Mascis', 'JMASCIS', 'IT_PROG', '14-FEB-2011', 9000);
1 row created.
SQL> UPDATE employees SET salary=9100 WHERE employee_id=1234;
1 row updated.
SQL> DELETE FROM employees WHERE employee_id=1234;
1 row deleted.
- Join is a query that combines rows from two or more tables, views, or materialized views.
SQL> show user
USER is "HR"
SQL> select email, department_name
2 from employees join departments
3 on employees.department_id = departments.department_id
4 where employee_id in (100,103)
5 order by email;
EMAIL DEPARTMENT_NAME
------------------------- ------------------------------
AHUNOLD IT
SKING Executive
- Join is a query that combines rows from two or more tables, views, or materialized views.
USER is "HR"
SQL> select email, department_name
2 from employees join departments
3 on employees.department_id = departments.department_id
4 where employee_id in (100,103)
5 order by email;
EMAIL DEPARTMENT_NAME
------------------------- ------------------------------
AHUNOLD IT
SKING Executive
- Join types include the following:
1. inner join is a join of two or more tables that returns only rows that satisfy the join condition
2. outer join returns all rows that satisfy the join condition and also returns rows from one table for which no rows from the other table satisfy the condition
2.1 left outer join of employees and departments retrieves all rows in the employees table even if there is no match in departments.
2.2 right outer join retrieves all rows in departments even if there is no match in employees.
3. Cartesian products (used to test high load in database server) Each row of one table combines with each row of the other, if employees has 107 rows and departments has 27, then the Cartesian product contains 107*27 rows.
- subquery is a SELECT statement nested within another SQL statement. Subqueries are useful when you must execute multiple queries to solve a single problem.
SQL> show user
USER is "HR"
SQL> select first_name, last_name
2 from employees
3 where department_id
4 in (select department_id from departments where location_id = 1800);
FIRST_NAME LAST_NAME
-------------------- -------------------------
Michael Hartstein
Pat Fay
1. inner join is a join of two or more tables that returns only rows that satisfy the join condition
2. outer join returns all rows that satisfy the join condition and also returns rows from one table for which no rows from the other table satisfy the condition
2.1 left outer join of employees and departments retrieves all rows in the employees table even if there is no match in departments.
2.2 right outer join retrieves all rows in departments even if there is no match in employees.
3. Cartesian products (used to test high load in database server) Each row of one table combines with each row of the other, if employees has 107 rows and departments has 27, then the Cartesian product contains 107*27 rows.
- subquery is a SELECT statement nested within another SQL statement. Subqueries are useful when you must execute multiple queries to solve a single problem.
SQL> show user
USER is "HR"
SQL> select first_name, last_name
2 from employees
3 where department_id
4 in (select department_id from departments where location_id = 1800);
FIRST_NAME LAST_NAME
-------------------- -------------------------
Michael Hartstein
Pat Fay
- Virtual Private Database (VPD) feature could restrict the query of employees using a WHERE clause
- implicit query is a component of a DML statement that retrieves data without using a subquery
SQL> update employees
2 set salary = salary*1.1
3 where last_name = 'Baer';
1 row updated.
- savepoint is a user-declared intermediate marker within the context of a transaction.
SQL> INSERT INTO employees (employee_id, last_name, email, job_id, hire_date, salary) VALUES (1234, 'Mascis', 'JMASCIS', 'IT_PROG', '14-FEB-2011', 9000);
1 row created.
SQL> commit;
Commit complete.
SQL> set transaction name 'update salaries';
Transaction set.
SQL> savepoint before_salary_update;
Savepoint created.
SQL> update employees set salary=9100 where employee_id=1234;
1 row updated.
SQL> select salary from employees where employee_id=1234;
SALARY
----------
9100
SQL> rollback to savepoint before_salary_update;
Rollback complete.
SQL> select salary from employees where employee_id=1234;
SALARY
----------
9000
SQL> update employees set salary=9200 where employee_id=1234;
1 row updated.
SQL> select salary from employees where employee_id=1234;
SALARY
----------
9200
SQL> commit comment 'Updated salaries';
Commit complete.
- Session control statements enable you to:
- Alter the current session by performing a specialized function, such as enabling and disabling SQL tracing (ALTER SESSION).
- Enable and disable roles, which are groups of privileges, for the current session (SETROLE).
SQL> connect system/oracle
Connected.
SQL> create role dw_manager identified by oracle;
Role created.
SQL> alter session set sql_trace = true;
Session altered.
SQL> set role all except dw_manager;
Role set.
SQL> set role none;
Role set.
SQL> set role none;
Role set.
- System control statements change the properties of the database instance. The only system control statement is ALTER SYSTEM
- from a new terminal window login as scott user
[oracle@localhost ~]$ sqlplus scott/oracle
SQL> show user
USER is "SCOTT"
SQL> select * from tab;
TNAME TABTYPE CLUSTERID
------------------------------ ------- ----------
BIN$AnwxBnZJbeHgUAB/AQAykw==$0 TABLE
BONUS TABLE
DATA_STAGING_EVO TABLE
DATA_STAGING_OTN TABLE
DATA_STAGING_PTN TABLE
DATA_STAGING_REPOS TABLE
DATA_STAGING_XQY TABLE
DEPT TABLE
EMP TABLE
SALGRADE TABLE
STAT_TABLE TABLE
11 rows selected.
- from the work terminal window
SQL> connect sys as sysdba
Enter password:
Connected.
SQL> desc v$session
SQL> set lines 800
SQL> column username format a25;
SQL> column status format a25;
SQL> column osuser format a25;
SQL> column machine format a25;
SQL> column action format a25;
SQL> column logon_time format a25;
SQL> column event format a45;
SQL> column state format a25;
SQL> SELECT username,status,action,logon_time,event,state
2 FROM v$session
3 WHERE username='SCOTT'; - use Capital letters as users saved in database
USERNAME STATUS ACTION LOGON_TIME EVENT STATE
------------------------------ ------------------------- ------------------------- ------------------------- --------------------------------------------- -------------------------
SCOTT INACTIVE 17-SEP-14 SQL*Net message from client WAITING
SQL> select program,status,action,logon_time
2 from v$session
3 where type='BACKGROUND';
PROGRAM STATUS ACTION LOGON_TIME
------------------------------------------------ ------------------------- ------------------------- -------------------------
oracle@localhost.localdomain (PMON) ACTIVE 16-SEP-14
oracle@localhost.localdomain (PSP0) ACTIVE 16-SEP-14
oracle@localhost.localdomain (VKTM) ACTIVE 16-SEP-14
oracle@localhost.localdomain (GEN0) ACTIVE 16-SEP-14
oracle@localhost.localdomain (DIAG) ACTIVE 16-SEP-14
oracle@localhost.localdomain (DBRM) ACTIVE 16-SEP-14
..........................
SQL> select username,sid,serial#
2 from v$session
3 where username is not null;
USERNAME SID SERIAL#
------------------------------ ---------- ----------
SYS 1 31
SCOTT 51 13
SQL> alter system kill session '51,13';
System altered.
- from scott terminal:
SQL> select * from emp;
select * from emp
*
ERROR at line 1:
ORA-00028: your session has been killed
- list background process
SQL> show user
USER is "SYS"
SQL> desc v$process
Name Null? Type
----------------------------------------- -------- ----------------------------
ADDR RAW(4)
PID NUMBER
SPID VARCHAR2(24)
PNAME VARCHAR2(5)
USERNAME VARCHAR2(15)
SERIAL# NUMBER
TERMINAL VARCHAR2(30)
PROGRAM VARCHAR2(48)
TRACEID VARCHAR2(255)
TRACEFILE VARCHAR2(513)
BACKGROUND VARCHAR2(1)
LATCHWAIT VARCHAR2(8)
LATCHSPIN VARCHAR2(8)
PGA_USED_MEM NUMBER
PGA_ALLOC_MEM NUMBER
PGA_FREEABLE_MEM NUMBER
PGA_MAX_MEM NUMBER
SQL> column pname format a20;
SQL> column username format a20;
SQL> column tracefile format a125;
SQL> set lines 2000
SQL> select pname, username, tracefile FROM v$process where pname is not null;
PNAME USERNAME TRACEFILE
-------------------- -------------------- -----------------------------------------------------------------------------------------------------------------------------
PMON oracle /home/oracle/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_pmon_27063.trc
PSP0 oracle /home/oracle/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_psp0_27065.trc
VKTM oracle /home/oracle/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_vktm_27067.trc
GEN0 oracle /home/oracle/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_gen0_27071.trc
DIAG oracle /home/oracle/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_diag_27073.trc
Data Control Language (DCL) statements. Some examples:
- GRANT - gives user's access privileges to database
- REVOKE - withdraw access privileges given with the GRANT command
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
- COMMIT - save work done
- SAVEPOINT - identify a point in a transaction to which you can later roll back
- ROLLBACK - restore database to original since the last COMMIT
- SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use
### uses DDL statements to create the plants table and then uses DML to insert two rows in the table
- For any SQL statement processed by Oracle, the optimizer performs the following operations:
- Evaluation of expressions and conditions
- Inspection of integrity constraints to learn more about the data and optimize based on this metadata
- Statement transformation
- Choice of optimizer goals
- Choice of access paths
- Choice of join orders
Optimizer Components
- query transformer determines whether it is helpful to change the form of the query so that the optimizer can generate a better execution plan
- Estimator determines the overall cost of a given execution plan. The estimator generates three different types of measures to achieve this goal (Selectivity,Cardinality,Cost)
- plan generator tries out different plans for a submitted query and picks the plan with the lowest cost
- access path is the way in which data is retrieved from the database
- The database can use several different access paths to retrieve data from a table:
- Full table scans
- Rowid scans
- Index scans
- Cluster scans
- Hash scans
- Optimizer statistics are a collection of data that describe details about the database and the objects in the database
- Table statistics
- Column statistics
- Index statistics
- System statistics
- Optimizer Hints, A hint is a comment in a SQL statement that acts as an instruction to the optimizer
### Execution Plan for SELECT with FIRST_ROWS Hint
SQL> connect hr/oracle
Connected.
SQL> SELECT /*+ FIRST_ROWS(25) */ employee_id, department_id
2 from employees
3 where department_id > 50;
EMPLOYEE_ID DEPARTMENT_ID
----------- -------------
103 60
104 60
105 60
106 60
107 60
SQL> connect hr/oracle
Connected.
SQL> SELECT /*+ FIRST_ROWS(25) */ employee_id, department_id
2 from employees
3 where department_id > 50;
EMPLOYEE_ID DEPARTMENT_ID
----------- -------------
103 60
104 60
105 60
106 60
107 60
Execution Plan for SELECT with FIRST_ROWS Hint |
### Execution Plan for SELECT with No Hint
SQL> connect hr/oracle
Connected.
SQL> SELECT employee_id, department_id
2 from employees
3 where department_id > 50;
EMPLOYEE_ID DEPARTMENT_ID
----------- -------------
100 90
101 90
102 90
103 60
104 60
- Stages of SQL Processing
SQL> connect hr/oracle
Connected.
SQL> SELECT employee_id, department_id
2 from employees
3 where department_id > 50;
EMPLOYEE_ID DEPARTMENT_ID
----------- -------------
100 90
101 90
102 90
103 60
104 60
Execution Plan for SELECT with No Hint |
SQL Execution Plans : http://www.dba-oracle.com/plsql/t_plsql_plans.htm
The following examples query tables within the SCOTT schema. If it is not already present, it can be created using the utlsampl.sql script found in the $ORACLE_HOME/rdbms/admin directory.
Before proceeding, the plan_table table must be created to hold the execution plan data.
plan_table
The execution plan information is stored in a table. For any of the following examples to work, this table must be created using the utlxplan.sql script. This script can be created in the current schema or in a shared schema. The following example shows how it is created in the SYS schema and made available to all users.
SQL> CONN sys/password AS SYSDBA
Connected
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql
Connected
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql
Table created.
SQL> GRANT ALL ON sys.plan_table TO public;
Grant succeeded.
SQL> CREATE PUBLIC SYNONYM plan_table FOR sys.plan_table;
Synonym created.
With the plan table present, execution plans using the autotrace feature of SQL*Plus can then be generated.
autotrace
The simplest way to get an execution plan is to use the autotrace feature of SQL*Plus. By switching on this feature, an execution plan is displayed for all suitable statement runes by SQL*Plus, as shown below.
SQL> SET AUTOTRACE ON
SQL> SELECT *
2 FROM emp e, dept d
3 WHERE e.deptno = d.deptno
4 AND e.ename = 'SMITH';
SQL> SELECT *
2 FROM emp e, dept d
3 WHERE e.deptno = d.deptno
4 AND e.ename = 'SMITH';
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO DEPTNO DNAME LOC
---------- ---------- -------------- -------------
7369 SMITH CLERK 7902 17-DEC-80 800
20 20 RESEARCH DALLAS
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO DEPTNO DNAME LOC
---------- ---------- -------------- -------------
7369 SMITH CLERK 7902 17-DEC-80 800
20 20 RESEARCH DALLAS
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 NESTED LOOPS
2 1 TABLE ACCESS (FULL) OF 'EMP'
3 1 TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' 4 3 INDEX (UNIQUE SCAN) OF 'PK_DEPT' (UNIQUE)
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 NESTED LOOPS
2 1 TABLE ACCESS (FULL) OF 'EMP'
3 1 TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' 4 3 INDEX (UNIQUE SCAN) OF 'PK_DEPT' (UNIQUE)
Statistics
----------------------------------------------------------
81 recursive calls
4 db block gets
27 consistent gets 0 physical reads
0 redo size
941 bytes sent via SQL*Net to client
425 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
----------------------------------------------------------
81 recursive calls
4 db block gets
27 consistent gets 0 physical reads
0 redo size
941 bytes sent via SQL*Net to client
425 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
This is a relatively easy way to get the execution plan, but it requires that the statement must run to completion. If the query is particularly inefficient or returns many rows, this may take considerable time. A better option is to run the explain plan statement manually, which is shown in the next section.
Explain Plan
The explain plan statement generates the execution plan for a query without executing the query itself, allowing the execution plan for poorly performing queries to be displayed without impacting the database. The following example shows how the explain plan statement is used to generate an execution plan.
SQL> EXPLAIN PLAN FOR
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
Explained.
If multiple people are accessing the same plan table, or a history of the execution plans is to be saved, the statement_id clause of the explain plan statement should be used. This associates a user specified identifier with each plan, which can be used when retrieving the data. The following example shows how the statement_id is set using the explain plan statement.
SQL> EXPLAIN PLAN SET STATEMENT_ID = 'TIM' FOR
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
Explained.
At this point the execution plan data is present in the plan_table, which can be queried using several methods to display the execution plan.
utlxpls.sql
Prior to Oracle 9i Release 2, the utlxpls.sql script or the utlxplp.sql script for parallel queries was used to query the plan_table and display execution plan. The example below shows the expected output from the script.
SQL> EXPLAIN PLAN FOR
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
Explained.
SQL> @$ORACLE_HOME/rdbms/admin/utlxpls.sql
Plan Table
-------------------------------------------------------------------------------
| Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
-------------------------------------------------------------------------------
| SELECT STATEMENT | | | | | | |
| NESTED LOOPS | | | | | | |
| TABLE ACCESS FULL |EMP | | | | | |
| TABLE ACCESS BY INDEX RO|DEPT | | | | | |
| INDEX UNIQUE SCAN |PK_DEPT | | | | | |
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
| Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
-------------------------------------------------------------------------------
| SELECT STATEMENT | | | | | | |
| NESTED LOOPS | | | | | | |
| TABLE ACCESS FULL |EMP | | | | | |
| TABLE ACCESS BY INDEX RO|DEPT | | | | | |
| INDEX UNIQUE SCAN |PK_DEPT | | | | | |
-------------------------------------------------------------------------------
8 rows selected.
SQL>
By default, the Oracle scripts do not accept a statement_id parameter, but they can be modified to create a personal script, like the explain.sql script shown below.
explain.sql
-- *****************************************************************
-- Parameters:
-- 1) Statement ID
-- *****************************************************************
-- Parameters:
-- 1) Statement ID
-- *****************************************************************
SET PAGESIZE 100
SET LINESIZE 200
SET VERIFY OFF
SET LINESIZE 200
SET VERIFY OFF
COLUMN plan FORMAT A50
COLUMN object_name FORMAT A30
COLUMN object_type FORMAT A15
COLUMN bytes FORMAT 9999999999
COLUMN cost FORMAT 9999999
COLUMN partition_start FORMAT A20
COLUMN partition_stop FORMAT A20
COLUMN object_name FORMAT A30
COLUMN object_type FORMAT A15
COLUMN bytes FORMAT 9999999999
COLUMN cost FORMAT 9999999
COLUMN partition_start FORMAT A20
COLUMN partition_stop FORMAT A20
SELECT LPAD(' ', 2 * (level - 1)) ||
DECODE (level,1,NULL,level-1 || '.' || pt.position || ' ') ||
INITCAP(pt.operation) ||
DECODE(pt.options,NULL,'',' (' || INITCAP(pt.options) || ')') plan,
pt.object_name,
pt.object_type,
pt.bytes,
pt.cost,
pt.partition_start,
pt.partition_stop
FROM plan_table pt
START WITH pt.id = 0
AND pt.statement_id = '&1'
CONNECT BY PRIOR pt.id = pt.parent_id
AND pt.statement_id = '&1';
DECODE (level,1,NULL,level-1 || '.' || pt.position || ' ') ||
INITCAP(pt.operation) ||
DECODE(pt.options,NULL,'',' (' || INITCAP(pt.options) || ')') plan,
pt.object_name,
pt.object_type,
pt.bytes,
pt.cost,
pt.partition_start,
pt.partition_stop
FROM plan_table pt
START WITH pt.id = 0
AND pt.statement_id = '&1'
CONNECT BY PRIOR pt.id = pt.parent_id
AND pt.statement_id = '&1';
The following example shows the output from the explain.sql script.
SQL> EXPLAIN PLAN SET STATEMENT_ID = 'TIM' FOR
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
2 SELECT *
3 FROM emp e, dept d
4 WHERE e.deptno = d.deptno
5 AND e.ename = 'SMITH';
Explained.
SQL> @explain.sql TIM
PLAN OBJECT_NAME OBJECT_TYPE BYTES COST PARTITION_START PARTITION_STOP
-------------------------------------------------- ------------------------------ --------------- ----------- ----Select Statement 57 4
-------------------------------------------------- ------------------------------ --------------- ----------- ----Select Statement 57 4
1.1 Nested Loops
57 4
2.1 Table Access (Full) EMP
TABLE 37 3
2.2 Table Access (By Index Rowid) DEPT
TABLE 20 1
3.1 Index (Unique Scan) PK_DEPT
INDEX (UNIQUE) 0
57 4
2.1 Table Access (Full) EMP
TABLE 37 3
2.2 Table Access (By Index Rowid) DEPT
TABLE 20 1
3.1 Index (Unique Scan) PK_DEPT
INDEX (UNIQUE) 0
5 rows selected.
The utlxpls.sql script is still present in later versions of Oracle, but it now displays the execution plan using the dbms_xplan package.- Stages of SQL Processing
depicts the general stages of SQL processing: parsing, optimization, row source generation, and execution. Depending on the statement, the database may omit some of these steps.
SQL Parsing
During the parse call, the database performs the following checks:
- Syntax Check - check each SQL statement for syntactic validity
- Semantic Check - check determines whether a statement is meaningful, for example, whether the objects and columns in the statement exist
- Shared Pool Check - determine whether it can skip resource-intensive steps of statement processing
Shared Pool Check
Shared Pool Check
|
SQL> conn sys/oracle as sysdba
Connected.
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql
Table created.
SQL> GRANT ALL ON sys.plan_table TO public;
Grant succeeded.
SQL> CREATE PUBLIC SYNONYM plan_table FOR sys.plan_table;
SQL> create role plustrace;
Role created.
SQL> grant select on v_$sesstat to plustrace;
Grant succeeded.
SQL> grant select on v_$statname to plustrace;
Grant succeeded.
SQL> grant select on v_$mystat to plustrace;
Grant succeeded.
SQL> grant plustrace to dba with admin option;
Grant succeeded.
SQL> grant plustrace to scott;
Grant succeeded.
SQL> conn scott/oracle
Connected.
SQL> set autotrace trace
SQL> select *
2 from emp e, dept d
3 where e.deptno = d.deptno
4 and e.ename = 'SMITH';
Execution Plan
----------------------------------------------------------
Plan hash value: 3625962092
----------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 58 | 4 (0)| 00:00:01 |
| 1 | NESTED LOOPS | | | | | |
| 2 | NESTED LOOPS | | 1 | 58 | 4 (0)| 00:00:01 |
|* 3 | TABLE ACCESS FULL | EMP | 1 | 38 | 3 (0)| 00:00:01 |
|* 4 | INDEX UNIQUE SCAN | PK_DEPT | 1 | | 0 (0)| 00:00:01 |
| 5 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)| 00:00:01 |
----------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
3 - filter("E"."ENAME"='SMITH')
4 - access("E"."DEPTNO"="D"."DEPTNO")
Statistics
----------------------------------------------------------
0 recursive calls
0 db block gets
9 consistent gets
0 physical reads
0 redo size
1123 bytes sent via SQL*Net to client
437 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
---------------------------------------------------------------------
SQL> conn sys/oracle as sysdbaConnected.
SQL> grant plustrace to hr;
Grant succeeded.
SQL> set autotrace trace
SQL> SELECT e.last_name, j.job_title, d.department_name
2 FROM hr.employees e, hr.departments d, hr.jobs j
3 WHERE e.department_id = d.department_id
4 AND e.job_id = j.job_id
5 AND e.last_name LIKE 'A%' ;
Execution Plan
----------------------------------------------------------
Plan hash value: 1513279928
--------------------------------------------------------------------------------
--------------
| Id | Operation | Name | Rows | Bytes | Cost (%CP
U)| Time |
--------------------------------------------------------------------------------
--------------
| 0 | SELECT STATEMENT | | 4 | 360 | 2 (
0)| 00:00:01 |
| 1 | NESTED LOOPS | | | |
| |
| 2 | NESTED LOOPS | | 4 | 360 | 2 (
0)| 00:00:01 |
| 3 | NESTED LOOPS | | 4 | 240 | 2 (
0)| 00:00:01 |
| 4 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 4 | 136 | 2 (
0)| 00:00:01 |
|* 5 | INDEX RANGE SCAN | EMP_NAME_IX | 4 | | 1 (
0)| 00:00:01 |
| 6 | TABLE ACCESS BY INDEX ROWID| JOBS | 1 | 26 | 0 (
0)| 00:00:01 |
|* 7 | INDEX UNIQUE SCAN | JOB_ID_PK | 1 | | 0 (
0)| 00:00:01 |
|* 8 | INDEX UNIQUE SCAN | DEPT_ID_PK | 1 | | 0 (
0)| 00:00:01 |
| 9 | TABLE ACCESS BY INDEX ROWID | DEPARTMENTS | 1 | 30 | 0 (
0)| 00:00:01 |
--------------------------------------------------------------------------------
--------------
Predicate Information (identified by operation id):
---------------------------------------------------
5 - access("E"."LAST_NAME" LIKE 'A%')
filter("E"."LAST_NAME" LIKE 'A%')
7 - access("E"."JOB_ID"="J"."JOB_ID")
8 - access("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
Note
-----
- dynamic sampling used for this statement (level=2)
Statistics
----------------------------------------------------------
50 recursive calls
0 db block gets
66 consistent gets
8 physical reads
0 redo size
771 bytes sent via SQL*Net to client
437 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
5 sorts (memory)
0 sorts (disk)
4 rows processed
How Oracle Database Processes DDL
- Issue a COMMIT before executing the CREATE TABLE statement
- Verify that user privileges are sufficient to create the table
- Determine which tablespace the table should reside in
- Ensure that the tablespace quota has not been exceeded
- Ensure that no object in the schema has the same name
- Insert rows that define the table into the data dictionary
- Issue a COMMIT if the DDL statement succeeded or a ROLLBACK if it did not
No comments:
Post a Comment