SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
Database Systems Slide 1
(SQL)
Creating and Managing Tables
Asif Sohail
University of the Punjab
Punjab University College of Information Technology (PUCIT)
Note:
The slides are adapted from Oracle corporation’s slides.
Database Systems Slide 2
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 Systems Slide 3
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
Database Systems Slide 4
Naming Conventions
• Must begin with a letter
• Can be 1–30 characters long
• Can contain only A–Z, a–z, 0–9, _, $, and #
• Names are not case sensitive (enclose names in
double quotes to make them case sensitive)
• Must not duplicate the name of another object
owned by the same user
• Must not be an Oracle Server reserved word
Database Systems Slide 5
The CREATE TABLE Statement
– You must have :
• CREATE TABLE privilege
• A storage area
You specify:
• Table name
• Column name, column data type, and column size
• Size specifies the max. length of a column.
• An oracle table can have up to 256 columns.
CREATE TABLE table_name
(col_name1 datatype(size) [Default expr][Col Constraints],
col_name2 datatype(size) [Default expr][Col Constraints],
…………
[Table Constraints]);
Database Systems Slide 6
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
Database Systems Slide 7
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? Type
--------------------------- -------- ---------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
Database Systems Slide 8
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 server
• Contain database information
Database Systems Slide 9
Querying the Data Dictionary
– Describe tables owned by the user.
• View distinct object types owned by the user.
• View tables, views, synonyms, and sequences owned
by the user.
SQL> SELECT *
2 FROM user_tables;
SQL> SELECT DISTINCT object_type
2 FROM user_objects;
SQL> SELECT *
2 FROM user_catalog;
Database Systems Slide 10
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_CONSTRAINTS.
Database Systems Slide 11
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 or Table Level]
• DEFAULT [Column Level]
Database Systems Slide 12
Defining Constraints
CREATE TABLE tablename
(col_name1 datatype(size)[Default expr][Col Constraints],
........
[table_constraint][,...]);
CREATE TABLE emp(
empno NUMBER(4),
ename VARCHAR2(10),
...
deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));
Database Systems Slide 13
Defining Constraints
– Column constraint level
– Table constraint level
column [CONSTRAINT constraint_name] constraint_type,
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
Database Systems Slide 14
The NOT NULL Constraint
• Ensures that null values are not permitted
for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
NOT NULL constraint
(no row can contain
a null value for
this column)
Absence of NOT NULL
constraint
(any row can contain
null for this column)
NOT NULL constraint
Database Systems Slide 15
The NOT NULL Constraint
• Defined at 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);
Database Systems Slide 16
The UNIQUE Key Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
UNIQUE key constraint
50 SALES DETROIT
60 BOSTON
Insert into Not allowed
(DNAME-SALES
already exists)
Allowed
Database Systems Slide 17
The UNIQUE Key Constraint
• Defined at either the table level or the column
level
SQL> CREATE TABLE dept(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));
Database Systems Slide 18
The PRIMARY KEY Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
PRIMARY KEY
Insert into
20 MARKETING DALLAS
FINANCE NEW YORK
Not allowed
(DEPTNO-20 already
exists)
Not allowed
(DEPTNO is null)
Database Systems Slide 19
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 dept(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
Database Systems Slide 20
The FOREIGN KEY Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
PRIMARY
KEY
EMP
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
...
FOREIGN
KEY
7571 FORD MANAGER ... 200 9
7571 FORD MANAGER ... 200 20
Insert into
Not allowed
(DEPTNO 9
does not exist
in the DEPT
table)
Allowed
Database Systems Slide 21
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));
Database Systems Slide 22
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
Database Systems Slide 23
The CHECK Constraint
– Defines a condition that each row must satisfy
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...
..., program CHAR(5),
CONSTRAINT student_program_ck
CHECK (program IN (‘BS’, MIT’, ‘MS’)),...
Database Systems Slide 24
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.
Database Systems Slide 25
Viewing Constraints
• Query the USER_CONSTRAINTS table to
view all constraint definitions and names.
CONSTRAINT_NAME C SEARCH_CONDITION
------------------------ - -------------------------
SYS_C00674 C EMPNO IS NOT NULL
SYS_C00675 C DEPTNO IS NOT NULL
EMP_EMPNO_PK P
...
SQL> SELECT constraint_name, constraint_type,
2 search_condition
3 FROM user_constraints
4 WHERE table_name = 'EMP';
Database Systems Slide 26
Viewing the Columns Associated with
Constraints
CONSTRAINT_NAME COLUMN_NAME
------------------------- ----------------------
EMP_DEPTNO_FK DEPTNO
EMP_EMPNO_PK EMPNO
EMP_MGR_FK MGR
SYS_C00674 EMPNO
SYS_C00675 DEPTNO
SQL> SELECT constraint_name, column_name
2 FROM user_cons_columns
3 WHERE table_name = 'EMP';
• View the columns associated with the constraint
names in the USER_CONS_COLUMNS view.
Database Systems Slide 27
Creating a Table
by Using a Subquery
– Create a table and insert rows by combining the
CREATE TABLE statement and AS subquery option.
– Match the number of specified columns to the number
of subquery columns.
– Define columns with column names and
default values.
– To create new table without populating it with the data
in the existing table, use the following:
CREATE TABLE table
[(column, column...)]
AS subquery;
CREATE TABLE table
[(column, column...)]
AS subquery WHERE 1=2;
Database Systems Slide 28
Creating a Table
by Using a Subquery
Name Null? Type
---------------------------- -------- -----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
ANNSAL NUMBER
HIREDATE DATE
SQL> DESCRIBE dept30
SQL> CREATE TABLE dept30
2 AS
3 SELECT empno, ename, sal*12 ANNSAL, hiredate
4 FROM emp
5 WHERE deptno = 30;
Table created.
Database Systems Slide 29
Creating a Small Database (Exercise)
Table Name: Student
Col Name Constraints
RegNo Primary Key
SName Not Null
Program Can be ‘BS’, ‘BBA’, or ‘BA’
NIC Unique
Table Name: Course
Col Name Constraints
CourseCode Primary Key
CourseTitle Not Null
CreditHours Can be either 3 or 4
Table Name: Result
Col Name Constraints
RegNo Primary Key, Foreign Key
CourseCode Primary Key, Foreign Key
CourseMarks Between 0 and 100
Database Systems Slide 30
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 or Enable a Constraint
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE table
MODIFY (column datatype [DEFAULT expr]
[, column datatype]...);
Database Systems Slide 31
Adding a Column
DEPT30
EMPNO ENAME ANNSAL HIREDATE
------ ---------- --------
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
“…add a
new
column
into
DEPT30
table…”
DEPT30
EMPNO ENAME ANNSAL HIREDATE
------ ---------- --------
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
JOB
JOB
New column
Database Systems Slide 32
Adding a Column
– You use the ADD clause to add columns.
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.
SQL> ALTER TABLE dept30
2 ADD (job VARCHAR2(9));
Table altered.
• The new column becomes the last column.
Database Systems Slide 33
Modifying a Column
– You can change a column’s datatype, size, and
default value.
– A change to the default value affects only
subsequent insertions to the table.
****************************************************
– ALTER TABLE tablename READ ONLY
ALTER TABLE dept30
MODIFY (ename VARCHAR2(15));
Table altered.
Database Systems Slide 34
Dropping and Renaming 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.
• Use the RENAME COLUMN clause to rename a
col.
ALTER TABLE dept30
RENAME COLUMN Job TO Designation;
Table altered.
Database Systems Slide 35
Adding a Constraint
• Add a FOREIGN KEY constraint to the EMP table
indicating that a manager must already exist as a
valid employee in the EMP table.
ALTER TABLE table
ADD [CONSTRAINT constraint] type (column);
SQL> ALTER TABLE emp
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.
Database Systems Slide 36
Dropping a Constraint
• Remove foreign key constraint from the EMP table.
SQL> ALTER TABLE emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.
• 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.
SQL> ALTER TABLE student
2 ALTER COLUMN program DROP DEFAULT;
Table altered.
• To drop a DEFAULT constraint
Database Systems Slide 37
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 emp
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.
Database Systems Slide 38
Enabling Constraints
– Activate an integrity constraint currently
disabled in the table definition by using the
ENABLE clause.
–
– A UNIQUE or PRIMARY KEY index is
automatically created if you enable a UNIQUE
key or PRIMARY KEY constraint.
SQL> ALTER TABLE emp
2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.
Database Systems Slide 39
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.
– CREATE GLOBAL TMPORARY TABLE
Database Systems Slide 40
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.
– NOTE: if the table has a reference in another table,
the above command may not work. To drop all the
references as well, use the following:
SQL> DROP TABLE dept30;
Table dropped.
SQL> DROP TABLE dept30 CASCADE CONSTRAINTS;
Table dropped.
Database Systems Slide 41
Thank you for your attention.
Asif Sohail
Assistant Professor
University of the Punjab
Punjab University College of Information Technology (PUCIT)
Allama Iqbal (Old) Campus, Anarkali
Lahore, Pakistan
Tel: +92-(0)42-111-923-923 Ext. 154
E-mail: asif@pucit.edu.pk

