creating tables
DESCRIPTION
Creating Tables. Objectives. Create a table containing integrity constraints. Identify table naming conventions. Describe the datatypes that can be used when specifying column definitions. Recognize the indexes that are created automatically by constraints. - PowerPoint PPT PresentationTRANSCRIPT
9-9-11
Creating TablesCreating Tables
9-9-22
ObjectivesObjectives
• Create a table containing integrity constraints.• Identify table naming conventions.• Describe the datatypes that can be used when
specifying column definitions.• Recognize the indexes that are created
automatically by constraints.• Create a table by populating it with rows from
another table.
9-9-33
Database ObjectsDatabase Objects
• An Oracle database can contain multiple data structures.– Table Basic unit of data storage– View Subset of data from one or
more tables
– Sequence Generates primary key values
– Index Improves the performance of some queries
– Synonym Gives alternative names to objects
• Define the structures in the database design.
9-9-44
Naming RulesNaming Rules
• Must begin with a letter• Can be 1–30 characters long• Must contain only A–Z, a–z, 0–9, _, $, and #• Must not duplicate the name of another object
owned by the same user• Must not be an Oracle Server reserved word
9-9-55
Creating Tables: SyntaxCreating Tables: Syntax
You specify:• Table name• Column name, column datatype and size• Schema – same as the owners name• DEFAULT expr – specify the default value if the
value is omitted in the INSERT statement
CREATE TABLE [CREATE TABLE [schemaschema.].]tabletable((column datatypecolumn datatype [DEFAULT [DEFAULT exprexpr]] [, …]);[, …]);
9-9-66
Referencing Another User's TablesReferencing Another User's Tables
• Tables belonging to other users are not in the user's schema.
• You should use the owner's name as a prefix to the table.
• A schema is a collection of objects including tables, views, sequences, synonyms …
9-9-77
The DEFAULT OptionThe DEFAULT Option
• Specify a default value for a column during an insert.
• Legal values are literal value, expression, or SQL Legal values are literal value, expression, or SQL function such as SYSDATE or USER.function such as SYSDATE or USER.
• Illegal values are another column name or a Illegal values are another column name or a pseudocolumn such as NEXTVAL or CURRVAL pseudocolumn such as NEXTVAL or CURRVAL of a sequence.of a sequence.
• The default value datatype must match the The default value datatype must match the column datatype.column datatype.
... hiredate DATE DEFAULT SYSDATE,...... hiredate DATE DEFAULT SYSDATE,...
9-9-88
Table Instance Chart: DEPTTable Instance Chart: DEPT
Column name DEPTNO DNAME LOCKey type PKNN/UK NN, U NNFK tableFK columnDatatype NUMBER VARCHAR2 VARCHAR2Length 2 14 13Sample data 10 Finance
20 Sales30 Sales40 Sales
9-9-99
Create a Table from a Table Instance Create a Table from a Table Instance ChartChart
1. Create a script file. Add CREATE TABLE table_name syntax.
2. Map the column names, datatypes, and lengths.3. Map the NOT NULL constraints, except PRIMARY
KEY, as column level constraints.4. Map the PRIMARY KEY constraint.5. Map the UNIQUE, CHECK, and FOREIGN KEY
constraints.6. Save and execute the script file.
9-9-1010
DatatypesDatatypesDatatype
VARCHAR2(size)
CHAR(size)
NUMBER
NUMBER(p,s)
DATE
LONG
RAW and LONG RAW
Description
Variable length character values
Fixed length character values
Floating point numbers
Number values with precision and scale
Date and time values
Variable length character values up to 2 GB
Variable length character for binary data
9-9-1111
Creating a TableCreating a Table
• Create a table.
• Confirm the table created using DESCRIBE command.
CREATE TABLE CREATE TABLE dept2dept2 (deptno number(2),(deptno number(2), dname varchar2(14),dname varchar2(14), loc varchar2(13));loc varchar2(13));Table created.Table created.
9-9-1212
Creating a Table by Using a Subquery: Creating a Table by Using a Subquery: SyntaxSyntax
• Create a table and insert rows by combining the CREATE TABLE command and AS subquery option.
• Match number of specified columns to number of subquery columns.
• Define columns with column names, and default values.
CREATE TABLE CREATE TABLE tabletable [[columncolumn(, (, columncolumn...)]...)] AS AS subquerysubquery;;
9-9-1313
Creating a Table by Using a Subquery: Creating a Table by Using a Subquery: ExampleExample
• Create a table containing all employees in department number 10 in the EMP table.
• Only the NOT NULL constraint will be copied.
CREATE TABLE CREATE TABLE emp_10emp_10AS AS SELECTSELECT empno, ename, sal*12 ANNSAL, empno, ename, sal*12 ANNSAL,
hiredatehiredateFROMFROM empempWHEREWHERE deptno = 10; deptno = 10; Table created.Table created.
9-9-1414
Confirming Table CreationConfirming Table Creation
Confirm the existence of a database table along with its column names by using the SQL*Plus DESCRIBE command.
SQL> DESCRIBE emp_10SQL> DESCRIBE emp_10Name Null? TypeName Null? Type------------------------- -------- --------------------------------- -------- --------EMPNO NOT NULL EMPNO NOT NULL NUMBER(4)NUMBER(4)ENAME ENAME VARCHAR2(10)VARCHAR2(10)ANNSAL ANNSAL NUMBERNUMBERHIREDATE HIREDATE DATEDATE
9-9-1515
ConstraintsConstraints
• Enforce rules at the table level.• Prevent the deletion of a table if there are
dependencies.• The following constraint types are valid in Oracle:– NOT NULL– UNIQUE– PRIMARY KEY– FOREIGN KEY– CHECK – specifies a condition that must be
true.
9-9-1616
Constraint GuidelinesConstraint Guidelines
• Name a constraint or the Server can generate a name by using the SYS_Cn format.
• Create a constraint– At the same time as the table is created.– After the table has been created.
• Define a constraint at the column or table level.
9-9-1717
Constraint: SyntaxConstraint: Syntax
• Column-constraint level
• Table-constraint level
columncolumn [CONSTRAINT [CONSTRAINT constraint_nameconstraint_name] ] constraint_typeconstraint_type,,
column,...column,... [CONSTRAINT constraint_name] constraint_type[CONSTRAINT constraint_name] constraint_type (column, ...),(column, ...),
9-9-1818
Define Constraints: ExampleDefine Constraints: Example
SQL> CREATE TABLE emp(empno number(4),ename varchar2(10),……deptno number(7,2) NOT
NULL,CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));
9-9-1919
The NOT NULL ConstraintThe NOT NULL Constraint
• Ensures that null values are not permitted for the column
• Is defined at the column-constraint levelExample
CREATE TABLECREATE TABLE friend (...friend (... phonephone VARCHAR2(15) NOT NULL,...VARCHAR2(15) NOT NULL,... last_namelast_name VARCHAR2(25) VARCHAR2(25) CONSTRAINT friend_last_name_nn CONSTRAINT friend_last_name_nn
NOT NULL,...);NOT NULL,...);
9-9-2020
The UNIQUE ConstraintThe UNIQUE Constraint
• Designates a column or combination of columns so that no two rows in the table can have the same value for this key
• Allows null values if the UNIQUE key is based on a single column
• Is defined at either the table or column-constraint level
• Automatically creates a UNIQUE index
... phone... phone VARCHAR2(10)VARCHAR2(10) CONSTRAINT emp_phone_uk UNIQUE,...CONSTRAINT emp_phone_uk UNIQUE,...
9-9-2121
The PRIMARY KEY ConstraintThe PRIMARY KEY Constraint
• Creates a primary key for the table; only one primary key is allowed for each table
• Enforces uniqueness of columns• Does not allow null values in any part of the
primary key• Is defined at either the table or column constraint
level• Automatically creates a UNIQUE index
... id... id NUMBER(7)NUMBER(7) CONSTRAINT emp_id_pk PRIMARY KEY,...CONSTRAINT emp_id_pk PRIMARY KEY,...
9-9-2222
The FOREIGN KEY ConstraintThe FOREIGN KEY Constraint
• Designates a column or combination of columns as a foreign key
• Establishes a relationship between the primary or unique key in the same table or between tables
• Is defined at either the table or column constraint level
• Must match an existing value in the parent table or be NULL
... deptno... deptno NUMBER(2)NUMBER(2) CONSTRAINT emp_deptno_fk CONSTRAINT emp_deptno_fk REFERENCES dept(deptno),...REFERENCES dept(deptno),...
9-9-2323
FOREIGN KEY Constraint KeywordsFOREIGN 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– Allows deletion in the parent table and deletion
of the dependent rows in the child table• ON DELETE SET NULL
9-9-2424
The CHECK ConstraintThe CHECK Constraint
• Defines a condition that each row must satisfy• Expressions that are not allowed:– References to pseudocolumns CURRVAL,
NEXTVAL, LEVEL, or ROWNUM– Calls to SYSDATE, UID, USER, or USERENV
functions– Queries that refer to other values in other rows
• Is defined at either the table-constraint level or the column-constraint level
... deptno... deptno NUMBER(2)NUMBER(2) CONSTRAINT emp_deptno_ck CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...CHECK (DEPTNO BETWEEN 10 AND 99),...
9-9-2525
Create Table: ExampleCreate Table: Example
SQL> CREATE TABLE s_dept 2 (id NUMBER(7) 3 CONSTRAINT s_dept_id_pk PRIMARY KEY, 4 name VARCHAR2(25) 5 CONSTRAINT s_dept_name_nn NOT NULL, 6 region_id NUMBER(7) 7 CONSTRAINT s_dept_region_id_fk REFERENCES 8 s_region (id), 9 CONSTRAINT s_dept_name_region_id_uk UNIQUE 10 (name, region_id));
9-9-2626
Create Table: ExampleCreate Table: ExampleSQL> CREATE TABLE s_emp 2 (id NUMBER(7) 3 CONSTRAINT s_emp_id_pk PRIMARY KEY, 4 last_name VARCHAR2(25) 5 CONSTRAINT s_emp_last_name_nn NOT NULL, 6 first_name VARCHAR2(25), 7 userid VARCHAR2(8) 8 CONSTRAINT s_emp_userid_nn NOT NULL 9 CONSTRAINT s_emp_userid_uk UNIQUE, 10 start_date DATE DEFAULT SYSDATE, 11 comments VARCHAR2(25), 12 manager_id NUMBER(7), 13 title VARCHAR2(25), 14 dept_id NUMBER(7) 15 CONSTRAINT s_emp_dept_id_fk REFERENCES 16 s_dept (id), 17 salary NUMBER(11,2), 18 commission_pct NUMBER(4,2) 19 CONSTRAINT s_emp_commission_pct_ck CHECK 20 (commission_pct IN(10,12.5,15,17.5,20)));
9-9-2727
SummarySummary
• Build tables in a database by using the SQL CREATE TABLE command.
• Construct a table with the following features:– Table name– Column names, datatypes, and lengths– Integrity constraints
CREATE TABLE [CREATE TABLE [schemaschema.].]tabletable((column datatype column datatype [[column_constraintcolumn_constraint], ], ......
[[table_constrainttable_constraint]);]);
9-9-2828
SummarySummary• Constraint types– NOT NULL– UNIQUE– PRIMARY KEY– FOREIGN KEY– CHECK
• UNIQUE indexes – Are created automatically with PRIMARY KEY
and UNIQUE constraints.• SQL*Plus DESCRIBE command – Displays the structure of the table.
9-9-2929
Practice OverviewPractice Overview
• Creating new tables containing constraints• Verifying that the tables exist
9-9-3030
Practice 1Practice 1• Create DEPARTMENT table based on the following
table instance chart. Enter the syntax in a script file and execute the script file to create the table. Confirm the table created.
Column name ID NAMEKey type PKNN/UK NN, U NNFK tableFK columnDatatype NUMBER VARCHAR2Length 7 25
9-9-3131
Practice 2Practice 2
• Populate the DEPARTMENT table with data from DEPT table. Include only columns that you need.
9-9-3232
Practice 3Practice 3• Create EMPLOYEE table based on the following
table instance chart. Enter the syntax in a script file and execute the script file to create the table. Confirm the table created.
Column name EID ENAME DEPTIDKey type PKNN/UK NN, U NNFK table DEPARTMENTFK column IDDatatype NUMBER VARCHAR2 NUMBERLength 7 25 7
9-9-3333
Practice 4Practice 4
• Populate the EMPLOYEE table with data from EMP table. Include only columns that you need.