Chapter4 Session1
Chapter4 Session1
1 Introduction to SQL
2 DDL Statements
2
Introduction to SQL
3
History of SQL
q1970–Edgar E. Codd develops relational database
concept
q1974-1979–System R with Sequel (later SQL)
created at IBM Research Lab
q1979–Oracle markets first relational DB with SQL
q1986–ANSI (American National Standards Institue)
SQL standards were first published
q1989, 1992, 1999, 2003, 2006, 2008, 2011 and
2016–Major ANSI standard updates
qCurrent–SQL is supported by most major database
vendors
4
Purpose of SQL Standard
qSpecify syntax/semantics for data definition and
manipulation
qDefine data structures
qEnable portability
qSpecify minimal (level 1) and complete (level 2)
standards
qAllow for later growth/enhancement to standard
5
Benefits of a Standardized
Relational Language
qReduced training costs
qProductivity
qApplication portability
qApplication longevity
qReduced dependence on a single vendor
qCross-system communication
6
SQL Commands
q 3 types:
SQL commands
8
Creating a database
qTwo tasks must be completed:
§ create the database structure
§ create the tables that will hold the end-user data
qFirst task
§ RDBMS creates the physical files that will hold the
database
§ Tends to differ substantially from one RDBMS to another
9
Creating a database
qA 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
qAfter 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:
§ Example:
ALTER DATABASE DemoShopping MODIFY NAME = DemoShopping2
§ Example:
DROP DATABASE DemoShopping2
qEx:
CREATE SCHEMA AUTHORIZATION vku
14
Some Common SQL Data
Types
Some Common SQL Data
Types
qExact numeric data types:
Some Common SQL Data
Types
qApproximate 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
qDate & Time data types
Some Common SQL Data
Types
qCharacter 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
qPrimary 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
qForeign 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
qNOT NULL constraint
§ Ensures that a column does not accept nulls
qUNIQUE 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.
qDEFAULT constraint
§ Assigns a value to an attribute when a new row is added
to a table
qCHECK constraint
§ is a kind of domain integrity
§ Validates data when an attribute value is entered
24
Creating a Table with foreign
key constraint
qExample:
25
The Vendor and Product tables
Vendor table
Product table
26
The Database Model
qExample
27
The Database Model
qThe 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
qCreating a simple table using syntax:
30
Creating a table with primary
key constraint
CREATE TABLE Vendor (
V_Code INT PRIMARY KEY,
qExample: V_Name VARCHAR(35) NOT NULL,
V_Contact VARCHAR(15) NOT NULL,
V_AreaCode CHAR(3) NOT NULL,
V_Phone CHAR(8) NOT NULL,
V_State CHAR(2) NOT NULL,
qOr V_Order CHAR(1) NOT NULL
)
32
Creating a Table with foreign
key constraint
CREATE TABLE Vendor (
qExample 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 (P_Code), Foreign key of
CONSTRAINT FK_Product_Vendor_Vcode
child_table
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:
qNO ACTION (the default)
§ Error message would be generated, and no action is performed
qCASCADE
§ if the parent record is deleted/updated, associated records in
child table are also deleted/updated.
qSET NULL
§ if the parent record is deleted/updated, associated records in
child table are set to null
§ Foreign key column should allow NULL values
qSET 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 rules
CREATE TABLE Product (
qExample 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 Vendor
ON UPDATE CASCADE
)
36
Creating a table with
constraints
qInvoice 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
qInvoice 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
qUse ALTER TABLE statement is used to
§ To add a column to an existing table:
ALTER TABLE table_name
ADD column_name datatype
§ To drop a column
ALTER TABLE table_name
DROP COLUMN column_name
Altering a table
qUse ALTER TABLE statement is also used to
§ To add a constraint to an existing table:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type syntax
§ To remove a constraint
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
42
Removing a table
qExample:
DROP TABLE Table_name [RESTRIC|CASCADE]
43
Auto-increment
qAuto-increment allows a unique number to be
generated automatically when a new record is
inserted into a table.
qOften this is the primary key field that we would like
to be created automatically every time a new record
is inserted.
Auto-increment
qTo 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.
qThe default value of seed and increment is 1.
qExample:
CREATE TABLE Employee
(
Emp_ID int PRIMARY KEY IDENTIY(1,1),
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
)
Exercises
qEx1: 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
qEx3: 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
qINSERT command is used to enter data into a table.
§ Example:
INSERT INTO Vendor
(V_Code,V_Name,V_Contact,V_AreaCode,V_Phone,V_State,V_Order)
VALUES(21225,'Bryson, Inc.','Smithson','615','223-3234','TN','Y')
qNote for INSERT statement
§ The row contents are entered between parentheses
§ Character (string) and date values must be entered between
apostrophes ( ’ ).
§ Numerical entries are not enclosed in apostrophes.
§ Attribute entries are separated by commas.
§ A value is required for each column in the table.
49
INSERT Statement
q 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.
50
INSERT Statement
q 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
INSERT INTO Product(P_Code, P_Descript)
VALUES('BRT-345','Titanium drill bit')
52
INSERT Statement
qSQL 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
qAny changes made to the table contents are not
physically saved on disk until
§ Database is closed
§ Program is closed
§ COMMIT command is used
qSaving 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
qThe 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