8 - Introduction To SQL 10-23-2024
8 - Introduction To SQL 10-23-2024
1
History of Structured Query
Language
SQL was first implemented in IBM’s System R
in the late 1970’s.
SQL is the de-facto standard query language
for creating and manipulating data in
relational databases.
Some minor syntax differences, but the
majority of SQL is standard across MS Access,
MS SQL Server, Oracle, Sybase, MySQL,
Postgres, Informix, etc.
SQL is either specified by a command-line tool
or is embeddedinto a general purpose
programming language such as Cobol, “C”,
Pascal, Java, C++, etc.
Objectives of SQL
SQL is relatively easy to learn:
6
SQL Numeric Data Types
Integers: INTEGER (INT) or SMALLINT
Integer: 4 bytes
Smallint: 2 bytes
Real ints: FLOAT, REAL, DOUBLE, PRECISION
Formatted ints: DECIMAL(i,j), NUMERIC(i,j)
SQL Character String Data Types
Two main types: Fixed length and variable length.
Fixed length of n characters: CHAR(n) or
CHARACTER(n)
Variable length up to size n: VARCHAR(n)
Literals
All non-numeric literals must be enclosed in
single quotes (e.g. ‘London’).
9
SQL Date and Time Data Types
Implementations vary widely for these data types.
DATE: Has 10 positions in the format: YYYY-MM-DD
TIME: Has 8 positions in the format: HH:MM:SS
TIME(i): Defines the TIME data type with an additional i positions
for fractions of a second.
For example:HH:MM:SS:dd
Offset from UTZ. +/- HH:MM
TIMESTAMP: Records an instant in time using full date and time
with fractions of sections.
INTERVAL: Used to specify some span of time measured in days or
minutes, etc.
Other ways of expressing dates:
Store as characters or integers with Year, Month Day:19972011
Store as Julian date:1997283
MS Access, SQL Server and Oracle store date and time information
together in a DATE or Date/Time data type.
10
Examples of SQL Data Types for
Some Popular RDBMS
Data Type Storage Size Range of Values
Byte 1 byte 0 to 255
Data types Boolean 2 bytes True or False.
12
Structured Query Language (SQL)
Data Definition Language
DDL is used to define the schema of the
database.
Create a database schema
Create, Drop or Alter a table
Create or Drop an Index
Define Integrity constraints
Define access privileges to users
Define access privileges on objects
SQL2 specification supports the creation of
multiple schemas per database each with a
distinct owner and authorized users.
13
CREATE TABLE
CREATE TABLE TableName
{(colName dataType [NOT NULL]
[UNIQUE]
[DEFAULT defaultOption]
[CHECK searchCondition] [,...]}
[PRIMARY KEY (listOfColumns),]
{[UNIQUE (listOfColumns),] […,]}
{[FOREIGN KEY (listOfFKColumns)
REFERENCES ParentTableName
[(listOfCKColumns)],
[ON UPDATE referentialAction]
[ON DELETEPearson
referentialAction
Education © 2014
]] [,…]} 14
1..1 1..*
Department Employees
15
Creating a Schema
Creating a Table:
CREATE TABLE employee (
employeeid VARCHAR(10) NOT NULL,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(18) NOT NULL,
soc_sec VARCHAR(11) NOT NULL,
date_of_birth DATE,
salary int,
departmentid int
);
CREATE TABLE department (
departmentid int NOT NULL,
department_name VARCHAR(30) NOT NULL,
department_location VARCHAR(30)
);
16
IEF - Entity Integrity
Primary key of a table must contain a unique,
non-null value for each row.
ISO standard supports FOREIGN KEY clause in
CREATE and ALTER TABLE statements:
PRIMARY KEY(staffNo)
PRIMARY KEY(clientNo, propertyNo)
UNIQUE(telNo) 17
IEF - Referential Integrity
FK is column or set of columns that links each
row in child table containing foreign FK to row
of parent table containing matching PK.
Referential integrity means that, if FK contains
a value, that value must refer to existing row
in parent table.
ISO standard supports definition of FKs with
FOREIGN KEY clause in CREATE :
18
Creating a Schema with primary
key (1)
Creating a Table:
CREATE TABLE employee (
employeeid VARCHAR(10) NOT NULL,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(18) NOT NULL,
soc_sec VARCHAR(11) NOT NULL,
date_of_birth DATE,
salary int,
departmentid int,
PRIMARY KEY (employeeid),
FOREIGN KEY (departmentid) REFERENCES department (departmentid)
);
CREATE TABLE department (
departmentid int NOT NULL,
department_name VARCHAR(30) NOT NULL,
department_location VARCHAR(30),
PRIMARY KEY (departmentid)
);
19
Creating a Schema with primary
key (2)
Creating a Table:
CREATE TABLE employee ( Adding primary key :
employeeid VARCHAR(10) NOT NULL, ALTER TABLE department
last_name VARCHAR(20) NOT NULL, ADD CONSTRAINT pk_department
first_name VARCHAR(18) NOT NULL, PRIMARY KEY (departmentid);
soc_sec VARCHAR(11) NOT NULL,
date_of_birth DATE, Adding primary key :
salary int, ALTER TABLE employee
departmentid int ADD CONSTRAINT pk_employee
); PRIMARY KEY (employeeid)
CREATE TABLE department (
departmentid int NOT NULL,Adding foreign key:
department_name ALTER TABLE employee
VARCHAR(30) NOT NULL,
department_location VARCHAR(30) ADD CONSTRAINT fk_employee
); FOREIGN KEY (departmentid)
REFERENCES department (departmentid)
20
21
Specifying Primary and Foreign
keys
CREATE TABLE order_header (
order_Number int NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
CONSTRAINT pk_order_header PRIMARY KEY (order_Number)
);
24
Examples of ON DELETE and ON
UPDATE.
CREATE TABLE order_items (
order_Number int NOT NULL,
line_item int NOT NULL,
part_Number VARCHAR(12) NOT NULL,
quantity int,
CONSTRAINT pk_order_items PRIMARY KEY
(order_Number, line_item),
CONSTRAINT fk_order_items FOREIGN KEY
(order_Number) REFERENCES order_header
(order_Number)
ON DELETE SET NULL
);
25Or adding ON UPDATE CASCADE
0..*
1..1
Parts
Part_Number
26
Assuming we have a “Parts” table
CREATE TABLE parts (
part_Number VARCHAR(12) NOT
NULL,
part_description VARCHAR(25) ,
part_price int,
CONSTRAINT pk_parts
PRIMARY KEY (part_Number)
);
27
Adding constraints:
CREATE TABLE order_items (
order_Number int NOT NULL,
line_item int NOT NULL,
part_Number VARCHAR(12) NOT NULL,
quantity int,
CONSTRAINT pk_order_items
PRIMARY KEY (order_Number,
line_item),
CONSTRAINT fk1_order_items
FOREIGN KEY (order_Number)
REFERENCES order_header
(order_Number)
ON DELETE SET NULL,
CONSTRAINT fk2_order_items
FOREIGN KEY (part_Number)
REFERENCES parts (part_Number)
ON DELETE SET NULL
);
28
Adding Constraints Later
CREATE TABLE order_header (
order_Number int NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10)
);
29
CREATE TABLE order_items (
order_Number int(10,0) NOT NULL,
line_item int(4,0) NOT NULL,
part_Number VARCHAR(12) NOT NULL,
quantity int(4,0)
);
31
Exercise: Create Customer and
order Tables
Tables Names Data types Constraints
customer customerID int NOT NULL,
PRIMARY
Name VARCHAR(20) NOT NULL
AGE INT NOT NULL
Address CHAR(25)
Salary int
32
ALTER TABLE
Add a new column to a table.
ALTER TABLE table_name
ADD column_name datatype;
Drop a column from a table.
ALTER TABLE "table_name" DROP "column_name";
Add a new table constraint (a primary key).
ALTER TABLE order_header
ADD CONSTRAINT pk_order_header
PRIMARY KEY (order_Number);
Drop a table constraint.
ALTER TABLE employee
DROP CONSTRAINT fk_department;
33
Customer table
Step1 :
CREATE TABLE customer (
customer_id int NOT NULL
CONSTRAINT pk_customer PRIMARY KEY,
name VARCHAR(20) NOT NULL,
age INT,
address CHAR(25),
salary int
);
Step 2: Adding foreign key to order_header table
a. Add customer_id column
ALTER TABLE order_header
ADD COLUMN customer_id int;
b. Add foreign key
ALTER TABLE order_header
ADD CONSTRAINT fk_order_header FOREIGN KEY (customer_id)
REFERENCES customer(customer_id)
ON DELETE SET NULL;
34
Removing Schema Components
with DROP
DROP SCHEMA schema_name CASCADE
Drop the entire schema including all tables. CASCADE option
deletes all data, all tables, indexes, domains, etc.
DROP SCHEMA schema_name RESTRICT
Removes the schema only if it is empty.
DROP TABLE table_name
Remove the table and all of its data.
DROP TABLE table_name CASCADE
Remove the table and all related tables as specified by FOREIGN
KEY constraints.
DROP TABLE table_name RESTRICT
Remove the table only if it is not referenced (via a FOREIGN KEY
constraint) by other tables.
DROP INDEX index_name
Removes an index.
DROP CONSTRAINT table_name.constraint_name
Removes a constraint from a table.
35
Changing Schema Components
with ALTER
Changing Column data type:
ALTER TABLE student ALTER last_name
VARCHAR(35);
Dropping a default value:
ALTER TABLE student ALTER gpa DROP DEFAULT
Adding a new default value to a column:
ALTER TABLE student ALTER gpa SET DEFAULT
0.00;
Adding Attributes/Columns to an existing
table:
ALTER TABLE student ADD admission DATE;
Removing Attributes (not widely
implemented):
36
Practice 1
Tables Columns Datatype Constraints
order_header order_Number int(10,0) NOT NULL, primary key
order_date DATE
sales_person VARCHAR(25)
bill_to VARCHAR(35)
bill_to_address VARCHAR(45)
bill_to_city VARCHAR(20)
bill_to_state VARCHAR(2)
bill_to_zip VARCHAR(10)
order_items order_Number int(10,0) NOT NULL, primary key
line_item int(4,0) NOT NULL
part_Number VARCHAR(12) NOT NULL
quantity int(4,0)
part part_Number VARCHAR(12) NOT NULL primary
part_description VARCHAR(25) x
part_price int
37
Adding Constraints Later
DROP TABLE order_header ;
38
CREATE TABLE order_items (
order_Number int(10,0) NOT NULL,
line_item int(4,0) NOT NULL,
part_Number VARCHAR(12) NOT NULL,
quantity int(4,0)
);