You are on page 1of 31

Chapter 6 Introduction to Structured Query Language (SQL) Part 1 DDL - Creating and Managing Tables

Objectives 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 effort and command structure/syntax must be easy to learn.  It must be portable conform to some recognized standard (used by all DBMS, eg Oracle, mySQL etc).
2

Pearson Education Limited 1995, 2005

What is SQL?


In programming, once an algorithm has been constructed the next step will be converting the algorithm to a working programming language, e.g., C++, Java. Similarly for database, once normalized relational schemas and relational algebra for queries have been defined, the next step will be coding them using a working language. Hence, language for database is called Structured Query Language (SQL). SQL is a standard query language that can be used to create and manipulate relational databases. Again similar to programming, there are many software that can be used to write a C++ program, e.g., Borland C++, Turbo C++, Netbean etc. So, in database, the software is called Database Management System (DBMS). Examples of them are Oracle, Access, SQL Server, MySQL etc.

What 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/features might be RDBMS dependent, e.g., VARCHAR2() can be used with Oracle but not MySQL. SQL is a 4th generation language. It is record based. In other words the commands reduce the need for loops.

SQL statements
SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK GRANT REVOKE Data Retrieval retrieve data from database Data Manipulation Language (DML) enters new rows, changing existing rows and removes unwanted rows from tables in the database.

Data Definition Language (DDL) sets up, changes and removes data structures from tables.

Transaction Control manages the changes made by DML statements. Data Control Language (DCL) gives or removes access right.
5

SQL statements


Consists of standard English words:


1) CREATE TABLE Staff ( staffNo VARCHAR2(5), lName VARCHAR2(15), salary NUMBER(7,2)); 2) INSERT INTO Staff VALUES (SG16, Brown, 8300); 3) SELECT staffNo, lName, salary FROM Staff WHERE salary > 10000;
6

DDL

DML

Pearson Education Limited 1995, 2005

Writing SQL Commands




SQL statement consists of reserved and user-defined words.


Reserved words are a fixed part of SQL and must be spelt exactly as required and cannot be split across lines. User-defined words are made up by user and represent names of 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.
7

Pearson Education Limited 1995, 2005

Data Definition Language (DDL)

DDL - Objectives
 Create tables  Describe the

datatypes that can be used when specifying column definition  Alter table definitions  Drop, rename and truncate tables  Defining constraints

Naming rules for table names and column names


 Must

begin with a letter.  Must 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.  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
10

Data types
        

VARCHAR2(size) variable length character data CHAR(size) fixed-length character data NUMBER(p,s) numeric data (precision, scale) DATE date and time values LONG - variable-length character data up to 2 gigabytes CLOB character data up to 4 gigabytes RAW raw binary data BLOB binary data up to 4 gigabytes BFILE binary data stored in an external file: up to 4 gigabytes
11

Creating tables
CREATE TABLE ( column_name table_name data type [default expr]);

Table_name is the name of the table Column_name is the name of the column Datatype is the column data type and length Default_expr specify default value if a value is omitted in the insert statement Eg: CREATE TABLE department ( dept_no number(5), dept_name varchar2(20), location varchar2(15)); Describe department;
12

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));
13

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));

14

Oracles example

15

Alter table


Use ALTER TABLE statement to add, modify or drop columns.


ALTER TABLE <table_name> ADD (column1 datatype, column2 datatype); ALTER TABLE <table_name> MODIFY (column ALTER TABLE <table_name> DROP (column);
16

datatype);

Oracles Example

17

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 TABLE statement.  Eg : DROP TABLE student;

18

RENAME and TRUNCATE


 To

change the name of a table RENAME old_name TO new_name; Eg: RENAME student TO stud;

 To

removes all rows/records from a table: TRUNCATE TABLE <table_name>; Eg: TRUNCATE TABLE stud;

19

Constraints
Enforce rules on the data at the table level whenever a row is inserted, updated or deleted from that table.  Prevent the deletion of a table if there are dependencies 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 rows in the table PRIMARY KEY uniquely identifies each row FOREIGN KEY establishes and enforces relationship of other tables CHECK specifies a condition must be true


20

Constraint Guidelines


Give a name for a constraint or the Oracle server generates a name 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 level References a single column and is defined within a specification for the owning column References one or more columns and is defined separately from the definitions of the columns in the table; can define any constraints except NOT NULL
21

Table level

Defining constraints
Department Dept_No {PK} Dept_Name PhoneNo Location
attach
1..1 1..*

Student St_ID {PK} St_Name St_Address St_email DeptNo {FK}

One or many students are attached to only one department.

22

Defining constraints
CREATE TABLE department ( dept_no number(5) CONSTRAINTS dpt_id_pk PRIMARY KEY, dept_name VARCHAR2(20) NOT NULL, location VARCHAR2(15)); Create table student ( st_id NUMBER(5), st_name VARCHAR2(15), st_email VARCHAR2(10) UNIQUE, cgpa NUMBER(4,2) CONSTRAINTS stud_cgpa CHECK (cgpa <= 4 ), dept_no NUMBER(5), CONSTRAINTS st_id_pk PRIMARY KEY (st_id), CONSTRAINTS st_dept_fk FOREIGN KEY (dept_no) REFERENCES department (dept_no));
23

24

FOREIGN KEY Constraint


KEY: defines the column in the child table at the table level constraint level  REFERENCES : Identifies the table and column in the parent table.
 FOREIGN

Create table student ( :: CONSTRAINTS st_dept_fk FOREIGN KEY (dept_no) REFERENCES department (dept_no));
25

The CHECK Constraint


 

Defines the condition that each row must satisfy. CHECK constraints can be defined at the column level or table level. Eg:
CREATE TABLE student ( ... cgpa NUMBER(4,2) CONSTRAINT STUD_CGPA CHECK (cgpa <= 4 ), ...); CREATE TABLE student ( ... cgpa NUMBER(4,2), CONSTRAINTS stud_cgpa CHECK (cgpa <= 4 ) ); 26

Column level

Table level

Adding a constraint
Use ALTER TABLE statement to:


Add, drop, enable or disable a constraint, but not to modify its structure Add a NOT NULL constraint by using the MODIFY clause
Assume student has a relationship with lecturers table to show that a lecturer supervises many students.

ALTER TABLE student ADD CONSTRAINTS std_mentor_fk FOREIGN KEY(lect_id) REFERENCES lecturer (lect_id); ALTER TABLE student MODIFY ( st_name VARCHAR2(20) NOT NULL);

Modify st_name column to add NOT NULL constraint


27

Dropping a constraint


Remove the mentors constraint from the students table: ALTER TABLE student DROP CONSTRAINTS std_mentor_fk ;

Remove the PRIMARY KEY constraint on the DEPARTMENT table and drop the associated FOREIGN KEY constraint on the STUDENTS.DEPTNO column: ALTER TABLE department DROP PRIMARY KEY CASCADE;
28

Cascading Constraints


The CASCADE CONSTRAINTS clause: is used along with the DROP COLUMN clause. 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 ;

29

Cascading Constraints

30

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

31

You might also like