Download Create Table

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Create Table
Data Definition Language (DDL)
•
•
•
•
•
•
DDL statements are used to define the database structure or
schema. Some examples:
o CREATE - to create objects in the database
o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces
allocated for the records are removed
o COMMENT - add comments to the data dictionary
• o RENAME - rename an object
Data Manipulation Language
•
•
•
•
•
•
•
•
•
•
DML statements are used for managing data within schema
objects. Some examples:
o SELECT - retrieve data from the a database
o INSERT - insert data into a table
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records
remain
o MERGE - UPSERT operation (insert or update)
o CALL - call a PL/SQL or Java subprogram
o EXPLAIN PLAN - explain access path to data
o LOCK TABLE - control concurrency
(SQL)
Creating and Managing Tables
Objectives
• After completing this lesson, you should
be able to do the following:
– Describe the main database objects
– Create tables
– Describe the data types that can be used
when specifying column definition
– Alter table definitions
– Drop, rename, and truncate tables
Database Objects
Object
Description
Table
Basic unit of storage; composed of rows
and columns
View
Logically represents subsets 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
Naming Conventions
– 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/sql reserved
word
The CREATE TABLE Statement
– You must have :
• CREATE TABLE privilege
• A storage area
CREATE TABLE table_name
( column_name1 datatype(size) [Column Constraints],
column_name2 datatype(size) [Column Constraints],
…………
[Table Constriants]);
You specify:
• Table name
• Column name, column data type, and column size
• Size specifies the max. length of a column.
Data Types
Datatype
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
Creating Tables
SQL> CREATE TABLE dept
2
(deptno NUMBER(2),
3
dname VARCHAR2(14),
4
loc
VARCHAR2(13));
Table created.
• Confirm table creation.
SQL> DESCRIBE dept
Name
Null?
--------------------------- -------DEPTNO
DNAME
LOC
Type
--------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)
The DEFAULT Option
• To specify a default value for a column.
• The default data type must match the column data type.
... hire_date DATE DEFAULT SYSDATE, ...
... Status CHAR(1) DEFAULT ‘P’, ...
SQL> CREATE TABLE test
2
(id
NUMBER(2),
3
value NUMBER(2) DEFAULT 50,
4
name
VARCHAR2(13));
Table created.
Tables in the Oracle Database
– User Tables
• Collection of tables created and maintained by the
user
• Contain user information
– Data Dictionary
• Collection of tables created and maintained by the
Oracle/sql server
• Contain database information
Querying the Data Dictionary
– Describe tables owned by the user.
SQL> SELECT
2 FROM
*
user_tables;
• View distinct object types owned by the user.
SQL> SELECT
2 FROM
DISTINCT object_type
user_objects;
• View tables, views, synonyms, and sequences owned
by the user.
SQL> SELECT
2 FROM
*
user_catalog;
Including Constraints
– Constraints enforce data integrity rules.
– Constraint can be either at table level or column level.
– A constraint should be given a meaningful name (its optional though),
otherwise oracle server give every constraint a unique name in sys-cn
format.
– A constraint can be defined either at the time of table creation or after it.
– The constraints are stored in a data dictionary view called
USER_CONSTTAINTS.
– The following constraint types are valid in Oracle:
•
•
•
•
•
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
Including Constraints
– The following constraint types are valid in Oracle:
•
•
•
•
•
NOT NULL [Column Level]
UNIQUE [Column or Table Level]
PRIMARY KEY [Column or Table Level]
FOREIGN KEY [Column or Table Level]
CHECK [Column Level]
Defining Constraints
CREATE TABLE tablename
(column datatype [column_constraint],
...
[table_constraint][,...]);
CREATE TABLE emp(
empno NUMBER(4),
ename VARCHAR2(10),
...
deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));
Defining Constraints
– Column constraint level
column [CONSTRAINT constraint_name] constraint_type,
– Table constraint level
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
The NOT NULL Constraint
• Ensures that null values are not
permitted for the column
EMP
EMPNO ENAME
7839
7698
7782
7566
...
KING
BLAKE
CLARK
JONES
NOT NULL constraint
(no row can contain
a null value for
this column)
JOB
...
COMM
PRESIDENT
MANAGER
MANAGER
MANAGER
Absence of NOT NULL
constraint
(any row can contain
null for this column)
DEPTNO
10
30
10
20
NOT NULL constraint
The NOT NULL Constraint
• Defined at the column level
SQL> CREATE TABLE
2
empno
3
ename
4
job
5
mgr
6
hiredate
7
sal
8
comm
9
deptno
emp(
NUMBER(4),
VARCHAR2(10) NOT NULL,
VARCHAR2(9),
NUMBER(4),
DATE,
NUMBER(7,2),
NUMBER(7,2),
NUMBER(7,2) NOT NULL);
The UNIQUE Key Constraint
UNIQUE key constraint
DEPT
DEPTNO
-----10
20
30
40
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
Insert into
50 SALES
DETROIT
Not allowed
(DNAME-SALES already
exists)
60
BOSTON
Allowed
The UNIQUE Key Constraint
• Defined at either the table level or the
column level
SQL> CREATE TABLE
2
deptno
3
dname
4
loc
5
CONSTRAINT
dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE(dname));
The PRIMARY KEY Constraint
PRIMARY KEY
DEPT
DEPTNO
-----10
20
30
40
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
Insert into
20 MARKETING
FINANCE
DALLAS
NEW YORK
Not allowed (DEPTNO20 already exists)
Not allowed
(DEPTNO is null)
The PRIMARY KEY Constraint
• Defined at either the table level or the
column level, however if the PK is
composite, then it should be defined at
table level.
SQL> CREATE TABLE
2
deptno
3
dname
4
loc
5
CONSTRAINT
6
CONSTRAINT
dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE (dname),
dept_deptno_pk PRIMARY KEY(deptno));
The FOREIGN KEY Constraint
DEPT
PRIMARY
KEY
DEPTNO
-----10
20
...
DNAME
---------ACCOUNTING
RESEARCH
LOC
-------NEW YORK
DALLAS
EMP
EMPNO ENAME
7839 KING
7698 BLAKE
...
JOB
...
COMM
PRESIDENT
MANAGER
DEPTNO
10
30
Insert into
7571 FORD
7571 FORD
MANAGER
MANAGER
FOREIGN
KEY
...
...
200
200
9
20
Not allowed
(DEPTNO 9 does
not exist in the
DEPT table)
Allowed
The FOREIGN KEY Constraint
• Defined at either the table level or the
column level
SQL> CREATE TABLE emp(
2
empno
NUMBER(4),
3
ename
VARCHAR2(10) NOT NULL,
4
job
VARCHAR2(9),
5
mgr
NUMBER(4),
6
hiredate DATE,
7
sal
NUMBER(7,2),
8
comm
NUMBER(7,2),
9
deptno
NUMBER(7,2) NOT NULL,
10
CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11
REFERENCES dept (deptno));
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
it is optional clause and it Allows deletion in the
parent table and deletion of the dependent rows in
the child table
–ON DELETE SET NULL:
Converts dependent foreign key values to null
The CHECK Constraint
– Defines a condition that each row must satisfy
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...
Viewing Constraints
• Query the USER_CONSTRAINTS table to
view all constraint definitions and names.
SQL>
2
3
4
SELECT constraint_name, constraint_type,
search_condition
FROM
user_constraints
WHERE table_name = 'EMP';
CONSTRAINT_NAME
-----------------------SYS_C00674
SYS_C00675
EMP_EMPNO_PK
...
C
C
C
P
SEARCH_CONDITION
------------------------EMPNO IS NOT NULL
DEPTNO IS NOT NULL
Viewing the Columns Associated with Constraints
• View the columns associated with the constraint names
in the USER_CONS_COLUMNS view.
SQL> SELECT
2 FROM
3 WHERE
constraint_name, column_name
user_cons_columns
table_name = 'EMP';
CONSTRAINT_NAME
------------------------EMP_DEPTNO_FK
EMP_EMPNO_PK
EMP_MGR_FK
SYS_C00674
SYS_C00675
COLUMN_NAME
---------------------DEPTNO
EMPNO
MGR
EMPNO
DEPTNO
Creating a Table
by Using a Subquery
– Create a table and insert rows by combining the
CREATE TABLE statement and 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.
Creating a Table
by Using a Subquery
SQL> CREATE TABLE
dept30
2 AS
3
SELECT
empno, ename, sal*12 ANNSAL, hiredate
4
FROM
emp
5
WHERE
deptno = 30;
Table created.
SQL> DESCRIBE dept30
Name
Null?
---------------------------- -------EMPNO
NOT NULL
ENAME
ANNSAL
HIREDATE
Type
----NUMBER(4)
VARCHAR2(10)
NUMBER
DATE
The ALTER TABLE Statement
• Use the ALTER TABLE statement to:
– Add a new column
– Modify an existing column
– Drop a column.
– Add or Drop a Constraint.
– Disable
Enable a Constraint
ALTER
TABLEor
table
ADD
(column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE table
MODIFY
(column datatype [DEFAULT expr]
[, column datatype]...);
Adding a Column
DEPT30
EMPNO
-----7698
7654
7499
7844
...
New column
ENAME
ANNSAL
---------- -------BLAKE
34200
MARTIN
15000
ALLEN
19200
TURNER
18000
HIREDATE
JOB
“…add a new
column into
DEPT30
table…”
01-MAY-81
28-SEP-81
20-FEB-81
08-SEP-81
DEPT30
EMPNO
-----7698
7654
7499
7844
...
ENAME
ANNSAL
---------- -------BLAKE
34200
MARTIN
15000
ALLEN
19200
TURNER
18000
HIREDATE
01-MAY-81
28-SEP-81
20-FEB-81
08-SEP-81
JOB
Adding a Column
– You use the ADD clause to add columns.
SQL> ALTER TABLE dept30
2 ADD
(job VARCHAR2(9));
Table altered.
• The new column becomes the last column.
EMPNO ENAME
ANNSAL HIREDATE JOB
--------- ---------- --------- --------- ---7698 BLAKE
34200 01-MAY-81
7654 MARTIN
15000 28-SEP-81
7499 ALLEN
19200 20-FEB-81
7844 TURNER
18000 08-SEP-81
...
6 rows selected.
Modifying a Column
– You can change a column’s datatype, size,
and default value.
ALTER TABLE dept30
MODIFY
(ename VARCHAR2(15));
Table altered.
– A change to the default value affects only
subsequent insertions to the table.
Dropping a Column
• Use the DROP COLUMN clause to drop
columns you no longer need from the table.
ALTER TABLE dept30
DROP COLUMN Job;
Table altered.
Adding a Constraint
ALTER TABLE table
ADD [CONSTRAINT constraint] type (column);
• Add a FOREIGN KEY constraint to the EMP table
indicating that a manager must already exist as a valid
employee in the EMP table.
SQL> ALTER TABLE
emp
2 ADD CONSTRAINT emp_mgr_fk
3
FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.
Dropping a Constraint
– Remove the manager constraint from the
EMP table.
SQL> ALTER TABLE
2 DROP CONSTRAINT
Table altered.
emp
emp_mgr_fk;
• Remove the PRIMARY KEY constraint on the
DEPT table and drop the associated FOREIGN
KEY constraint on the EMP.DEPTNO column.
SQL> ALTER TABLE
dept
2 DROP PRIMARY KEY CASCADE;
Table altered.
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.
SQL> ALTER TABLE
2 DISABLE CONSTRAINT
Table altered.
emp
emp_empno_pk CASCADE;
Enabling Constraints
– Activate an integrity constraint currently
disabled in the table definition by using the
ENABLE clause.
SQL> ALTER TABLE
2 ENABLE CONSTRAINT
– altered.
Table
emp
emp_empno_pk;
– A UNIQUE or PRIMARY KEY index is
automatically created if you enable a
UNIQUE key or PRIMARY KEY constraint.
Dropping a Table
– All data and structure in the table is deleted.
– Any pending transactions are committed.
– All indexes are dropped.
– You cannot roll back this statement.
SQL> DROP TABLE dept30;
Table dropped.
Changing the Name of an Object
– To change the name of a table, view, sequence,
or synonym, you execute the RENAME
statement.
SQL> RENAME dept TO department;
Table renamed.
Related documents