Contenu connexe

Similaire à SQL-8 Table Creation.pdf

Unit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptxUnit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptx
PetroJoe
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
EliasPetros
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
webhostingguy
 

Similaire à SQL-8 Table Creation.pdf (20)

Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Lab
LabLab
Lab
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Unit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptxUnit 2 Chap 4 SQL DDL.pptx
Unit 2 Chap 4 SQL DDL.pptx
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
SQL
SQLSQL
SQL
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Les10
Les10Les10
Les10
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
 
mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
 
Module 3
Module 3Module 3
Module 3
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
Oracle SQL AND PL/SQL
Oracle SQL AND PL/SQLOracle SQL AND PL/SQL
Oracle SQL AND PL/SQL
 

Dernier

➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men 🔝Thrissur🔝 Escor...
➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men  🔝Thrissur🔝   Escor...➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men  🔝Thrissur🔝   Escor...
➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men 🔝Thrissur🔝 Escor...
amitlee9823
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
amitlee9823
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Riyadh +966572737505 get cytotec
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
JoseMangaJr1
 
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
amitlee9823
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
amitlee9823
 
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
amitlee9823
 
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
only4webmaster01
 

Dernier (20)

Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men 🔝Thrissur🔝 Escor...
➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men  🔝Thrissur🔝   Escor...➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men  🔝Thrissur🔝   Escor...
➥🔝 7737669865 🔝▻ Thrissur Call-girls in Women Seeking Men 🔝Thrissur🔝 Escor...
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 
hybrid Seed Production In Chilli & Capsicum.pptx
hybrid Seed Production In Chilli & Capsicum.pptxhybrid Seed Production In Chilli & Capsicum.pptx
hybrid Seed Production In Chilli & Capsicum.pptx
 
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
 
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
 
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
 

