SlideShare a Scribd company logo
1 of 62
Download to read offline
Oracle OCP 考试系列培训
                之
         1Z0-007 Lesson9
                   www.OracleOnLinux.cn




9-1   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
9
      Using DDL Statements
   to Create and Manage Tables




Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Objectives


      After completing this lesson, you should be able to do
      the following:
       • Categorize the main database objects
       • Review the table structure
       • List the data types that are available for columns
       • Create a simple table
       • Understand how constraints are created at the
           time of table creation
       • Describe how schema objects work




9-3          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Database Objects


      Object            Description
      Table             Basic unit of storage; composed of rows
      View              Logically represents subsets of data from
                        one or more tables
      Sequence          Generates numeric values
      Index             Improves the performance of some
                        queries
      Synonym           Gives alternative names to objects




9-4      Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
在 Oracle 数据库中的表


      用户表:
      • 由用户创建和维护的一些表
      • 存放用户数据的信息
      数据字典表:
      • 由Oracle数据库创建和维护
      • 存放Oracle数据库自身的信息、数据库对象信息




9-5      Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
查询数据字典


      • 查看用户拥有的表:
       SELECT table_name
       FROM   user_tables ;

      • 查看用户拥有的所有对象:
       SELECT object_name
              object_name
       FROM   user_objects ;

      • 查看用户拥有的表、视图、 同义词和序列:

       SELECT *
       FROM   user_catalog ;




9-6       Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Naming Rules


      Table names and column names:
       • Must begin with a letter
       • Must be 1–30 characters long
                 1–
       • Must contain only A–Z, a–z, 0–9, _, $, and #
                            A– a– 0–
       • Must not duplicate the name of another object
          owned by the same user
       • Must not be an Oracle server reserved word




9-7         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
CREATE TABLE Statement


      •   You must have:
          – CREATE TABLE privilege
          – A storage area
      CREATE TABLE [schema.]table
                (column datatype [DEFAULT expr][, ...]);

      •   You specify:
          – Table name
          – Column name, column data type, and column size




                                                                      P79 Q132


9-8         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Referencing Another User ’s Tables
                              User’


      •   Tables belonging to other users are not in the
          user’s schema.
          user’
      •   You should use the owner ’s name as a prefix to
                             owner’
          those tables.




                     USERA                                 USERB
           SELECT *                             SELECT *
           FROM userB.employees;                FROM userA.employees;


9-9         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
DEFAULT Option


       •   Specify a default value for a column during an
           insert.
       ... hire_date DATE DEFAULT SYSDATE, ...

       •   Literal values, expressions, or SQL functions are
           legal values.
       •   Another column’s name or a pseudocolumn are
                     column’
           illegal values.
       •   The default data type must match the column data
           type.
       CREATE TABLE hire_dates
               (id          NUMBER(8),
                hire_date DATE DEFAULT SYSDATE);
       Table created.

9-10         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating Tables


       •   Create the table.
       CREATE TABLE dept
               (deptno                NUMBER(2),
                dname                 VARCHAR2(14),
                loc                   VARCHAR2(13),
                create_date           DATE DEFAULT SYSDATE);
       Table created.

       •   Confirm table creation.
       DESCRIBE dept




9-11          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Data Types

       Data Type           Description
       VARCHAR2( size ) Variable-length character data
       CHAR( size )        Fixed-length character data
       NUMBER( p,s)        Variable-length numeric data
       DATE                Date and time values
       LONG                Variable-length character data (up to 2 GB)
       CLOB                Character data (up to 4 GB)
       RAW and LONG        Raw binary data
       RAW
       BLOB                Binary data (up to 4 GB)
       BFILE               Binary data stored in an external file (up to 4 GB)
       ROWID               A base-64 number system representing the unique
                           address of a row in its table



9-12           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
9-13   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ROWID Format




9-14   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ROWID


       •   Get the rowid:
       SELECT ROWID FROM employees;

       •   Get the detail of rowid:
       select rowid,
       dbms_rowid.rowid_object(rowid) object_id,
       dbms_rowid.rowid_relative_fno(rowid) file_id,
       dbms_rowid.rowid_block_number(rowid) block_id ,
       dbms_rowid.rowid_row_number(rowid)   num ,
       rowidtochar(rowid) from employees;




9-15          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ROWID


       •   Get the detail of rowid:

       select rowid ,
       substr(rowid,1,6) "OBJECT",
       substr(rowid,7,3) "FILE",
       substr(rowid,10,6) "BLOCK",
       substr(rowid,16,3) "ROW"
       from TableName;




9-16          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ROWID Format




9-17   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ROWID Format

       Locating a Row Using ROWID
       •   Because a segment can only reside in one tablespace, by
       using the data object number, the Oracle server can determine
       the tablespace that contains a row.
       •   The relative file number within the tablespace is used to
       locate the file, the block number is used to locate the block
       containing the row, and the row number is used to locate the
       row directory entry for the row.
       •   The row directory entry can be used to locate the beginning
       of the row.Thus, ROWID can be used to locate any row within
       a database.


