View
253
Download
0
Category
Preview:
Citation preview
8/6/2019 Lecture7 - SQL DDL - Part 1
1/31
Introduction to Structured QueryLanguage (SQL) Part 1
DDL - Creating and ManagingTables
Chapter 6
8/6/2019 Lecture7 - SQL DDL - Part 1
2/31
2
O bjectives of SQL
Ideally, database language should allow user to: create the database and relation structures; perform insertion, modification, deletion of data
from relations; perform simple and complex queries.Must perform these tasks with minimal user effortand command structure/syntax must be easy to learn.It must be portable conform to some recognizedstandard (used by all DBMS, eg Oracle, mySQL etc).
Pearson Education Limited 1995, 2005
8/6/2019 Lecture7 - SQL DDL - Part 1
3/31
8/6/2019 Lecture7 - SQL DDL - Part 1
4/31
4
W hat is SQL?
Most SQL commands are Relational DBMS (RDBMS)independent. Meaning that they can be used in MySQL,Oracle, Informix, SQLServer etc
However, some complex or advanced commands/featuresmight be RDBMS dependent, e.g., VARCHAR2() can be usedwith Oracle but not MySQL.SQL is a 4 th generation language. It is record based. In other words the commands reduce the need for loops.
8/6/2019 Lecture7 - SQL DDL - Part 1
5/31
5
SQL statements
SELECT Data Retrieval retrieve data from database
INSERTUPDATE
DELETE
Data Manipulation Language (DML) entersnew rows, changing existing rows and removes
unwanted rows from tables in the database.CREATE
ALTER DROPRENAMETRUNCATE
Data Definition Language (DDL) sets up,changes and removes data structures from tables.
COMMITROLLBACK
Transaction Control manages the changes made by DML statements.
GRANT
REVOKE
Data Control Language (DCL) gives or
removes access right.
8/6/2019 Lecture7 - SQL DDL - Part 1
6/31
6
SQL statements
Consists of standard English words:
1) CREATE TABLE Staff( staffNo VARCHAR2(5 ),
l Name VARCHAR2( 1 5 ),sa l ary NUMBER(7 , 2 ));
2 ) INSERT INTO Staff VALUES(SG 16, Brown , 8300);
3) SELECT staffNo , l Name , sa l aryFROM Staff
WHERE sa l ary > 10000;
Pearson Education Limited 1995, 2005
DDL
DML
8/6/2019 Lecture7 - SQL DDL - Part 1
7/31
7
W riting SQL CommandsSQL statement consists of reserved and user-defined words.
Reserved words are a fixed part of SQL and must be speltexactly as required and cannot be split across lines.
User-defined words are made up by user and represent namesof various database objects such as tables, columns, views,index.
Most components of an SQL statement are case insensitive ,except for literal character data.More readable with indentation : Each clause should begin on a new line. Start of a clause should line up with start of other clauses. If clause has several parts, should each appear on a separate line
and be indented under start of clause.
Pearson Education Limited 1995, 2005
8/6/2019 Lecture7 - SQL DDL - Part 1
8/31
Data Definition Language (DDL)
8/6/2019 Lecture7 - SQL DDL - Part 1
9/31
9
DDL - O bjectives
Create tablesDescribe the datatypes that can be used whenspecifying column definitionAlter table definitionsDrop, rename and truncate tablesDefining constraints
8/6/2019 Lecture7 - SQL DDL - Part 1
10/31
10
N aming rules for table names and columnnames
Must begin with a letter.Must be 1- 3 0 characters long.Must contain only A -Z , a-z , 0-9 , _ , $ and #Must not duplicate the name of another objectowned by the same user.
Naming guidelines
Use descriptive names for tables and column Names are case insensitive Eg: EMPLOYEE is treated as the same name as
eMPloyee or EmPLOYee
8/6/2019 Lecture7 - SQL DDL - Part 1
11/31
11
Data types
VARCHAR2(size) variable length character dataCHAR(size) fixed-length character data
NUMBER(p,s) numeric data (precision, scale)DATE date and time valuesLONG - variable-length character data up to 2 gigabytesCLOB character data up to 4 gigabytesRAW raw binary data
BLOB binary data up to 4 gigabytesBFILE binary data stored in an external file: up to 4 gigabytes
8/6/2019 Lecture7 - SQL DDL - Part 1
12/31
12
Creating tables
CREATE TABLE table_name( column_name data type [default expr ]);
Table_name is the name of the table
Column_name is the name of the columnDatatype is the column data type and lengthDefault_expr specify default value if a value is omitted in the insert
statementEg:CREATE TABLE department( dept_no number(5 ),
dept_name varchar2(2 0),l ocation varchar2( 1 5 ));
Describe department ;
8/6/2019 Lecture7 - SQL DDL - Part 1
13/31
13
Create table staff ( id NUMBER( 4 ),
name VARCHAR2(50),
position VARCHAR2(15),salary NUMBER ( 7 ,2),
primary key (id));
Create table patient (ic NUMBER(12) PRIMARY KEY,name VARCHAR2(50),
phone# NUMBER(10));
8/6/2019 Lecture7 - SQL DDL - Part 1
14/31
14
Create table medicine( code NUMBER( 4 ),
name VARCHAR2(50),
dosage VARCHAR2(15), primary key (code));
Create table treatment (ic NUMBER(12),id NUMBER( 4 ),datevisit DATE,disease VARCHAR2(10),medcode NUMBER( 4 ),
primary key (ic,id,datevisit,medcode),foreign key ic references patient(ic),foreign key id references staff(id),foreign key medcode references medicine(code));
8/6/2019 Lecture7 - SQL DDL - Part 1
15/31
15
O racles example
8/6/2019 Lecture7 - SQL DDL - Part 1
16/31
16
A lter table
Use ALTER TABLE statement to add, modify or dropcolumns.
ALTER TABLE ADD (co l umn1 datatype ,
co l umn2 datatype );
ALTER TABLE MODIFY (col umn datatype );
ALTER TABLE DROP (co l umn );
8/6/2019 Lecture7 - SQL DDL - Part 1
17/31
17
O racles Example
8/6/2019 Lecture7 - SQL DDL - Part 1
18/31
18
Dropping a table
All data and structure in the table is deleted.Any pending transactions are committed.All indexes are dropped.Cannot roll back (undo) the DROP TABLEstatement.Eg : DROP TABLE student ;
8/6/2019 Lecture7 - SQL DDL - Part 1
19/31
19
RENAMEand TRUNCATE
To change the name of a tableRENAME old_name TO new_name ;
Eg: RENAME student TO stud ;
To removes all rows/records from a table:TRUNCATE TABLE ;
Eg: TRUNCATE TABLE stud ;
8/6/2019 Lecture7 - SQL DDL - Part 1
20/31
20
ConstraintsEnforce rules on the data at the table level whenever arow is inserted, updated or deleted from that table.Prevent the deletion of a table if there aredependencies from other tables.Types of constraints: NOT NULL a column cannot contain a null value UNIQUE specifies a column or combination of
columns whose values must be unique for all rowsin the table
PRIMARY KEY uniquely identifies each row FOREIGN KEY establishes and enforces
relationship of other tables
CHECK specifies a condition must be true
8/6/2019 Lecture7 - SQL DDL - Part 1
21/31
21
Constraint Guidelines
Give a name for a constraint or the Oracle server generates aname using the SYS _Cn format.Constraint can be created: At the same time as the table is created, or After the table has been created using ALTER TABLE
statement.Define a constraint at the column or the table level.
Column levelReferences a single column and is defined withina specification for the owning column
Table level
References one or more columns and is definedseparately from the definitions of the columns inthe table; can define any constraints except NO TNU LL
8/6/2019 Lecture7 - SQL DDL - Part 1
22/31
22
Defining constraints
One or many students are attached to only one department.
Department
Dept_No {PK}Dept_NamePhoneNoLocation
Student
St_ID {PK}St_NameSt_AddressSt_emailDeptNo {FK}
attach
1..1 1..*
8/6/2019 Lecture7 - SQL DDL - Part 1
23/31
23
Defining constraintsCREATE TABLE department( dept_no number(5 ) CONSTRAINTS dpt_id_pk PRIMARY KEY ,
dept_name VARCHAR2(2 0) NOT NULL ,l ocation VARCHAR2( 1 5 ));
Create tab l e student( st_id NUMBER(5 ),
st_name VARCHAR2( 1 5 ),st_emai l VARCHAR2( 10) UNIQUE,
cgpa NUMBER(4 , 2 ) CONSTRAINTS stud_cgpa CHECK (cgpa
8/6/2019 Lecture7 - SQL DDL - Part 1
24/31
24
8/6/2019 Lecture7 - SQL DDL - Part 1
25/31
25
FOREIGN KEY Constraint
FOREIGN KEY: defines the column in the child tableat the table level constraint level
REFERENCES : Identifies the table and column inthe parent table.
Create tab l e student (::CONSTRAINTS st_dept_fk FOREIGN KEY (dept_no )
REFERENCES department (dept_no ));
8/6/2019 Lecture7 - SQL DDL - Part 1
26/31
26
The CHECK Constraint
Defines the condition that each row must satisfy.CHECK constraints can be defined at the column level or table level.
Eg:
Column level
CREATE TABLE student( ...
cgpa NUMBER(4 , 2 ) CONSTRAINT STUD_CGPA CHECK (cgpa
8/6/2019 Lecture7 - SQL DDL - Part 1
27/31
8/6/2019 Lecture7 - SQL DDL - Part 1
28/31
28
Dropping a constraint
Remove the PRIMARY KEY constraint on the DEPARTMENTtable and drop the associated FOREIGN KEY constraint on theSTUDENTS.DEPTNO column:
ALTER TABLE departmentDROP PRIMARY KEY CASCADE ;
Remove the mentors constraint from the students table:
ALTER TABLE student
DROP CONSTRAINTS std_mentor_fk ;
8/6/2019 Lecture7 - SQL DDL - Part 1
29/31
29
Cascading Constraints
The CASCADE CONSTRAINTS clause: is used along with the DROP COLUMNclause. Drops all referential integrity constraints that refer to the
primary and unique keys defined on the dropped columns. Eg:
The following statements returned an error. ALTER TABLE department
drop (dept_no );
Submitting the following statement will delete the constraints: ALTER TABLE department
drop (dept_no ) CASCADE CONSTRAINTS ;
8/6/2019 Lecture7 - SQL DDL - Part 1
30/31
3 0
Cascading Constraints
8/6/2019 Lecture7 - SQL DDL - Part 1
31/31
3 1
Summary
In this chapter you should have learned: Creating new tables
Modify column definitions Verifying that the table exist Dropping and altering tables About constraints
Recommended