0% found this document useful (0 votes)
22 views

SQL - Tables - Constraints

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

SQL - Tables - Constraints

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

DBS211

STRUCTURED QUERY LANGUAGE (SQL)

1
Structured Query Language (SQL)

• Structured Query Language (SQL) is a database language designed for


managing data held in a RDBMS
• SQL Statements:
• SQL Statements are not case sensitive.
• SQL Statements can be on one or more lines.
• Keywords cannot be abbreviated or split across lines.
• Clauses are usually placed on separate lines.
• The order of clauses are important.
• Tabs and indents are used to enhance readability.
• A SQL statement is either completely succeeds or completely fails.
2
SQL Statements
SELECT Data retrieval Retrieves data from the database
SELECT Data manipulation Enters new rows, changes existing rows, and removes
INSERT language (DML) – unwanted rows from tables in the database
UPDATE Create/Insert,
DELETE Read/Select, Update,
Delete (CRUD)
CREATE Data definition Sets up, changes, and removes data structures from tables
ALTER language (DDL)
DROP

COMMIT Transaction Control Manages the changes made by DML statements. Changes to
ROLLBACK Language (TCL) the data can be grouped together into logical transactions.
SAVEPOINT

GRANT Data Control Gives or removes access rights to both the Oracle database
REVOKE Language (DCL) and the structures within it

3
SQL’s Data Definition Language (DDL)
• DDL statements define, modify and remove objects from data
dictionary tables that are maintained by the DBMS

• Whenever you use a DDL statement, the DBMS changes metadata


(“data about data”) maintained in the data dictionary

• Objects that can be defined include: table, view, sequence, index

4
Oracle’s Data Dictionary
• Data dictionary tables maintain data about the structure of databases

• Users cannot directly insert, update or delete information in the data dictionary

• DDL statements cause the DBMS to add/update or delete information in the


data dictionary tables

• Oracle’s data dictionary views such as ALL_OBJECTS, ALL_TABLES,


ALL_CONSTRAINTS can be queried using SELECT statements and contain
information about objects you have access to
5
SQL’s DDL Statements
• Objects are defined using the CREATE statement

• Some objects can be modified using the ALTER statement

• Objects are removed using the DROP statement

• Oracle’s data dictionary views such as USER_OBJECTS,


USER_TABLES, USER_CONSTRAINTS, USER_TAB_COLUMNS,
USER_SEQUENCES, USER_INDEXES can be queried using SELECT
statements and contain information about objects you have created
6
Schema
• The DataBase Administrator (DBA) has set up your Oracle account
with permission for you to create objects in a schema (schema has
same name as your account)

• A schema is a collection of related tables, views, sequences and


indexes, i.e. a database

7
Database Objects
• Table: Basic unit of storage; stores data

• View: Subset of data from one or more tables

• Sequence: Generates primary key values

• Index: Improves the performance of some queries

8
Naming Conventions
• Must begin with a letter

• Can be 128 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

• Must not be an Oracle Server reserved word

• Names are case insensitive 9


CREATE TABLE Statement

CREATE TABLE [schema] table (column datatype [DEFAULT expr]


[ , …]);

CREATE TABLE payments


(customerNumber NUMBER(38,0),
checkNumber VARCHAR(50),
paymentDate DATE,
amount NUMBER(10,2));

10
Tables in the Oracle Database
• User Tables
• Data Dictionary

11
Data Dictionary
• Below are two categories of data dictionary view. Each category has a
distinct prefix which reflects their intended use.

Prefix Description
USER_ These views contain information about objects owned by the user

ALL_ These views contain information about all of the tables accessible to the user

12
Querying the Data Dictionary

• The data dictionary tables frequently used to view


database objects owned by user are:

• USER_TABLES
• USER_OBJECTS
• USER_CATALOG or CAT

13
Querying the Data Dictionary (cont’d)
SELECT *
FROM user_tables;

• View distinct object types owned by the user:


SELECT DISTINCT object_type
FROM user_objects;

• View tables, view, synonyms, and sequences owned by the user


SELECT *
FROM user_catalog;
14
Datatypes

Data type Description