9-18           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Including Constraints


       •   Constraints enforce rules at the table level.
       •   Constraints prevent the deletion of a table if there
           are dependencies.
       •   The following constraint types are valid:
           –   NOT NULL
           –   UNIQUE
           –   PRIMARY KEY
           –   FOREIGN KEY
           –   CHECK



                                       P60 Q96, P71 Q113,P79 Q131

9-19           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Constraint Guidelines


       •   You can name a constraint, or the Oracle server
           generates a name by using the SYS_Cn format.
       •   Create a constraint at either of the following times:
           – At the same time as the table is created
           – After the table has been created
       •   Define a constraint at the column or table level.
       •   View a constraint in the data dictionary.




9-20          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Defining Constraints


       •   Syntax:
       CREATE TABLE [schema.]table
             (column datatype [DEFAULT expr]
             [column_constraint],
             ...
             [table_constraint][,...]);
                              ][,...]);
       •   Column-level constraint:
       column [CONSTRAINT constraint_name] constraint_type,

       •   Table-level constraint:
       column,...
         [CONSTRAINT constraint_name] constraint_type
         (column, ...),


9-21         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Defining Constraints


       •   Column-level constraint:
       CREATE TABLE employees(
         employee_id NUMBER(6)
           CONSTRAINT emp_emp_id_pk PRIMARY KEY,                                1
         first_name   VARCHAR2(20),
         ...);
       •   Table-level constraint:
       CREATE TABLE employees(
         employee_id NUMBER(6),
         first_name   VARCHAR2(20),
         ...
         job_id       VARCHAR2(10) NOT NULL,
                                                                                2
         CONSTRAINT emp_emp_id_pk
           PRIMARY KEY (EMPLOYEE_ID));


9-22         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
NOT NULL Constraint

       Defined at the column level only.
                              level
       Ensures that null values are not permitted for the
       column:




   …

       NOT NULL constraint                      NOT NULL         Absence of NOT NULL
       (No row can contain                      constraint       constraint
       a null value for                                          (Any row can contain
       this column.)                                             a null value for this
                                                                 column.)


9-23            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
UNIQUE Constraint

                                                           UNIQUE constraint
       EMPLOYEES




       …
                                      INSERT INTO

                                                                          Allowed
                                                                          Not allowed:
                                                                          already exists




9-24         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
UNIQUE Constraint


       Defined at either the table level or the column level:
                                                       level:

         CREATE TABLE employees(
             employee_id      NUMBER(6),
             last_name        VARCHAR2(25) NOT NULL,
             email            VARCHAR2(25),
             salary           NUMBER(8,2),
             commission_pct   NUMBER(2,2),
             hire_date        DATE NOT NULL,
         ...
             CONSTRAINT emp_email_uk UNIQUE(email));




9-25          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
PRIMARY KEY Constraint


       DEPARTMENTS
                           PRIMARY KEY




          …
  Not allowed                             INSERT INTO
  (null value)




       Not allowed
       (50 already exists)

9-26          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
FOREIGN KEY Constraint
             DEPARTMENTS



PRIMARY
  KEY
             …
 EMPLOYEES
                                                                              FOREIGN
                                                                              KEY




…                                                                            Not allowed
                                    INSERT INTO                              (9 does not
                                                                                exist)
                                                                              Allowed

 9-27     Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
FOREIGN KEY Constraint


       Defined at either the table level or the column level:

        CREATE TABLE employees(
            employee_id      NUMBER(6),
            last_name        VARCHAR2(25) NOT NULL,
            email            VARCHAR2(25),
            salary           NUMBER(8,2),
            commission_pct   NUMBER(2,2),
            hire_date        DATE NOT NULL,
        ...
            department_id    NUMBER(4),
            CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
              REFERENCES departments(department_id),
            CONSTRAINT emp_email_uk UNIQUE(email));


                                                         P75 Q124

9-28          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
FOREIGN KEY Constraint:
                         Keywords

       •   FOREIGN KEY: Defines the column in the child
           table at the table-constraint level
       •   REFERENCES: Identifies the table and column
           in the parent table
       •   ON DELETE CASCADE: Deletes the dependent
           rows in the child table when a row in the
           parent table is deleted
       •   ON DELETE SET NULL: Converts dependent
           foreign key values to null




9-29         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
CHECK Constraint


       •     Defines a condition that each row must satisfy
       •     CHECK constraints can be defined at the column
             level or table level
       •     The following expressions are not allowed:
              – References to CURRVAL, NEXTVAL, LEVEL, and
                ROWNUM pseudocolumns
              – Calls to SYSDATE, UID, USER, and USERENV
                functions
              – Queries that refer to other values in other rows
           ..., salary NUMBER(2)
                CONSTRAINT emp_salary_min
                       CHECK (salary > 0),...



