View
226
Download
1
Category
Preview:
Citation preview
Lecture5: SQL Overview , Oracle Data Type , DDL and Constraints
Ref. Chapter6
Lecture4
1
Lecture4
SQL overview
• Official pronunciation is ‘S-Q-L‘ or ( see-qual)• SQL: Structured Query Language• The standard for relational database management systems
(RDBMS) such as Oracle Database.• All SQL statements are instructions to the database.• Easy to learn:
• Consists of standard English words, case insensitive• It is a non-procedural language:
• you specify what information you require, rather than how to get it. In other words, SQL does not require you to specify the access methods to the data 2
The Process of Database Design
Lecture4
Real World Domain
Conceptual model (ERD)
Relational Data Model
Create schema
(DDL)
Load Data(DML)
3
Lecture4
SQL Overview
• SQL provides statements for a variety of tasks, including:1. Querying data( Select command)2. Inserting, updating, and deleting rows in a table (DML)3. Creating, replacing, altering, and dropping objects(DDL)4. Controlling access to the database and its objects(DCL)5. Guaranteeing database consistency and integrity(DCL)
4
Lecture4
Built-In Oracle Data type SummaryBuilt-in Data type Description Max Size: Oracle 9i/10g
VARCHAR2(size[BYTE | CHAR]) Variable length character string having
maximum length size bytes.You must specify size
4000 bytesminimum is 1
CHAR(size)Fixed length character data of length size bytes. This should be used for fixed length data. Such as codes A100, B102...
2000 bytesDefault and minimum size is 1 byte.
NUMBER(p,s) Number having precision p and scale s. The precision pcan range from 1 to 38. The scale s can range from -84 to127.
The precision p can range from 1 to 38.
The scale s can range from -84 to 127.
DATE Valid date range from January 1, 4712 BC to December31, 9999 AD.
from January 1, 4712 BC to December 31, 9999 AD.
TIMESTAMP[timePrecsion]
Year, month, and day values of date, as well as hour,minute, and second values of time,
Accepted values of fractional_seconds_precision are 0 to 9. (default = 6)
5
Lecture4
NUMBER(p,s)
• Syntax for specifying numbers• Number (precision, scale)
• Precision is the maximum digits of numbers• Scale specifies the position of decimal point.• E.g.
• Number(5) 5 digit integer, ex) 12345 • Number(6,2) 6 digit (not including decimal point)
decimal number with 2 digits after the decimal point , ex) 1234.56
• Can store 1—38 digits precision 6
Lecture4
StringTo store strings, you can choose from: • Char
• stores fixed-length character strings of up to 2000 characters. Eg. char(10)
• should use it to store short strings• Varchar2
• Stores variable-length strings of up to 4000 characters long. Eg. Varchar2(50)
• Preferred for most string types
String values are quoted with single quotes• Eg ‘12234’, ‘abcd’, ‘a12’
7
Lecture4
Date and time
• Oracle uses the date data type to store both date and time• Always uses 7 bytes for date-time data.• Oracle date has rich formats, you need to specify it
SS second 0-59MI Minute 0-59HH Hour 1-12HH24 Military hour 1-24DD day of month 1-31 (depends on month)DAY day of the week Sunday-SaturdayD day of the week 1-7MM month number 1-12MONmonth abbreviated Jan—DecMonth Month spelled out January-DecemberYY last 2 digits of year eg, 98YYYY full year value eg, 1998
8
Lecture4
Date and time
• Example of date format:• ‘dd-mon-yyyy’ 01-dec-2001
• ‘dd/mm/yyyy’ 01/12/2001
• ‘mm-dd-yy hh:mi:ss’ 12-01-01 12:30:59
• Default format: ‘dd-mon-yyyy’
• Current date and time: • Sysdate
9
Lecture4
10
Lecture4Data Definition language ( DDL )
Table Creation
11
Lecture4
Data Definition (Creating a table)
• Creating a table create table table-name ( column-name1 datatype , …….. column-nameN datatype );
• Table Name CONDITIONS :• can not exceed 30 characters long• Must begin with an alphabetic character• May contain letters, numbers, $, # and _• Should not be an oracle reserved word • Should be descriptive
12
Lecture4
Identifying Primary Key
create table table-name ( column-name1 datatype, …….. column-nameN datatype ,[constraint constraint-name] Primary key (columns-name) );
ORcreate table table-name (
column-name1 datatype [constraint constraint-name] primary key, …….. column-nameN datatype);
13
Lecture4
Example
create table Department (Dept_no char(4) PRIMARY KEY,
Dept_name varchar2(25));
ORcreate table Department (
dept_no char(4), Dept_name varchar2(25),
CONSTRAINT dept_PK PRIMARY KEY(dept_no));
14
Lecture4
Integrity Constraints
• An integrity constraint defines a business rule for a table column.
• When enabled, the rule will be enforced by oracle• constraints can be specified as row constraints and table
constraints. Tables constraints can, for example, identify several columns such as Primary key.
• If the results of an INSERT or UPDATE statement violate an integrity constraint, the statement will be rolled back.
• Note : If you don’t give the constraint name, the system will generate a name automatically, but the name is hard for human understanding. 15
Lecture4
Integrity Constraints
• Constraint clauses can appear in the following statements:
1. CREATE TABLE2. ALTER TABLE3. CREATE VIEW4. ALTER VIEW
16
Lecture4
The FIFTH types of integrity constraint
1. NOT NULL constraint 2. unique constraint 3. primary key constraint 4. foreign key constraint5. check constraint
17
Lecture4
NOT NULL constraint
• The NOT NULL constraint enforces a column to NOT accept NULL values.
• The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.
Syntax: create table table-name (
column-name1 datatype NOT NULL );
18
Lecture4
NOT NULL constraint
• Example : The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
CREATE TABLE Persons( P_Id char(5) NOT NULL, LastName varchar2(255) NOT NULL, FirstName varchar2(255), Address varchar2(255), City varchar2(255) );
19
Lecture4
SQL NULL
• If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.
• NULL values are treated differently from other values.• NULL is used as a placeholder for unknown or inapplicable
values.• Note: It is not possible to compare NULL and 0; they are
not equivalent.• It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.• We will have to use the IS NULL and IS NOT NULL
operators instead.20
Lecture4
UNIQUE constraint
• The UNIQUE constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.
• The UNIQUE constraint provides a guarantee for uniqueness for a column or set of columns.
• Unique columns are not automatically NOT NULL
Syntax: create table table-name (
column-name1 datatype UNIQUE );ORcreate table table-name (
…….…….
[constraint constraint-name] UNIQUE (Columns_list) ;
21
Lecture4
Example
• The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
CREATE TABLE Persons(P_Id char(5) NOT NULL UNIQUE,LastName varchar2(255) NOT NULL,FirstName varchar2(255),Address varchar2(255),City varchar2(255),Unique (LastName, FirstName))
22
Lecture4
Primary key Constraints
• A primary key constraint combines a NOT NULL constraint and a UNIQUE constraint in a single declaration. That is, it prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
• Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
23
Lecture4
Primary key Constraints
Syntax: create table table-name (
column-name1 datatype Primary Key);
OR
create table table-name (…….
…….[constraint constraint-name] Primary Key (Columns_list) ;
24
Lecture4
Primary key Constraints
Example :create table Department (dept_no char(4),Dept_name varchar2(25),CONSTRAINT dept_PK PRIMARY KEY(dept_no));
25
Lecture4
Foreign Keys constraint
foreign key constraint requires values in one table to match values in another table.
Syntax: create table table-name (
column-name1 datatype,…………[constraint constraint-name] Foreign key (Column_name) references referenced_table (column_in_referenced_table) );
26
Lecture4
Foreign Keys constraint
Create table Staff(staff_no char(3),staff_name varchar2(20),dept_no char(4),Constraint staff_fk foreign key (dept_no) references department (dept_no));
27
Lecture4
referential integrity constraints
• When you delete or update a value of the columns referenced by other tables, the referential integrity constraints may be violated.
• ON DELETE/UPDATE Clause• The ON DELETE / ON UPDATE clause lets you
determine how Oracle Database automatically maintains referential integrity if you remove or update a referenced primary key value. If you omit this clause, then Oracle does not allow you to delete referenced key values in the parent table that have dependent rows in the child table.
28
Lecture4
referential integrity constraints
Four options are supported when the user attempt to delete the CK and there matching FKs:
• ON DELETE/UPDATE CASCADE: delete or update the CK row from the parent table and all matching FK rows in the child table.
• ON DELETE/UPDATE SET NULL: delete or update the CK row from the parent table and set the FK values to NULL in the child table. This is valid only if the foreign key columns do not have the NOT NULL qualifier specified.
• ON DELETE/UPDATE SET Default: delete or update the CK row from the parent table and set the FK values to the specified default value in the child table. Valid only if DEFAULT constraint is specified
• No action: Reject the delete operation from the parent table. This is the default setting if the ON DELETE rule is omitted.
29
Lecture4
• CREATE TABLE EmpMaster(EmpId CHAR(1) PRIMARY KEY,EmpName VARCHAR(25));
• CREATE TABLE EmpDetails(DeptId CHAR(3) PRIMARY KEY,DeptName VARCHAR(20)
EmpId CHAR(1) FOREIGN KEY REFERENCES EmpMaster(EmpId) ON DELETE CASCADE );
• delete from EmpMaster where EmpId=1
EmpMaster EmpDetails
parent child
EmpId EmpName
1 Ali
2 Slaut
3 John
EmpId DeptNo DeptName
1 101 AAA
2 101 AAA
3 103 CCC
FK
PK
30
EmpId EmpName
2 Slaut
3 John
EmpId DeptNo DeptName
2 101 AAA
3 103 CCC
Lecture4
• CREATE TABLE EmpMaster(EmpId CHAR(1) PRIMARY KEY,EmpName VARCHAR(25));
• CREATE TABLE EmpDetails(DeptId CHAR(3) PRIMARY KEY,DeptName VARCHAR(20)
EmpId CHAR(1) FOREIGN KEY REFERENCES EmpMaster(EmpId) ON DELETE SET NULL );
• delete from EmpMaster where EmpId=1EmpMaster
EmpDetails
parentchild
EmpId EmpName
1 Ali
2 Slaut
3 John
EmpId DeptNo DeptName
1 101 AAA
2 101 AAA
3 103 CCC
FK
PK
31
EmpId EmpName
2 Slaut
3 John
EmpId DeptNo DeptName
NULL 101 AAA
2 101 AAA
3 103 CCC
Lecture4
Check Constraints
• The CHECK constraint is used to limit the value range that can be placed in a column.
• If you define a CHECK constraint on a single column it allows only certain values for this column.
• If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
32
Lecture4
Check Constraints
Syntax: create table table-name (
column-name1 datatype Check (Check_condition));
OR
create table table-name (…….
…….[constraint constraint-name] Check (Check_condition));
33
Lecture4
Check Constraints Example
Create table staff(Staff_no char(3),Staff_name varchar2(20) not null,Staff_gender char(1) check (staff_gender in (‘M’, ‘F’)),Staff_salary number(8,2) not null,Dept_no char(4),Constraint staff_pk Primary key (staff_no),Constraint staff_fk Foreign key (dept_no) references department (dept_no),Constraint staff_sal check (staff_salary >10000.00));
To allow naming of a CHECK constraint
34
Lecture4
DEFAULT constraint
• The DEFAULT constraint is used to insert a default value into a column.
• The default value will be added to all new records, if no other value is specified.
Syntax: create table table-name (
column-name1 datatype Default (Default_value));
35
Lecture4
DEFAULT constraint
• Example : The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created:
CREATE TABLE Persons(P_Id char(5) NOT NULL,LastName varchar2(255) NOT NULL,FirstName varchar2(255),Address varchar2(255),City varchar2(255) DEFAULT 'Sandnes')
36
Lecture4
Example : All Constraints
Create table staff(Staff_no char(3),Staff_name varchar2(20) not null,DateofBirth date,Staff_nationality char(10) default ‘Saudi’,Staff_salary number(8,2) not null,Dept_no char(4), Constraint staff_pk Primary key (staff_no),Constraint staff_fk Foreign key (dept_no) references department (dept_no) on delete set null, Constraint staff_sal check (staff_salary >10000.00),UNIQUE(staff_name, DateofBirth));
37
Lecture4
38
Lecture4
Modifying Table Definitions
Alter table table_nameadd (column_specification | constraint,...,
column_specification| constraint);Alter table table_name
modify (column_specification | constraint,..., Column_specification | constraint);
Alter table table_namedrop column column_name | drop (column_list);
Alter table table_name drop primary key;
Alter table table_namedrop constraint constraint_name;
39
Lecture4
Examples
alter table ordersadd (quantity number (3) not null);
alter table ordersmodify (quantity number(5));
alter table ordersdrop (quantity);
• Be careful if the table contains data.40
Lecture4
Dropping Tables
• Drop table table_name [Cascade Constraints];
• Pay attention to referential integrity constraints when dropping tables.
• If Cascade Constraints is used, the constraints will be dropped first.
• example• Drop table Staff; • Drop table Department;• Drop table Department cascade constraints;
41
Lecture4
Viewing/enabling/disabling/dropping Constraints
• To view the constraints defined for table Department, type SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name ='DEPARTMENT';
• To disable/enable a constraint, use ALTER TABLE Table_name DISABLE CONSTRAINT constraint_name; ALTER TABLE Table_name ENABLE CONSTRAINT constraint_name;
• To drop a constraint, use ALTER TABLE Table_name DROP PRIMARY KEY| UNIQUE (column_name) | CONSTRAINT constraint_name;
42
Lecture4
Example
• To DROP a CHECK Constraint
ALTER TABLE PersonsDROP CONSTRAINT chk_Person;
• To DROP a FOREIGN KEY Constraint
ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders;
43
Lecture4
Viewing Tables and Table Structures
• To see what tables are there in SQL*plus, type
select * from cat;
• To see the structure of a table, type
describe table_name; or desc table _name;
44
Lecture4
45
References
• “Database Systems: A Practical Approach to Design, Implementation and Management.” Thomas Connolly, Carolyn Begg. 5th Edition, Addison-Wesley, 2009.
Lecture4
46
Recommended