SQL-8 Table Creation.pdf

  • 1. Database Systems Slide 1 (SQL) Creating and Managing Tables Asif Sohail University of the Punjab Punjab University College of Information Technology (PUCIT) Note: The slides are adapted from Oracle corporation’s slides.
  • 2. Database Systems Slide 2 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
  • 3. Database Systems Slide 3 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
  • 4. Database Systems Slide 4 Naming Conventions • Must begin with a letter • Can be 1–30 characters long • Can contain only A–Z, a–z, 0–9, _, $, and # • Names are not case sensitive (enclose names in double quotes to make them case sensitive) • Must not duplicate the name of another object owned by the same user • Must not be an Oracle Server reserved word
  • 5. Database Systems Slide 5 The CREATE TABLE Statement – You must have : • CREATE TABLE privilege • A storage area You specify: • Table name • Column name, column data type, and column size • Size specifies the max. length of a column. • An oracle table can have up to 256 columns. CREATE TABLE table_name (col_name1 datatype(size) [Default expr][Col Constraints], col_name2 datatype(size) [Default expr][Col Constraints], ………… [Table Constraints]);
  • 6. Database Systems Slide 6 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
  • 7. Database Systems Slide 7 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? Type --------------------------- -------- --------- DEPTNO NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13)
  • 8. Database Systems Slide 8 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 server • Contain database information
  • 9. Database Systems Slide 9 Querying the Data Dictionary – Describe tables owned by the user. • View distinct object types owned by the user. • View tables, views, synonyms, and sequences owned by the user. SQL> SELECT * 2 FROM user_tables; SQL> SELECT DISTINCT object_type 2 FROM user_objects; SQL> SELECT * 2 FROM user_catalog;
  • 10. Database Systems Slide 10 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_CONSTRAINTS.
  • 11. Database Systems Slide 11 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 or Table Level] • DEFAULT [Column Level]
  • 12. Database Systems Slide 12 Defining Constraints CREATE TABLE tablename (col_name1 datatype(size)[Default expr][Col Constraints], ........ [table_constraint][,...]); CREATE TABLE emp( empno NUMBER(4), ename VARCHAR2(10), ... deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO));
  • 13. Database Systems Slide 13 Defining Constraints – Column constraint level – Table constraint level column [CONSTRAINT constraint_name] constraint_type, column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
  • 14. Database Systems Slide 14 The NOT NULL Constraint • Ensures that null values are not permitted for the column EMP EMPNO ENAME JOB ... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ... NOT NULL constraint (no row can contain a null value for this column) Absence of NOT NULL constraint (any row can contain null for this column) NOT NULL constraint
  • 15. Database Systems Slide 15 The NOT NULL Constraint • Defined at 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);
  • 16. Database Systems Slide 16 The UNIQUE Key Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON UNIQUE key constraint 50 SALES DETROIT 60 BOSTON Insert into Not allowed (DNAME-SALES already exists) Allowed
  • 17. Database Systems Slide 17 The UNIQUE Key Constraint • Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE(dname));
  • 18. Database Systems Slide 18 The PRIMARY KEY Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON PRIMARY KEY Insert into 20 MARKETING DALLAS FINANCE NEW YORK Not allowed (DEPTNO-20 already exists) Not allowed (DEPTNO is null)
  • 19. Database Systems Slide 19 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 dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE (dname), 6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
  • 20. Database Systems Slide 20 The FOREIGN KEY Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS ... PRIMARY KEY EMP EMPNO ENAME JOB ... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 ... FOREIGN KEY 7571 FORD MANAGER ... 200 9 7571 FORD MANAGER ... 200 20 Insert into Not allowed (DEPTNO 9 does not exist in the DEPT table) Allowed
  • 21. Database Systems Slide 21 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));
  • 22. Database Systems Slide 22 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
  • 23. Database Systems Slide 23 The CHECK Constraint – Defines a condition that each row must satisfy ..., deptno NUMBER(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99),... ..., program CHAR(5), CONSTRAINT student_program_ck CHECK (program IN (‘BS’, MIT’, ‘MS’)),...
  • 24. Database Systems Slide 24 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.
  • 25. Database Systems Slide 25 Viewing Constraints • Query the USER_CONSTRAINTS table to view all constraint definitions and names. CONSTRAINT_NAME C SEARCH_CONDITION ------------------------ - ------------------------- SYS_C00674 C EMPNO IS NOT NULL SYS_C00675 C DEPTNO IS NOT NULL EMP_EMPNO_PK P ... SQL> SELECT constraint_name, constraint_type, 2 search_condition 3 FROM user_constraints 4 WHERE table_name = 'EMP';
  • 26. Database Systems Slide 26 Viewing the Columns Associated with Constraints CONSTRAINT_NAME COLUMN_NAME ------------------------- ---------------------- EMP_DEPTNO_FK DEPTNO EMP_EMPNO_PK EMPNO EMP_MGR_FK MGR SYS_C00674 EMPNO SYS_C00675 DEPTNO SQL> SELECT constraint_name, column_name 2 FROM user_cons_columns 3 WHERE table_name = 'EMP'; • View the columns associated with the constraint names in the USER_CONS_COLUMNS view.
  • 27. Database Systems Slide 27 Creating a Table by Using a Subquery – Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option. – Match the number of specified columns to the number of subquery columns. – Define columns with column names and default values. – To create new table without populating it with the data in the existing table, use the following: CREATE TABLE table [(column, column...)] AS subquery; CREATE TABLE table [(column, column...)] AS subquery WHERE 1=2;
  • 28. Database Systems Slide 28 Creating a Table by Using a Subquery Name Null? Type ---------------------------- -------- ----- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) ANNSAL NUMBER HIREDATE DATE SQL> DESCRIBE dept30 SQL> CREATE TABLE dept30 2 AS 3 SELECT empno, ename, sal*12 ANNSAL, hiredate 4 FROM emp 5 WHERE deptno = 30; Table created.
  • 29. Database Systems Slide 29 Creating a Small Database (Exercise) Table Name: Student Col Name Constraints RegNo Primary Key SName Not Null Program Can be ‘BS’, ‘BBA’, or ‘BA’ NIC Unique Table Name: Course Col Name Constraints CourseCode Primary Key CourseTitle Not Null CreditHours Can be either 3 or 4 Table Name: Result Col Name Constraints RegNo Primary Key, Foreign Key CourseCode Primary Key, Foreign Key CourseMarks Between 0 and 100
  • 30. Database Systems Slide 30 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 or Enable a Constraint ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...);
  • 31. Database Systems Slide 31 Adding a Column DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ---------- -------- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... “…add a new column into DEPT30 table…” DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ---------- -------- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... JOB JOB New column
  • 32. Database Systems Slide 32 Adding a Column – You use the ADD clause to add columns. 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. SQL> ALTER TABLE dept30 2 ADD (job VARCHAR2(9)); Table altered. • The new column becomes the last column.
  • 33. Database Systems Slide 33 Modifying a Column – You can change a column’s datatype, size, and default value. – A change to the default value affects only subsequent insertions to the table. **************************************************** – ALTER TABLE tablename READ ONLY ALTER TABLE dept30 MODIFY (ename VARCHAR2(15)); Table altered.
  • 34. Database Systems Slide 34 Dropping and Renaming 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. • Use the RENAME COLUMN clause to rename a col. ALTER TABLE dept30 RENAME COLUMN Job TO Designation; Table altered.
  • 35. Database Systems Slide 35 Adding a Constraint • Add a FOREIGN KEY constraint to the EMP table indicating that a manager must already exist as a valid employee in the EMP table. ALTER TABLE table ADD [CONSTRAINT constraint] type (column); SQL> ALTER TABLE emp 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno); Table altered.
  • 36. Database Systems Slide 36 Dropping a Constraint • Remove foreign key constraint from the EMP table. SQL> ALTER TABLE emp 2 DROP CONSTRAINT emp_mgr_fk; Table altered. • 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. SQL> ALTER TABLE student 2 ALTER COLUMN program DROP DEFAULT; Table altered. • To drop a DEFAULT constraint
  • 37. Database Systems Slide 37 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 emp 2 DISABLE CONSTRAINT emp_empno_pk CASCADE; Table altered.
  • 38. Database Systems Slide 38 Enabling Constraints – Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. – – A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint. SQL> ALTER TABLE emp 2 ENABLE CONSTRAINT emp_empno_pk; Table altered.
  • 39. Database Systems Slide 39 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. – CREATE GLOBAL TMPORARY TABLE
  • 40. Database Systems Slide 40 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. – NOTE: if the table has a reference in another table, the above command may not work. To drop all the references as well, use the following: SQL> DROP TABLE dept30; Table dropped. SQL> DROP TABLE dept30 CASCADE CONSTRAINTS; Table dropped.
  • 41. Database Systems Slide 41 Thank you for your attention. Asif Sohail Assistant Professor University of the Punjab Punjab University College of Information Technology (PUCIT) Allama Iqbal (Old) Campus, Anarkali Lahore, Pakistan Tel: +92-(0)42-111-923-923 Ext. 154 E-mail: asif@pucit.edu.pk