0% found this document useful (0 votes)
49 views40 pages

8 - Introduction To SQL 10-23-2024

SQL, developed in the late 1970s, is the standard language for managing relational databases, with a consistent syntax across various platforms. It consists of two main components: Data Definition Language (DDL) for defining database structures and Data Manipulation Language (DML) for handling data. SQL supports various data types, constraints, and integrity rules to ensure accurate and efficient data management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views40 pages

8 - Introduction To SQL 10-23-2024

SQL, developed in the late 1970s, is the standard language for managing relational databases, with a consistent syntax across various platforms. It consists of two main components: Data Definition Language (DDL) for defining database structures and Data Manipulation Language (DML) for handling data. SQL supports various data types, constraints, and integrity rules to ensure accurate and efficient data management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Lecture 8: SQL

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:

 it is non-procedural - you specify what information


you require, rather than how to get it;
 it is essentially free-format.
 Consists of standard English words:
1) CREATE TABLE Staff(staffNo VARCHAR(5),
lName VARCHAR(15),
salary DECIMAL(7,2));
2) INSERT INTO Staff VALUES (‘SG16’, ‘Brown’, 8300);
3) SELECT staffNo, lName, salary
FROM Staff
WHERE salary > 10000;
3
History of Structured Query
Language

 SQL is a standardized language monitored by


the American National Standards Institute
(ANSI) as well as by National Institute of
Standards (NIST).
 ANSI 1990 – SQL 1 standard
 ANSI 1992 – SQL 2 Standard (sometimes called
SQL-92)
 ANSI 1999 – SQL 1999 – adds regular expressions,
triggers, some Object oriented concepts
 ANSI 2003 – SQL 2003 – XML features,
autogenerated data (e.g., autoint)
 ANSI 2006 – SQL 2006 – Further XML Integration
using XQuery, XPath, etc.
Components of SQL
 SQL has two major parts:
 Data Definition Language (DDL)
 – Used to create (define) data structures such as tables,
indexes, clusters
 Data Manipulation Language (DML)
 – Used to insert, update, delete and retrieve (select)
data from tables.
Structured Query Language (SQL)
Data Types
 When creating tables in a database schema,
we need to specify the data type for each
column of the table.
 For example, if we need to store a salary or a
date of birth, we need to choose the right data
type that is supported by our target DBMS.
 Each vendor’s implementation of SQL uses
slightly different names for the data types.

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’).

 All numeric literals must not be enclosed in


quotes (e.g. 650.00).

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.

most often Integer


Long (long integer)
2 bytes
4 bytes
-32,768 to 32,767.
-2,147,483,648 to

used are 2,147,483,647.


-3.402823E38 to -1.401298E-
45 for negative values;
shown Single(single-precision
floating-point)
4 bytes 1.401298E-45 to
3.402823E38 for
in Bold positive values.
-1.79769313486232E308 to -
letters 4.94065645841247E-324 for
Double (double- negative values;
8 bytes
precision floating-point) 4.94065645841247E-324 to
1.79769313486232E308 for
positive values.
-922,337,203,685,477.5808
Currency (scaled
8 bytes to
integer)
922,337,203,685,477.5807.
January 1, 100 to December
Date 8 bytes
31, 9999.
Object 4 bytes Any Object reference.
0 to approx. 2 billion (approx.
10 bytes + string
String (variable-length) 65,400 for MS Windows
length
version 3.1).
String (fixed-length) Length of string 1 to approximately 65,400.
11 Any numeric value up to the
Variant (with ints) 16 bytes
range of a Double.
Oracle supports the following data
types:
 Numeric: BINARY_NumberEGER, DEC,
DECIMAL, DOUBLE PRECISION, FLOAT, INT,
INTEGER, NATURAL, NATURALN, int, NUMERIC,
PLS_NumberEGER, POSITIVE, POSITIVEN,
REAL, SMALLINT
 Date: DATE Note: Also stores time.
 Character: CHAR, CHARACTER, STRING,
VARCHAR, VARCHAR2
 Others: BOOLEAN, LONG, LONG RAW, RAW

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)

 Can only have one PRIMARY KEY clause per