VARCHAR2(size) Variable-length character data (A maximum size must be specified. Default and
VARCHAR(size) minimum size is 1; maximum size is 4000)
CHAR(size) Fixed-length character data of length size bytes (Default and minimum size is 1;
maximum size is 2000)
NUMBER(p,s) Number having precision p and scale s ( The precision is the total number of
decimal digits, and the scale is the number of digits to the right of the decimal
point. The precision can range from 1 to 38

DATE Date and time values between January 1, 4712 B.C. and
December 31, 9999 A.D.
LONG Variable-length character data up to 2 gigabytes

15
Creating a Table by using a Subquery
CREATE TABLE table
[(column, column…)]
AS subquery;
• Match the number of specified columns to the number of subquery columns
CREATE TABLE Payments_bak (customernumber, dateofpayment, amountpaid) AS
SELECT customernumber, paymentdate, amount
FROM payments;

• Create structure of a table based on another table. The new table does not have all constraints
CREATE TABLE Payments_bak (customernumber, dateofpayment, amountpaid) AS
SELECT customernumber, paymentdate, amount
FROM payments
WHERE 0 =1;

INSERT INTO Payments_bak (customernumber, dateofpayment, amountpaid) 16


The ALTER TABLE Statement
• Use the ALTER TABLE statement to:
• Add a new column by using the ADD ALTER TABLE table
clause ADD (column datatype [DEFAULT expr]
[, column datatype] … ) ;
• Modify an existing column by using
the MODIFY clause ALTER TABLE table
MODIFY (column datatype [DEFAULT expr]
[, column datatype] … ) ;
• Define a default value for the new
column ALTER TABLE table
DROP (column);
• Drop a column
ALTER TABLE table
• Rename a column RENAME column old_column TO new_column;

RENAME old_table_name TO new_table_name;


• Rename a table

17
Adding a Column

• You cannot specify where the column is to appear. The new column
becomes the last column

ALTER TABLE payments_bak


ADD RepName VARCHAR(30);

18
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 payments_bak


MODIFY RepName VARCHAR(50);

19
Dropping a Column
• The column may or may not contain data
• The table have at least one column remaining in it after it is altered
• Once a column is dropped, it cannot be recovered

ALTER TABLE payments_bak


DROP COLUMN PaymentDate;

ALTER TABLE payments_bak


DROP (PaymentDate, Amount);

20
Dropping a Table
• Any pending transactions are committed
• All indexes are dropped
• Any views and synonyms will remain but are invalid

DROP TABLE payments_bak;

DROP TABLE payments_bak CASCADE CONSTRAINTS;

21
Constraints Guidlines
• Constraint names - SYS_Cn format

• Create a constraint:
• At the same time as the table is created
• After the table has been created

• Column or table level constraints

• USER_CONSTRAINTS data dictionary table

22
What are constraints?
• Constraints enforce rules at the table level

• Constraints prevents the deletion of a table if there are


dependencies

• The following constraint types are valid in Oracle:


• PRIMARY KEY
• FOREIGN KEY
• UNIQUE
• CHECK
• DEFAULT
• NOT NULL 23
Defining Constraints
• Column constraint level:

column [CONSTRAINT constraint_name] constraint_type

• Table constraint level:

column, …
[CONSTRAINT constraint_name] constraint_type
(column, …),

24
The PRIMARY KEY Constraint
• Primary Key constraints can be defined at the column level or table
level

• A Composite Primary Key is created by using the table level definition

• A UNIQUE index is automatically created for a Primary Key column

25
The PRIMARY KEY Constraint (cont’d)
• The following two statements are equal.

CREATE TABLE REP (


RepNum NUMBER,
Last_Name VARCHAR(15),
First_Name VARCHAR(15),
Commission NUMBER(7, 2),
Rate NUMBER(3, 2),
CONSTRAINT pk_rep PRIMARY KEY(RepNum));

CREATE TABLE REP (


RepNum NUMBER CONSTRAINT pk_rep PRIMARY KEY,
Last_Name VARCHAR(15),
First_Name VARCHAR(15),
Commission NUMBER(7, 2),
26
Rate NUMBER(3, 2));
Composite Primary Key
• Composite Primary key – Primary Key based on multiple columns.

CREATE TABLE inv_detail(


inv_number varchar(3),
product_id varchar(15),
quantity NUMBER(3),
CONSTRAINT pk_invdetail PRIMARY KEY (inv_number, product_id));

27
Alter Table - Primary Key
• Use Alter Table Statement if table already exists.
• When a constraint is added, all existing data are verified for violations.

CREATE TABLE REP (


RepNum NUMBER,
Last_Name VARCHAR(15),
First_Name VARCHAR(15),
Commission NUMBER(7, 2),
Rate NUMBER(3, 2));

• Add Primary Key


ALTER TABLE REP
ADD CONSTRAINT pk_rep PRIMARY KEY(RepNum);

• Drop Primary Key Constraint


ALTER TABLE REP
DROP CONSTRAINT pk_rep; 28
The FOREIGN KEY Constraint
• FOREIGN KEY constraints can be defined at the column or table constraint
level

• ON DELETE CASCADE indicates that when the row in the parent table is
deleted, the dependent rows in the child table will also be deleted

• ON DELETE SET NULL converts foreign key values to null when the
parent value is removed

29
Foreign Key Constraint
• The following two statements are equal.
CREATE TABLE customer (
CustNum NUMBER,
Cust_Name VARCHAR(50),
City VARCHAR(50),
RepNum NUMBER,
CONSTRAINT pk_customer PRIMARY KEY(CustNum),
CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum));

