Lecture5: SQL Overview, Oracle Data Type, DDL and Constraints Ref. Chapter6 Lecture4 1
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 Lecture4 2
The Process of Database Design Lecture4 Real World Domain Conceptual model (ERD) Relational Data Model Create schema (DDL) Load Data (DML) 3
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) Lecture4 4
Built-In Oracle Data type Summary Built-in Data typeDescription Max Size: Oracle 9i/10g VARCHAR2(size [BYTE | CHAR]) Variable length character string having maximum length size bytes. You must specify size 4000 bytes minimum is 1 CHAR(size) Fixed length character data of length size bytes. This should be used for fixed length data. Such as codes A100, B bytes Default and minimum size is 1 byte. NUMBER(p,s)Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127. The precision p can range from 1 to 38. The scale s can range from -84 to 127. DATEValid date range from January 1, 4712 BC to December 31, 9999 AD. from January 1, 4712 BC to December 31, 9999 AD. TIMESTAMP[timePr ecsion] 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) Lecture4 5
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) Number(6,2) 6 digit (not including decimal point) decimal number with 2 digits after the decimal point, ex) Can store 1—38 digits precision Lecture4 6
String To 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’ Lecture4 7
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 second0-59 MIMinute0-59 HHHour1-12 HH24Military hour1-24 DDday of month1-31 (depends on month) DAYday of the week Sunday-Saturday Dday of the week1-7 MM month number 1-12 MONmonth abbreviated Jan—Dec Month Month spelled outJanuary-December YYlast 2 digits of yeareg, 98 YYYYfull year valueeg, 1998 Lecture4 8
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’ :30:59 Default format: ‘dd-mon-yyyy’ Current date and time: Sysdate Lecture4 9
10
Data 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 Lecture4 12
Identifying Primary Key create table table-name ( column-name1 datatype, …….. column-nameN datatype, [constraint constraint-name] Primary key (columns-name) ); OR create table table-name ( column-name1 datatype [constraint constraint-name] primary key, …….. column-nameN datatype); Lecture4 13
Example create table Department ( Dept_no char(4) PRIMARY KEY, Dept_name varchar2(25)); OR create table Department ( dept_no char(4), Dept_name varchar2(25), CONSTRAINT dept_PK PRIMARY KEY(dept_no)); Lecture4 14
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. Lecture4 15
Integrity Constraints Constraint clauses can appear in the following statements: 1.CREATE TABLE 2.ALTER TABLE 3.CREATE VIEW 4.ALTER VIEW Lecture4 16
The FIFTH types of integrity constraint 1.NOT NULL constraint 2.unique constraint 3.primary key constraint 4.foreign key constraint 5.check constraint Lecture4 17
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 ); Lecture4 18
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) ); Lecture4 19
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 =,. We will have to use the IS NULL and IS NOT NULL operators instead. Lecture4 20
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 ); OR create table table-name ( ……. [constraint constraint-name] UNIQUE (Columns_list) ; Lecture4 21
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) ) Lecture4 22
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. Lecture4 23
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) ; Lecture4 24
Primary key Constraints Example : create table Department ( dept_no char(4), Dept_name varchar2(25), CONSTRAINT dept_PK PRIMARY KEY(dept_no)); Lecture4 25
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) ); Lecture4 26
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)); Lecture4 27
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. Lecture4 28
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. Lecture4 29
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 EmpIdEmpName 1Ali 2Slaut 3John EmpIdDeptNo DeptName 1101 AAA 2101 AAA 3103 CCC FK PK Lecture4 30 EmpIdEmpName 2Slaut 3John EmpIdDeptNo DeptName 2101 AAA 3103 CCC
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=1 EmpMaster EmpDetails parent child EmpIdEmpName 1Ali 2Slaut 3John EmpIdDeptNo DeptName 1101 AAA 2101 AAA 3103 CCC FK PK Lecture4 31 EmpIdEmpName 2Slaut 3John EmpIdDeptNo DeptName NULL101 AAA 2101 AAA 3103 CCC
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. Lecture4 32
Check Constraints Syntax: create table table-name ( column-name1 datatype Check (Check_condition) ); OR create table table-name ( ……. [constraint constraint-name] Check (Check_condition) ); Lecture4 33
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 > )); To allow naming of a CHECK constraint Lecture4 34
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) ); Lecture4 35
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' ) Lecture4 36
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 > ), UNIQUE(staff_name, DateofBirth)); Lecture4 37
Lecture4 38
Modifying Table Definitions Alter table table_name add (column_specification | constraint,..., column_specification| constraint); Alter table table_name modify (column_specification | constraint,..., Column_specification | constraint); Alter table table_name drop column column_name | drop (column_list); Alter table table_name drop primary key; Alter table table_name drop constraint constraint_name; Lecture4 39
Examples alter table orders add (quantity number (3) not null); alter table orders modify (quantity number(5)); alter table orders drop (quantity); Be careful if the table contains data. Lecture4 40
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; Lecture4 41
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; Lecture4 42
Example To DROP a CHECK Constraint ALTER TABLE Persons DROP CONSTRAINT chk_Person; To DROP a FOREIGN KEY Constraint ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders; Lecture4 43
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; Lecture4 44
Lecture4 45
References “Database Systems: A Practical Approach to Design, Implementation and Management.” Thomas Connolly, Carolyn Begg. 5 th Edition, Addison-Wesley, Lecture4 46