table. Can still ensure uniqueness for
alternate keys using UNIQUE:

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 :

FOREIGN KEY(branchNo) REFERENCES Branch


(column_name)

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

CREATE TABLE order_items (


order_Number int NOT NULL,
line_item int NOT NULL,
part_Number VARCHAR(12) NOT NULL,
quantity int,
price int,
CONSTRAINT pk_order_items PRIMARY KEY (order_Number, line_item),
CONSTRAINT fk_order_items FOREIGN KEY (order_Number)
REFERENCES order_header (order_Number)
); 22
Specifying Constraints on Columns
and Tables
 We apply constraints on columns so that we
can ensure good data is added into the
database and the amount of NULL values is
minimized
 Constraints on Columns:
 NOT NULL – Attribute may not take a NULL value
 DEFAULT – Store a given default value if no value is
specified
 PRIMARY KEY – Indicate which column(s) form the
primary key
 FOREIGN KEY – Indicate which column(s) form a
foreign key. This enforces referential integrity
 UNIQUE – Indicates which column(s) must have
23
unique values.
Referential Integrity Constraint:
 Specify the behavior for child tuples when a
parent tuple is modified.
 Action to take if referential integrity is
violated:
 SET NULL – Child tuples foreign key is set to NULL
– Orphans.
 SET DEFAULT – Set the value of the foreign key to
some default value.
 CASCADE – Child tuples are updated (or deleted)
according to the action take on the parent tuple.

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

ALTER TABLE order_header


ADD CONSTRAINT pk_order_header
PRIMARY KEY (order_Number);

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

ALTER TABLE order_items ADD


CONSTRAINT pk_order_items
PRIMARY KEY (order_Number, line_item) ;

ALTER TABLE order_items ADD


CONSTRAINT fk1_order_items
FOREIGN KEY (order_Number)
REFERENCES order_header (order_Number)
ON DELETE SET NULL;

ALTER TABLE order_items ADD


CONSTRAINT fk2_order_items
FOREIGN KEY (part_Number)
REFERENCES parts (part_Number)
ON DELETE SET NULL; (on delete no action/ on delete restrict
leave it unchanged!)
30
Creating indexes on table columns
 To speed up retrieval of orders given
order_Number:
 CREATE INDEX idx_order_Number ON
order_header (order_Number) ;
 To speed up retrieval of orders given sales
person:
 CREATE INDEX idx_sales_person ON
order_header (sales_person) ;
 We give the first part of the index name as
“idx” just as a convention.

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

1. Drop all tables


2. For Order_Item table:
Foreign key:order_Number on delete SET NULL
Foreign key 2: part int ON DELETE SET NULL;

37
Adding Constraints Later
DROP TABLE order_header ;

CREATE TABLE order_header (


order_Number int(10,0) 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)
);
ALTER TABLE order_header
ADD CONSTRAINT pk_order_header
PRIMARY KEY (order_Number);

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

ALTER TABLE order_items ADD


CONSTRAINT pk_order_items
PRIMARY KEY (order_Number, line_item) ;

ALTER TABLE order_items ADD


CONSTRAINT fk1_order_items
FOREIGN KEY (order_Number)
REFERENCES order_header (order_Number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE;

ALTER TABLE order_items ADD


CONSTRAINT fk2_order_items
FOREIGN KEY (part_Number)
REFERENCES parts (part_Number)
ON DELETE SET DEFAULT
39 ON UPDATE CASCADE;
Practice 1
1..1 1..1
Bike Rental Customer
1..* 1..*

Tables Columns Date Types Constraints


Bike Bike_id int (10,0) NOT NULL, primary
Description Varchar(250) key
Cost_per_hour int
Customer DriverLicence Varchar(250) NOT NULL, primary
Lname Varchar(250) key
Fname Varchar(250)
Address Varchar(250)
City Varchar(250)
State Varchar(250)
Zip Varchar(250)
Telephone Varchar(250)
Credit_card_no int
Rental Driver_license Varchar(150) NOT NULL, primary
Date Date key
Bike_id int NOT NULL, primary
Time_out Date key
Time_in Datetime NOT NULL, primary
40 key
NOT NULL

You might also like