9-30            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
CREATE TABLE : Example
                            TABLE:
       CREATE TABLE employees
           ( employee_id    NUMBER(6)
               CONSTRAINT     emp_employee_id                 PRIMARY KEY
           , first_name     VARCHAR2(20)
           , last_name      VARCHAR2(25)
               CONSTRAINT     emp_last_name_nn                NOT NULL
           , email          VARCHAR2(25)
               CONSTRAINT     emp_email_nn                    NOT NULL
               CONSTRAINT     emp_email_uk                    UNIQUE
           , phone_number   VARCHAR2(20)
           , hire_date      DATE
               CONSTRAINT     emp_hire_date_nn                NOT NULL
           , job_id         VARCHAR2(10)
               CONSTRAINT     emp_job_nn                      NOT NULL
           , salary         NUMBER(8,2)
               CONSTRAINT     emp_salary_ck                   CHECK (salary>0)
           , commission_pct NUMBER(2,2)
           , manager_id     NUMBER(6)
           , department_id NUMBER(4)
               CONSTRAINT     emp_dept_fk                     REFERENCES
                  departments (department_id));

9-31          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Violating Constraints


       UPDATE    employees
       SET       department_id = 55
       WHERE     department_id = 110;


       UPDATE employees
              *
       ERROR at line 1:
       ORA-02291: integrity constraint (HR.EMP_DEPT_FK)
       violated - parent key not found


       Department 55 does not exist.




9-32            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Violating Constraints


       You cannot delete a row that contains a primary key
       that is used as a foreign key in another table.
       DELETE FROM departments
       WHERE       department_id = 60;



       DELETE FROM departments
                   *
       ERROR at line 1:
       ORA-02292: integrity constraint (HR.EMP_DEPT_FK)
       violated - child record found




9-33          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a Table
                        by Using a Subquery

       •   Create a table and insert rows by combining the
           CREATE TABLE statement and the AS subquery
           option.
       CREATE TABLE table
                  [(column, column...)]
       AS subquery;

       •   Match the number of specified columns to the
           number of subquery columns.
       •   Define columns with column names and
           default values.



9-34         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Creating a Table
                        by Using a Subquery

       CREATE TABLE dept80
         AS
            SELECT employee_id, last_name,
                   salary*12 ANNSAL,
                   salary*   ANNSAL,
                   hire_date
            FROM   employees
            WHERE  department_id = 80;
       Table created.

       DESCRIBE dept80




9-35         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
The ALTER TABLE Statement


       Use the ALTER TABLE statement to:
        • Add a new column
        • Modify an existing column
        • Define a default value for the new column
        • Drop a column




9-36         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
The ALTER TABLE Statement


       Use the ALTER TABLE statement to add, modify, or
       drop columns.
        ALTER TABLE table
        ADD        (column datatype [DEFAULT expr]
                   [, column datatype ]...);

        ALTER TABLE table
        MODIFY     (column datatype [DEFAULT expr]
                   [, column datatype ]...);

        ALTER TABLE table
        DROP       (column);



9-37         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Adding a Column


       •       You use the ADD clause to add columns.
           ALTER TABLE dept80
           ADD        (job_id VARCHAR2(9));
           Table altered.

       •       The new column becomes the last column.




           …




9-38             Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Adding a Column


       •   You use the ADD clause to add columns.
       •   The new column becomes the last column.
       •   表初始有记录,增加字段后,没有指定默认值则该字段
           所有记录对应值为NULL,否则,对应记录为指定默认
           值
       •   表初始有记录,不能增加非空字段
       •   表初始无记录,才能增加非空字段




9-39         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Modifying a Column


       •     You can change a column’s data type, size, and
                              column’
             default value.
           ALTER TABLE dept80
           MODIFY      (last_name VARCHAR2(30));
           Table altered.

       •     A change to the default value affects only
             subsequent insertions to the table.
       •     改变字段的数据类型时,该字段初始值必须为NULL
       •     Varchar2(10)--->Char(6) --->Varchar2(4), 注意字段长
             Varchar2(10)--->Char(6)--->
                                     --->Varchar2(4),
             度问题[宽变窄,窄变宽]
                                                                   P71 Q112


9-40           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Dropping a Column


       Use the DROP COLUMN clause to drop columns you no
       longer need from the table.
        ALTER TABLE dept80
        DROP COLUMN job_id;
        Table altered.




9-41         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Dropping a Column


       Use the DROP COLUMN clause to drop columns you no
       longer need from the table.
        • 删除字段,不可逆操作(DDL)
        • 属于联合约束、组合索引的字段不可删,除非带有
           cascade键字




9-42         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
The SET UNUSED Option


       •     You use the SET UNUSED option to mark one or
             more columns as unused.
       •     You use the DROP UNUSED COLUMNS option to
             remove the columns that are marked as unused.
           ALTER   TABLE <table_name>
           SET     UNUSED(< column_name> );
           OR
           ALTER   TABLE <table_name>
           SET     UNUSED COLUMN <column_name>;

           ALTER TABLE < table_name>
           DROP UNUSED COLUMNS;



