Chapter4 Session1
Chapter4 Session1
1 Introduction to SQL
2 DDL Statements
2
Introduction to SQL
3
History of SQL
1970–Edgar E. Codd develops relational database
concept
1974-1979–System R with Sequel (later SQL)
created at IBM Research Lab
1979–Oracle markets first relational DB with SQL
1986–ANSI (American National Standards Institue)
SQL standards were first published
1989, 1992, 1999, 2003, 2006, 2008, 2011 and
2016–Major ANSI standard updates
Current–SQL is supported by most major database
vendors
4
Purpose of SQL Standard
Specify syntax/semantics for data definition and
manipulation
Define data structures
Enable portability
Specify minimal (level 1) and complete (level 2)
standards
Allow for later growth/enhancement to standard
5
Benefits of a Standardized
Relational Language
Reduced training costs
Productivity
Application portability
Application longevity
Reduced dependence on a single vendor
Cross-system communication
6
SQL Commands
3 types:
SQL commands
8
Creating a database
Two tasks must be completed:
create the database structure
create the tables that will hold the end-user data
First task
RDBMS creates the physical files that will hold the
database
Tends to differ substantially from one RDBMS to another
9
Creating a database
A SQL Server database can be created, altered
and dropped by one of two following methods:
Using the designer with SQL Server Management Studio
(SSMS) or
Using a Query
After creating database, 2 files are generated:
.MDF file – Data file (contains actual data)
.LDF file _ Transaction Log file ( used to recover the
database)
10
Creating a new database
1. Using designer:
Right-click to Database
menu, choose New Database
Example:
2. Use Query
Syntax:
USE DatabaseName
Example
USE DemoShopping
Example:
DROP DATABASE DemoShopping2
Ex:
ExampleCREATE
(For most RDBMS,AUTHORIZATION
SCHEMA it is optional) vku
14
Some Common SQL Data
Types
Some Common SQL Data
Types
Exact numeric data types:
Some Common SQL Data
Types
Approximate numeric data types:
The approximate numeric data type stores floating
point numeric data. They are often used in
scientific calculations.
Some Common SQL Data
Types
Date & Time data types
Some Common SQL Data
Types
Character strings data types
Character strings data types allow you to store either fixed-
length (char) or variable-length data (varchar).
CONSTRAINTS
DEFAULT
UNIQUE
SQL Constraints
Primary Key Constraints
Is a way to enforce Entity Integrity
Ensures that values in a primary key column are unique and
not null.
A primary key can be one column or combination of columns
Foreign key Constraints
Is a way to enforce Referential integrity
Ensures that if the foreign key contains a value, that value
must refer to an existing value in the parent table.
The parent table in such a parent–child relationship should be
created first so that the child table will reference an existing
parent table when it is created
23
SQL constraints
NOT NULL constraint
Ensures that a column does not accept nulls
UNIQUE constraint
Ensures that all values in a column are unique
you can have many UNIQUE constraints per table, but
only one PRIMARY KEY constraint per table.
DEFAULT constraint
Assigns a value to an attribute when a new row is added
to a table
CHECK constraint
is a kind of domain integrity
Validates data when an attribute value is entered
24
Creating a Table with
foreign key constraint
Example:
25
The Vendor and Product
tables
Vendor table
Product table
26
The Database Model
Example
27
The Database Model
The database model reflects the following business
rules:
A customer may generate many invoices. Each invoice is
generated by one customer.
An invoice contains one or more invoice lines. Each invoice
line is associated with one invoice.
Each invoice line references one product. A product may be
found in many invoice lines.
A vendor may supply many products. Some vendors do not
yet supply products.
If a product is vendor-supplied, it is supplied by only a single
vendor.
Some products are not supplied by a vendor.
28
Creating a table
Creating a simple table using syntax:
30
Creating a table with
primary CREATE
keyTABLE
constraint
Vendor (
Example: V_Code INT PRIMARY KEY,
V_Name VARCHAR(35) NOT NULL,
V_Contact VARCHAR(15) NOT
NULL,
V_AreaCode CHAR(3) NOT NULL,
V_Phone CHAR(8) NOT NULL,
Or V_State CHAR(2) NOT NULL,
V_Order CHAR(1) NOT NULL
)
CREATE TABLE Vendor (
V_Code INT NOT NULL,
V_Name VARCHAR(35) NOT NULL, Primary keys can
V_Contact VARCHAR(15) NOT NULL, never have NULL
V_AreaCode CHAR(3) NOT NULL, values
V_Phone CHAR(8) NOT NULL,
V_State CHAR(2) NOT NULL,
V_Order CHAR(1) NOT NULL,
CONSTRAINT PK_Vendor PRIMARY KEY
(V_Code)
) 31
Creating a Table with
foreign key constraint
Syntax
32
Creating a Table with
foreign key constraint
CREATE TABLE Vendor (
Example V_Code INT NOT NULL,
…
Primary key of V_Order CHAR(1) NOT NULL,
parent table CONSTRAINT PK_Vendor PRIMARY
KEY(V_CODE)
)
CREATE TABLE Product (
P_Code VARCHAR(10) NOT NULL,
P_Descript VARCHAR(35) NOT NULL,
P_InDate DATE NOT NULL,
P_QOH INT NOT NULL,
P_Min INT NOT NULL,
P_Price DECIMAL(8,2) NOT NULL,
P_Discount DECIMAL(8,2) NOT NULL,
V_Code INT NULL,
CONSTRAINT PK_Product PRIMARY KEY Foreign key of
(P_Code),
child_table
CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES Vendor) 33
Foreign key constraint
with Delete and Update
rules
DELETE AND UPDATE rules in SQL Server foreign key can
be use with the following options:
NO ACTION (the default)
Error message would be generated, and no action is performed
CASCADE
if the parent record is deleted/updated, associated records in
child table are also deleted/updated.
SET NULL
if the parent record is deleted/updated, associated records in
child table are set to null
Foreign key column should allow NULL values
SET DEFAULT
if the parent record is deleted/updated, associated records in
child table are set to default value specified in column
definition.
Also default value should be present in primary key column.
Foreign key constraint
with Delete and Update
Example
rules
CREATE TABLE Product (
P_Code VARCHAR(10) NOT NULL,
P_Descript VARCHAR(35) NOT NULL,
P_InDate DATE NOT NULL,
P_QOH INT NOT NULL,
P_Min INT NOT NULL,
P_Price DECIMAL(8,2) NOT NULL,
P_Discount DECIMAL(8,2) NOT NULL,
V_Code INT NULL,
CONSTRAINT PK_Product PRIMARY KEY
(P_Code),
CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES
ON UPDATE CASCADE specification ensures that if you make a change in
Vendor
any V_CODE in VENDOR table ON
thatUPDATE
will result in that value changing in the
CASCADE
PRODUCT table )to match.
35
Creating a table with
DEFAULT, CHECK, UNIQUE
constraint
Example: CUSTOMER table
CREATE TABLE Customer (
CUS_Code INT PRIMARY KEY,
CUS_Lname NVARCHAR(30) NOT NULL,
CUS_Fname NVARCHAR(30) NOT NULL,
CUS_Initial CHAR(1),
CUS_AreaCode CHAR(3)
DEFAULT '615' NOT NULL
CHECK(CUS_AreaCode
IN('615','713','931')),
CUS_Phone CHAR(8) NOT NULL,
CUS_Balance DECIMAL DEFAULT 0.00,
CONSTRAINT UQ_CUS_LName_FName
UNIQUE (CUS_Lname, CUS_Fname)
)
36
Creating a table with
constraints
Invoice table
the DEFAULT constraint assigns a default date to a new
invoice
the CHECK constraint validates that the invoice date is
greater than January 1, 2016
CREATE TABLE Invoice (
INV_Number INT PRIMARY KEY,
CUS_CodeINT NOT NULL,
INV_Date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT FK_Inv_Cus_CusCode FOREIGN KEY(CUS_Code)
REFERENCES Customer,
CONSTRAINT CK_INVDate CHECK (INV_Date > '2016-01-01')
)
37
Creating a table with
constraints
Invoice table has
a composite primary key (INV_NUMBER, LINE_NUMBER)
a UNIQUE constraint
in INV_NUMBER and P_CODE to ensure that the same
product is not ordered twice in the same invoice.
CREATE TABLE Line ( Some primary keys are composite–
INV_Number INTEGER NOT NULL, composed of multiple attributes
LINE_Number NUMERIC(2,0) NOT NULL,
P_Code VARCHAR(10) NOT NULL,
LINE_Units DECIMAL(9,2) DEFAULT 0.00 NOT NULL,
LINE_Price DECIMAL(9,2) DEFAULT 0.00 NOT NULL,
PRIMARY KEY (INV_Number,LINE_Number),
FOREIGN KEY (INV_Number) REFERENCES Invoice ON DELETE
CASCADE,
FOREIGN KEY (P_Code) REFERENCES Product(P_Code),
CONSTRAINT UQ_Line UNIQUE(INV_Number, P_Code))
38
Altering a table
Use ALTER TABLE statement is used to
To add a column to an existing table:
ALTER TABLE table_name
ADD column_name datatype
42
Removing a table
Example:
43
Auto-increment
Auto-increment allows a unique number to be
generated automatically when a new record is
inserted into a table.
Often this is the primary key field that we would like
to be created automatically every time a new record
is inserted.
Auto-increment
To create an identity column for a table:
seed is the value of the first row loaded into the table.
increment is the incremental value added to the identity
value of the previous row.
The default value of seed and increment is 1.
Example:
CREATE TABLE Employee
(
Emp_ID int PRIMARY KEY IDENTIY(1,1),
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
)
Exercises
Ex1: Create the following tables (Employee,
Department)
Use Auto-increment
apply 4 rules: No action, Cascade, set null, set default.
46
Exercises
Ex2: Create a database scheme that consists of four
tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)
Exercises
Ex3: Create a database named BookDB
Use the SQL statements to create the tables: Books
(BookID, BookTitle, CopyRight, Year), Authors (AuthorID,
AuthorFName, AuthorMName, AuthorLName,
DateOfBirth, Gender, Address) and AuthorBook
(BookID, AuthorID)
Set the constraints for the tables
48
INSERT Statement
INSERT command is used to enter data into a table.
Example:
INSERT
Note for INSERT
INTO statement
Vendor
The row contents are entered between parentheses
(V_Code,V_Name,V_Contact,V_AreaCode,V_Phone,V_State,V_Order)
Character (string) and date values must be entered between apostrophes ( ’ ).
VALUES(21225,'Bryson, Inc.','Smithson','615','223-
Numerical entries are not enclosed in apostrophes.
3234','TN','Y')
Attribute entries are separated by commas.
A value is required for each column in the table.
49
INSERT Statement
You do not need to specify the column (s) name if you are adding
values for all the columns of the table. However, make sure the
order of the values is in the same order as the columns in the table.
Inserting Rows with Null Attributes with NULL keyword when all the
INSERT values
attribute INTO Vendor
must beVALUES(21225,'Bryson,
specified
Inc.','Smithson','615','223-3234','TN','Y')
50
INSERT Statement
Inserting Rows with Optional Attributes
Rather than declaring each attribute as NULL in the INSERT command, you can indicate just the attributes
that have required values.
Example: assume that the only required attributes for the PRODUCT table are P_Code and P_Descript
52
INSERT Statement
SQL Server automatically uses the following value
for the column that is available in the table but does
not appear in the column list of the INSERT
statement:
The next incremental value if the column has an IDENTITY
property.
The default value if the column has a default value specified.
The NULL if the column is nullable
The calculated value if the column is a computed column.
The current timestamp value if the data type of the column is
a timestamp data type
53
INSERT Statement
Any changes made to the table contents are not
physically saved on disk until
Database is closed
Program is closed
COMMIT command is used
Saving table changes by
COMMIT;
Will permanently save any changes (such as rows added,
attributes modified, and rows deleted) made to any table
in the database
54
The content of Product
table
Update statement
The UPDATE statement is used to modify the
existing records in a table.
UPDATE Product
SET P_InDate = '01-18-2016', P_Price = 17.99, P_Min =
10
WHERE P_CODE = '13-Q2/P2'
62