CREATE TABLE customer (


CustNum NUMBER CONSTRAINT pk_customer PRIMARY KEY,
Cust_Name VARCHAR(50),
City VARCHAR(50),
30
RepNum NUMBER CONSTRAINT fk_customer_repnum REFERENCES Rep(RepNum));
Alter Table - Foreign Key
• Add Foreign Key constraint to an existing table.
ALTER TABLE customer
ADD CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum);

ALTER TABLE customer


ADD CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum) ON DELETE CASCADE;

ALTER TABLE customer


ADD CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum) ON DELETE SET NULL;

• Above statement will validate existing column values. The statement will fail if there are any values that
do not exist in the Primary Key of related table.

• Drop Foreign Key Constraint


ALTER TABLE customer
DROP CONSTRAINT fk_customer_repnum; 31
The UNIQUE KEY Constraints

• UNIQUE key constraints allow the input of nulls unless you also
define NOT NULL constraints for the same column(s)

• If more than one column is defined as UNIQUE key, that group of


columns is said to be composite unique key

32
Unique Key Constraint Example
• The following two statements are equal.
CREATE TABLE customer (
CustNum NUMBER,
Cust_Name VARCHAR(50),
City VARCHAR(50),
RepNum NUMBER,
CONSTRAINT pk_customer PRIMARY KEY(CustNum),
CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum) ,
CONSTRAINT uk_custName UNIQUE(cust_name));

CREATE TABLE customer (


CustNum NUMBER CONSTRAINT pk_customer PRIMARY KEY,
Cust_Name VARCHAR(15) CONSTRAINT uk_custName UNIQUE,
City VARCHAR(50),
33
RepNum NUMBER CONSTRAINT fk_customer_repnum REFERENCES Rep(RepNum));
Alter Table - Unique Key Constraint

• Add Unique constraint to an existing table.


ALTER TABLE customer
ADD CONSTRAINT uk_custName UNIQUE(cust_name);

• Drop Unique Key Constraint


ALTER TABLE customer
DROP CONSTRAINT uk_custName;

34
Check Constraint Example
• The following two statements are equal.
CREATE TABLE customer (
CustNum INTEGER,
Cust_Name VARCHAR(50),
City VARCHAR(50),
RepNum INTEGER,
CONSTRAINT pk_customer PRIMARY KEY(CustNum),
CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum),
CONSTRAINT uk_custName UNIQUE(cust_name),
CONSTRAINT ck_customer_city CHECK(City IN ('Toronto', 'Ottawa')));

CREATE TABLE customer (


CustNum INTEGER CONSTRAINT pk_customer PRIMARY KEY,
Cust_Name VARCHAR(15) CONSTRAINT uk_custName UNIQUE,
City VARCHAR(50) CONSTRAINT ck_customer_city CHECK(City IN ('Toronto', 'Ottawa')),
35
RepNum INTEGER CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum));
Alter Table – Check Constraint

• Add Check constraint to an existing table.


ALTER TABLE customer
ADD CONSTRAINT ck_customer_city CHECK(City IN ('Toronto', 'Ottawa'));

• Drop Check Constraint


ALTER TABLE customer
DROP CONSTRAINT ck_customer_city;

36
The DEFAULT Constraint
• Specify a default value for a column during an insert
• The default data type must match the column datatype
CREATE TABLE customer (
CustNum NUMBER, Cust_Name VARCHAR(50),
City VARCHAR(50) DEFAULT 'Toronto',
RepNum NUMBER,
CONSTRAINT pk_customer PRIMARY KEY(CustNum),
CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum),
CONSTRAINT uk_custName UNIQUE(cust_name),
CONSTRAINT ck_customer_city CHECK(City IN ('Toronto', 'Ottawa')));

• Add/remove DEFAULT Constraint from/to an existing table


ALTER TABLE customer
MODIFY cust_name DEFAULT 'Toronto’;

ALTER TABLE customer


37
MODIFY cust_name DEFAULT NULL;
The NOT NULL Constraint
• Can be specified only at the column level, not at the table level
CREATE TABLE customer (
CustNum NUMBER,
Cust_Name VARCHAR(50) customer_custname_nn NOT NULL,
City VARCHAR(50) DEFAULT 'Toronto',
RepNum NUMBER,
CONSTRAINT pk_customer PRIMARY KEY(CustNum),
CONSTRAINT fk_customer_repnum FOREIGN KEY(RepNum) REFERENCES Rep(RepNum),
CONSTRAINT uk_custName UNIQUE(cust_name),
CONSTRAINT ck_customer_city CHECK(City IN ('Toronto', 'Ottawa')));

• Add/remove NOT NULL to/from an existing table


ALTER TABLE customer
MODIFY cust_name NOT NULL;

ALTER TABLE customer


38
MODIFY cust_name NULL;

You might also like