9-43           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
The SET UNUSED Option


       •   SET UNUSED 并非真正从目标表上删除数据,占存储
           空间
       •   SET UNUSED 的列不再可以使用,DESC无效
       •   SET UNUSED 的列可从 USER_UNUSED_COL_TABS视
                           USER_UNUSED_COL_TABS
           图查看相关信息


       ALTER TABLE dept80
       SET   UNUSED( last_name );
             UNUSED(last_name
                     last_name);

       ALTER TABLE dept80
       DROP UNUSED COLUMN S;
                   COLUMNS;



9-44         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Notes Only




9-45   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Adding a Constraint Syntax


       Use the ALTER TABLE statement to:
        • Add or drop a constraint, but not modify its
           structure
        • Enable or disable constraints
        • Add a NOT NULL constraint by using the MODIFY
           clause
        ALTER TABLE <table_name>
        ADD [CONSTRAINT < constraint_name> ]
        type (<column_name> );




9-46         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Adding a Constraint


       Add a FOREIGN KEY constraint to the EMP2 table
       indicating that a manager must already exist as a valid
       employee in the EMP2 table.
        ALTER TABLE emp2
        modify employee_id Primary Key;
        Table altered.

        ALTER TABLE emp2
        ADD CONSTRAINT emp_mgr_fk
          FOREIGN KEY(manager_id)
          REFERENCES emp2(employee_id);
        Table altered.



9-47          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
ON DELETE CASCADE


       Delete child rows when a parent key is deleted.

        ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fk
        FOREIGN KEY (Department_id)
        REFERENCES departments (dept_id)
                   departments(dept_id)
        ON DELETE CASCADE ;
                  CASCADE;
        Table altered.




9-48          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Dropping a Constraint


       •     Remove the manager constraint from the EMP2
             table.
           ALTER TABLE emp2
           DROP CONSTRAINT emp_mgr_fk;
           Table altered.

       •     Remove the PRIMARY KEY constraint on the
             DEPT2 table and drop the associated FOREIGN
             KEY constraint on the EMP2.DEPARTMENT_ID
             column.
           ALTER TABLE dept2
           DROP PRIMARY KEY CASCADE;
                             CASCADE;
           Table altered.

9-49           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Disabling Constraints


       •     Execute the DISABLE clause of the ALTER TABLE
             statement to deactivate an integrity constraint.
       •     Apply the CASCADE option to disable dependent
             integrity constraints.

           ALTER TABLE emp2
           DISABLE CONSTRAINT emp_dt_fk;
           Table altered.




9-50           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Enabling Constraints


       •     Activate an integrity constraint currently disabled
             in the table definition by using the ENABLE clause.
           ALTER TABLE       emp2
           ENABLE CONSTRAINT emp_dt_fk;
           Table altered.

       •     A UNIQUE index is automatically created if you
             enable a UNIQUE key or PRIMARY KEY constraint.




9-51           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Notes Only




9-52   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Cascading Constraints


       •   The CASCADE CONSTRAINTS clause is used along
           with the DROP COLUMN clause.
       •   The CASCADE CONSTRAINTS clause drops all
           referential integrity constraints that refer to the
           primary and unique keys defined on the dropped
           columns.
       •   The CASCADE CONSTRAINTS clause also drops all
           multicolumn constraints defined on the dropped
           columns.




9-53         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Cascading Constraints


       Example:
        ALTER TABLE emp2
        DROP COLUMN employee_id CASCADE CONSTRAINTS;
        Table altered.

        ALTER TABLE test1
        DROP (pk, fk, col1) CASCADE CONSTRAINTS;
        Table altered.




9-54         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
查看约束条件


       查询 USER_CONSTRAINTS 表可以看到用户的所有约束条
       件的名字和定义.
       SELECT constraint_name,constraint_type,
              search_condition
       FROM user_constraints
       WHERE table_name='EMPLOYEES'




       …


9-55         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
查看与约束相关的列



       在 USER_CONS_COLUMNS
         USER_CONS_COLUMNS视图中可以看到与约束相关的列
       的信息.
       SELECT       constraint_name, column_name
       FROM         user_cons_columns
       WHERE        table_name = 'EMPLOYEES';




       …
                                                                       P72 Q117


9-56            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Dropping a Table


       •   All data and structure in the table are deleted.
       •   Any pending transactions are committed.
       •   All indexes are dropped.
       •   All constraints are dropped.
       •   You cannot roll back the DROP TABLE statement.
       DROP TABLE dept80;
       Table dropped.




                                                                  P72 Q116



9-57         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
改变表的名字


       •     为了改变表、视图、序列或者同义词的名字,执行
             RENAME语句.
             RENAME
           RENAME dept TO detail_dept;
           Table renamed.

       •     必须是对象的拥有者.




9-58           Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
截断表


                TABLE语句:
       TRUNCATE TABLE
       •   从表中删掉所有的行
       •   释放被表使用的存储空间
        TRUNCATE TABLE detail_dept;
        Table truncated.

       TRUNCATE语句不可以回滚.
       TRUNCATE
       相应的, 也可以使用 DELETE 语句删掉所有的行.
       P56 Q89




9-59         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
为表增加注释


       可以使用 COMMENT 语句为表或者列增加注释信息.
        COMMENT ON TABLE employees
        IS 'Employee Information';
        Comment created.
       注释可以通过下列数据字典查看:
       • ALL_COL_COMMENTS
       • USER_COL_COMMENTS
       • ALL_TAB_COMMENTS
       • USER_TAB_COMMENTS




9-60       Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Summary


       In this lesson, you should have learned how to use the
       CREATE TABLE statement to create a table and include
       constraints.
        • Categorize the main database objects
        • Review the table structure
        • List the data types that are available for columns
        • Create a simple table
        • Understand how constraints are created at the
            time of table creation
        • Describe how schema objects work



9-61          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 9: Overview


       This practice covers the following topics:
        • Creating new tables
        • Creating a new table by using the CREATE TABLE
           AS syntax
        • Verifying that tables exist
        • Dropping tables




9-62         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.

More Related Content

What's hot

Homework help on oracle
Homework help on oracleHomework help on oracle
Homework help on oracleSteve Nash
 
Sql tutorial-Structured query language
Sql tutorial-Structured query languageSql tutorial-Structured query language
Sql tutorial-Structured query languageMayank Bansal
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data baseSalman Memon
 
Advanced sql injection
Advanced sql injectionAdvanced sql injection
Advanced sql injectionbadhanbd
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLRam Kedem
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?CPD INDIA
 
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQL
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQLAdding Value to HBase with IBM InfoSphere BigInsights and BigSQL
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQLPiotr Pruski
 
Lesson04 学会使用分组函数
Lesson04 学会使用分组函数Lesson04 学会使用分组函数
Lesson04 学会使用分组函数renguzi
 
Introduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQLIntroduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQLHarmony Kwawu
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextCarsten Czarski
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 

What's hot (19)

Homework help on oracle
Homework help on oracleHomework help on oracle
Homework help on oracle
 
Sql tutorial-Structured query language
Sql tutorial-Structured query languageSql tutorial-Structured query language
Sql tutorial-Structured query language
 
Les02
Les02Les02
Les02
 
Controlling User Access -Data base
Controlling User Access -Data baseControlling User Access -Data base
Controlling User Access -Data base
 
Wizard of ORDS
Wizard of ORDSWizard of ORDS
Wizard of ORDS
 
wee
weewee
wee
 
MySQL lecture
MySQL lectureMySQL lecture
MySQL lecture
 
Advanced sql injection
Advanced sql injectionAdvanced sql injection
Advanced sql injection
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?
 
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQL
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQLAdding Value to HBase with IBM InfoSphere BigInsights and BigSQL
Adding Value to HBase with IBM InfoSphere BigInsights and BigSQL
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
treeview
treeviewtreeview
treeview
 
Lesson04 学会使用分组函数
Lesson04 学会使用分组函数Lesson04 学会使用分组函数
Lesson04 学会使用分组函数
 
Introduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQLIntroduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQL
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 

Viewers also liked

Lesson08
Lesson08Lesson08
Lesson08renguzi
 
Lesson07
Lesson07Lesson07
Lesson07renguzi
 
Lesson06 使用子查询
Lesson06 使用子查询Lesson06 使用子查询
Lesson06 使用子查询renguzi
 
Lesson10
Lesson10Lesson10
Lesson10renguzi
 
Lesson03 学会使用单行函数
Lesson03 学会使用单行函数Lesson03 学会使用单行函数
Lesson03 学会使用单行函数renguzi
 
Lesson05 从多表中查询数据
Lesson05 从多表中查询数据Lesson05 从多表中查询数据
Lesson05 从多表中查询数据renguzi
 

Viewers also liked (6)

Lesson08
Lesson08Lesson08
Lesson08
 
Lesson07
Lesson07Lesson07
Lesson07
 
Lesson06 使用子查询
Lesson06 使用子查询Lesson06 使用子查询
Lesson06 使用子查询
 
Lesson10
Lesson10Lesson10
Lesson10
 
Lesson03 学会使用单行函数
Lesson03 学会使用单行函数Lesson03 学会使用单行函数
Lesson03 学会使用单行函数
 
Lesson05 从多表中查询数据
Lesson05 从多表中查询数据Lesson05 从多表中查询数据
Lesson05 从多表中查询数据
 

Similar to Oracle OCP 1Z0-007 Lesson9 Table and Constraint Creation

Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.pptAhmadUsman79
 
Less07 schema
Less07 schemaLess07 schema
Less07 schemaImran Ali
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle Abrar ali
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
Less08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxLess08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxMurtazaMughal13
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systemsSHAKIR325211
 
DDL. data defination language for creating database
DDL. data defination language for creating databaseDDL. data defination language for creating database
DDL. data defination language for creating databaseSHAKIR325211
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句renguzi
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slidesenosislearningcom
 

Similar to Oracle OCP 1Z0-007 Lesson9 Table and Constraint Creation (20)

Les10.ppt
Les10.pptLes10.ppt
Les10.ppt
 
Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.ppt
 
Les09
Les09Les09
Les09
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle
 
War of the Indices- SQL vs. Oracle
War of the Indices-  SQL vs. OracleWar of the Indices-  SQL vs. Oracle
War of the Indices- SQL vs. Oracle
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Intro
IntroIntro
Intro
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
 
Less08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxLess08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptx
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
 
Database Objects
Database ObjectsDatabase Objects
Database Objects
 
Less07 storage
Less07 storageLess07 storage
Less07 storage
 
Les01
Les01Les01
Les01
 
DDL. data defination language for creating database
DDL. data defination language for creating databaseDDL. data defination language for creating database
DDL. data defination language for creating database
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
 
SQL 3.pptx
SQL 3.pptxSQL 3.pptx
SQL 3.pptx
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slides
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Oracle OCP 1Z0-007 Lesson9 Table and Constraint Creation

  • 1. Oracle OCP 考试系列培训 之 1Z0-007 Lesson9 www.OracleOnLinux.cn 9-1 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 2. 9 Using DDL Statements to Create and Manage Tables Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 3. Objectives After completing this lesson, you should be able to do the following: • Categorize the main database objects • Review the table structure • List the data types that are available for columns • Create a simple table • Understand how constraints are created at the time of table creation • Describe how schema objects work 9-3 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 4. Database Objects Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries Synonym Gives alternative names to objects 9-4 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 5. 在 Oracle 数据库中的表 用户表: • 由用户创建和维护的一些表 • 存放用户数据的信息 数据字典表: • 由Oracle数据库创建和维护 • 存放Oracle数据库自身的信息、数据库对象信息 9-5 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 6. 查询数据字典 • 查看用户拥有的表: SELECT table_name FROM user_tables ; • 查看用户拥有的所有对象: SELECT object_name object_name FROM user_objects ; • 查看用户拥有的表、视图、 同义词和序列: SELECT * FROM user_catalog ; 9-6 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 7. Naming Rules Table names and column names: • Must begin with a letter • Must be 1–30 characters long 1– • Must contain only A–Z, a–z, 0–9, _, $, and # A– a– 0– • Must not duplicate the name of another object owned by the same user • Must not be an Oracle server reserved word 9-7 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 8. CREATE TABLE Statement • You must have: – CREATE TABLE privilege – A storage area CREATE TABLE [schema.]table (column datatype [DEFAULT expr][, ...]); • You specify: – Table name – Column name, column data type, and column size P79 Q132 9-8 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 9. Referencing Another User ’s Tables User’ • Tables belonging to other users are not in the user’s schema. user’ • You should use the owner ’s name as a prefix to owner’ those tables. USERA USERB SELECT * SELECT * FROM userB.employees; FROM userA.employees; 9-9 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 10. DEFAULT Option • Specify a default value for a column during an insert. ... hire_date DATE DEFAULT SYSDATE, ... • Literal values, expressions, or SQL functions are legal values. • Another column’s name or a pseudocolumn are column’ illegal values. • The default data type must match the column data type. CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT SYSDATE); Table created. 9-10 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 11. Creating Tables • Create the table. CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE); Table created. • Confirm table creation. DESCRIBE dept 9-11 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 12. Data Types Data Type Description VARCHAR2( size ) Variable-length character data CHAR( size ) Fixed-length character data NUMBER( p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data (up to 2 GB) CLOB Character data (up to 4 GB) RAW and LONG Raw binary data RAW BLOB Binary data (up to 4 GB) BFILE Binary data stored in an external file (up to 4 GB) ROWID A base-64 number system representing the unique address of a row in its table 9-12 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 13. 9-13 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 14. ROWID Format 9-14 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 15. ROWID • Get the rowid: SELECT ROWID FROM employees; • Get the detail of rowid: select rowid, dbms_rowid.rowid_object(rowid) object_id, dbms_rowid.rowid_relative_fno(rowid) file_id, dbms_rowid.rowid_block_number(rowid) block_id , dbms_rowid.rowid_row_number(rowid) num , rowidtochar(rowid) from employees; 9-15 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 16. ROWID • Get the detail of rowid: select rowid , substr(rowid,1,6) "OBJECT", substr(rowid,7,3) "FILE", substr(rowid,10,6) "BLOCK", substr(rowid,16,3) "ROW" from TableName; 9-16 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 17. ROWID Format 9-17 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 18. ROWID Format Locating a Row Using ROWID • Because a segment can only reside in one tablespace, by using the data object number, the Oracle server can determine the tablespace that contains a row. • The relative file number within the tablespace is used to locate the file, the block number is used to locate the block containing the row, and the row number is used to locate the row directory entry for the row. • The row directory entry can be used to locate the beginning of the row.Thus, ROWID can be used to locate any row within a database. 9-18 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 19. Including Constraints • Constraints enforce rules at the table level. • Constraints prevent the deletion of a table if there are dependencies. • The following constraint types are valid: – NOT NULL – UNIQUE – PRIMARY KEY – FOREIGN KEY – CHECK P60 Q96, P71 Q113,P79 Q131 9-19 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 20. Constraint Guidelines • You can name a constraint, or the Oracle server generates a name by using the SYS_Cn format. • Create a constraint at either of the following times: – At the same time as the table is created – After the table has been created • Define a constraint at the column or table level. • View a constraint in the data dictionary. 9-20 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 21. Defining Constraints • Syntax: CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); ][,...]); • Column-level constraint: column [CONSTRAINT constraint_name] constraint_type, • Table-level constraint: column,... [CONSTRAINT constraint_name] constraint_type (column, ...), 9-21 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 22. Defining Constraints • Column-level constraint: CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, 1 first_name VARCHAR2(20), ...); • Table-level constraint: CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, 2 CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID)); 9-22 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 23. NOT NULL Constraint Defined at the column level only. level Ensures that null values are not permitted for the column: … NOT NULL constraint NOT NULL Absence of NOT NULL (No row can contain constraint constraint a null value for (Any row can contain this column.) a null value for this column.) 9-23 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 24. UNIQUE Constraint UNIQUE constraint EMPLOYEES … INSERT INTO Allowed Not allowed: already exists 9-24 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 25. UNIQUE Constraint Defined at either the table level or the column level: level: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... CONSTRAINT emp_email_uk UNIQUE(email)); 9-25 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 26. PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY … Not allowed INSERT INTO (null value) Not allowed (50 already exists) 9-26 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 27. FOREIGN KEY Constraint DEPARTMENTS PRIMARY KEY … EMPLOYEES FOREIGN KEY … Not allowed INSERT INTO (9 does not exist) Allowed 9-27 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 28. FOREIGN KEY Constraint Defined at either the table level or the column level: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email)); P75 Q124 9-28 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 29. FOREIGN KEY Constraint: Keywords • FOREIGN KEY: Defines the column in the child table at the table-constraint level • REFERENCES: Identifies the table and column in the parent table • ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted • ON DELETE SET NULL: Converts dependent foreign key values to null 9-29 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 30. CHECK Constraint • Defines a condition that each row must satisfy • CHECK constraints can be defined at the column level or table level • The following expressions are not allowed: – References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns – Calls to SYSDATE, UID, USER, and USERENV functions – Queries that refer to other values in other rows ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),... 9-30 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 31. CREATE TABLE : Example TABLE: CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id)); 9-31 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 32. Violating Constraints UPDATE employees SET department_id = 55 WHERE department_id = 110; UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found Department 55 does not exist. 9-32 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 33. Violating Constraints You cannot delete a row that contains a primary key that is used as a foreign key in another table. DELETE FROM departments WHERE department_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found 9-33 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 34. Creating a Table by Using a Subquery • Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option. CREATE TABLE table [(column, column...)] AS subquery; • Match the number of specified columns to the number of subquery columns. • Define columns with column names and default values. 9-34 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 35. Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, salary* ANNSAL, hire_date FROM employees WHERE department_id = 80; Table created. DESCRIBE dept80 9-35 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 36. The ALTER TABLE Statement Use the ALTER TABLE statement to: • Add a new column • Modify an existing column • Define a default value for the new column • Drop a column 9-36 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 37. The ALTER TABLE Statement Use the ALTER TABLE statement to add, modify, or drop columns. ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype ]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype ]...); ALTER TABLE table DROP (column); 9-37 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 38. Adding a Column • You use the ADD clause to add columns. ALTER TABLE dept80 ADD (job_id VARCHAR2(9)); Table altered. • The new column becomes the last column. … 9-38 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 39. Adding a Column • You use the ADD clause to add columns. • The new column becomes the last column. • 表初始有记录,增加字段后,没有指定默认值则该字段 所有记录对应值为NULL,否则,对应记录为指定默认 值 • 表初始有记录,不能增加非空字段 • 表初始无记录,才能增加非空字段 9-39 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 40. Modifying a Column • You can change a column’s data type, size, and column’ default value. ALTER TABLE dept80 MODIFY (last_name VARCHAR2(30)); Table altered. • A change to the default value affects only subsequent insertions to the table. • 改变字段的数据类型时,该字段初始值必须为NULL • Varchar2(10)--->Char(6) --->Varchar2(4), 注意字段长 Varchar2(10)--->Char(6)---> --->Varchar2(4), 度问题[宽变窄,窄变宽] P71 Q112 9-40 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 41. Dropping a Column Use the DROP COLUMN clause to drop columns you no longer need from the table. ALTER TABLE dept80 DROP COLUMN job_id; Table altered. 9-41 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 42. Dropping a Column Use the DROP COLUMN clause to drop columns you no longer need from the table. • 删除字段,不可逆操作(DDL) • 属于联合约束、组合索引的字段不可删,除非带有 cascade键字 9-42 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 43. The SET UNUSED Option • You use the SET UNUSED option to mark one or more columns as unused. • You use the DROP UNUSED COLUMNS option to remove the columns that are marked as unused. ALTER TABLE <table_name> SET UNUSED(< column_name> ); OR ALTER TABLE <table_name> SET UNUSED COLUMN <column_name>; ALTER TABLE < table_name> DROP UNUSED COLUMNS; 9-43 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 44. The SET UNUSED Option • SET UNUSED 并非真正从目标表上删除数据,占存储 空间 • SET UNUSED 的列不再可以使用,DESC无效 • SET UNUSED 的列可从 USER_UNUSED_COL_TABS视 USER_UNUSED_COL_TABS 图查看相关信息 ALTER TABLE dept80 SET UNUSED( last_name ); UNUSED(last_name last_name); ALTER TABLE dept80 DROP UNUSED COLUMN S; COLUMNS; 9-44 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 45. Notes Only 9-45 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 46. Adding a Constraint Syntax Use the ALTER TABLE statement to: • Add or drop a constraint, but not modify its structure • Enable or disable constraints • Add a NOT NULL constraint by using the MODIFY clause ALTER TABLE <table_name> ADD [CONSTRAINT < constraint_name> ] type (<column_name> ); 9-46 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 47. Adding a Constraint Add a FOREIGN KEY constraint to the EMP2 table indicating that a manager must already exist as a valid employee in the EMP2 table. ALTER TABLE emp2 modify employee_id Primary Key; Table altered. ALTER TABLE emp2 ADD CONSTRAINT emp_mgr_fk FOREIGN KEY(manager_id) REFERENCES emp2(employee_id); Table altered. 9-47 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 48. ON DELETE CASCADE Delete child rows when a parent key is deleted. ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fk FOREIGN KEY (Department_id) REFERENCES departments (dept_id) departments(dept_id) ON DELETE CASCADE ; CASCADE; Table altered. 9-48 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 49. Dropping a Constraint • Remove the manager constraint from the EMP2 table. ALTER TABLE emp2 DROP CONSTRAINT emp_mgr_fk; Table altered. • Remove the PRIMARY KEY constraint on the DEPT2 table and drop the associated FOREIGN KEY constraint on the EMP2.DEPARTMENT_ID column. ALTER TABLE dept2 DROP PRIMARY KEY CASCADE; CASCADE; Table altered. 9-49 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 50. Disabling Constraints • Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. • Apply the CASCADE option to disable dependent integrity constraints. ALTER TABLE emp2 DISABLE CONSTRAINT emp_dt_fk; Table altered. 9-50 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 51. Enabling Constraints • Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. ALTER TABLE emp2 ENABLE CONSTRAINT emp_dt_fk; Table altered. • A UNIQUE index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint. 9-51 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 52. Notes Only 9-52 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 53. Cascading Constraints • The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN clause. • The CASCADE CONSTRAINTS clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns. • The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on the dropped columns. 9-53 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 54. Cascading Constraints Example: ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS; Table altered. ALTER TABLE test1 DROP (pk, fk, col1) CASCADE CONSTRAINTS; Table altered. 9-54 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 55. 查看约束条件 查询 USER_CONSTRAINTS 表可以看到用户的所有约束条 件的名字和定义. SELECT constraint_name,constraint_type, search_condition FROM user_constraints WHERE table_name='EMPLOYEES' … 9-55 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 56. 查看与约束相关的列 在 USER_CONS_COLUMNS USER_CONS_COLUMNS视图中可以看到与约束相关的列 的信息. SELECT constraint_name, column_name FROM user_cons_columns WHERE table_name = 'EMPLOYEES'; … P72 Q117 9-56 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 57. Dropping a Table • All data and structure in the table are deleted. • Any pending transactions are committed. • All indexes are dropped. • All constraints are dropped. • You cannot roll back the DROP TABLE statement. DROP TABLE dept80; Table dropped. P72 Q116 9-57 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 58. 改变表的名字 • 为了改变表、视图、序列或者同义词的名字,执行 RENAME语句. RENAME RENAME dept TO detail_dept; Table renamed. • 必须是对象的拥有者. 9-58 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 59. 截断表 TABLE语句: TRUNCATE TABLE • 从表中删掉所有的行 • 释放被表使用的存储空间 TRUNCATE TABLE detail_dept; Table truncated. TRUNCATE语句不可以回滚. TRUNCATE 相应的, 也可以使用 DELETE 语句删掉所有的行. P56 Q89 9-59 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 60. 为表增加注释 可以使用 COMMENT 语句为表或者列增加注释信息. COMMENT ON TABLE employees IS 'Employee Information'; Comment created. 注释可以通过下列数据字典查看: • ALL_COL_COMMENTS • USER_COL_COMMENTS • ALL_TAB_COMMENTS • USER_TAB_COMMENTS 9-60 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 61. Summary In this lesson, you should have learned how to use the CREATE TABLE statement to create a table and include constraints. • Categorize the main database objects • Review the table structure • List the data types that are available for columns • Create a simple table • Understand how constraints are created at the time of table creation • Describe how schema objects work 9-61 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 62. Practice 9: Overview This practice covers the following topics: • Creating new tables • Creating a new table by using the CREATE TABLE AS syntax • Verifying that tables exist • Dropping tables 9-62 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.