Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Chapter4_session1-Introduction to SQL, DDL, DML

Uploaded by

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

Chapter4_session1-Introduction to SQL, DDL, DML

Uploaded by

cuongnt.22ef
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Database Systems

Chapter 4: Structured Query Language


(SQL)
Session 1:
Introduction to SQL, DDL, DML
Outline

1 Introduction to SQL

2 DDL Statements

3 DML Statements with INSERT/UPDATE/DELETE

2
Introduction to SQL

Pronounced “S-Q-L” by some and “sequel” by others


Pronounced “S-Q-L” by some and “sequel” by others
SQL is a Nonprocedural language
The standard for relational database management
systems (RDBMS).

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

Data Definition Data Manipulation Data Control


Language(DDL) Language(DML) Language(DCL)
Control the database:
Define the database: Maintain and query
- GRANT OR REVOKE
- CREATE, ALTER, DROP the database:
PRIVILEGES TO
TABLES, VIEWS, INDEXES - UPDATING, INSERTING,
ACCESS THE
- ESTABLISHING DELETING AND
DATABASE
CONSTRAINTS QUERYING DATA
- COMMITING DATA
7
Data Definition Language(DDL)
DDL statements are used to define a database
Major CREATE statements:
CREATE DATABASE – create a new database
CREATE SCHEMA–defines a portion of the database
owned by a particular user
CREATE TABLE–defines a table and its columns
CREATE VIEW–defines a logical table from one or more
views

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

2. Using a Query: Ctrl +N


To create a new query
 Syntax:

CREATE DATABASE DatabaseName

 Example:

CREATE DATABASE DemoShopping


 Click Execute button to
create the DemoShopping database.
Creating a new database
Using the database
1. Click the combobox to
choose the database

2. Use Query
 Syntax:
USE DatabaseName
 Example
USE DemoShopping

Right-click to the database, choose Properties,


click Files to know database files
Altering/Deleting a Database
To alter an existing database:
 Syntax:
ALTER DATABASE OldDatabase MODIFY NAME = NewDatabase

 Example:
ALTER DATABASE DemoShopping MODIFY NAME = DemoShopping2

To drop a database


 Syntax:
DROP DATABASE TheDatabase

 Example:
DROP DATABASE DemoShopping2

 Dropping a database will delete the LDF and MDF files.


Creating the Database Schema
Schema: logical database structure
Is a group of database objects- such as tables and indexes
– that are related to each other.
Authentication
Process through which the DBMS verifies that only
registered users are able to access the database
Log on to the RDBMS using a user ID and a password
created by the database administrator
Syntax:
CREATE SCHEMA AUTHORIZATION <creator>

Ex: CREATE SCHEMA AUTHORIZATION 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).

Unicode character string data types store either fixed-


length (nchar) or variable-length (nvarchar)
Some Common SQL Data Types
Binary string data types
The binary data types stores fixed and variable
length binary data.
Some Common SQL Data Types
Other data types
SQL Constraints
A constraint is a mechanism that may be used to
limit the values entered into a column.

CONSTRAINTS

NOT NULL CHECK FOREIGN KEY PRIMARY KEY

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:

• Each product is supplied by only a single vendor.


• A vendor may supply many products
• PRODUCT is optional to VENDOR.
• Some vendors have never supplied a product (VENDOR is
optional to PRODUCT)

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:

Data Types can be string, numeric, and date/time. Not all


data types are supported by every relational database
vendors.
To make the SQL code more readable:
one line per column definition,
SQL keywords should be upper-case letters
User-defined words should be lower-case letters
Creating a Table with primary key
constraint
Syntax 1:

Syntax 2: you can named for constraint

30
Creating a table with primary key
constraint CREATE TABLE Vendor (
V_Code INT PRIMARY KEY,
Example: 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,
Or 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 (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:
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 rules
CREATE TABLE Product (
Example 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
)

ON UPDATE CASCADE specification ensures that if you make


a change in any V_CODE in VENDOR table that will result in
that value changing in the 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

To change the data type of a column in a table


ALTER TABLE table_name
ALTER COLUMN column_name datatype

To drop a column


ALTER TABLE table_name
DROP COLUMN column_name
Altering a table
Use 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;

Show all constraints in a table


exec sp_helpconstraint 'table_name'
Altering a table with examples
To add column for a table
 Add a column named CUS_Address to the Customer table
ALTER TABLE dbo.Customer
ADD CUS_Address NVARCHAR(50) DEFAULT N'Đà Nẵng'
To add constraints for a table
 Add a primary key for Vendor table if you forget to create it.
Note: you only create a primary key on column(s) that are
already defined as NOT NULL
ALTER TABLE Vendor
ADD CONSTRAINT PK_Vendor PRIMARY KEY(V_Code)

 Add a foreign key for Product table


ALTER TABLE Product
ADD CONSTRAINT FK_Product_Vendor_Vcode
FOREIGN KEY (V_Code) REFERENCES Vendor
ON UPDATE CASCADE
41
Removing a table
DROP TABLE statement removes the specified table
from a database
Syntax
DROP TABLE Table_name [RESTRIC|CASCADE]
Default option is RESTRICT, the table will not be dropped if
there are any dependent objects, such as views or
constraints, that currently reference the table.
If CASCADE is specified, all dependent objects will also be
dropped as the table is dropped.

42
Removing a table
Example:
DROP TABLE Table_name [RESTRIC|CASCADE]

Many RDBMSs allows users to retain the table’s


structure but remove all of the data that have been
entered in the table with its TRUNCATE TABLE command
 Syntax:
TRUNCATE TABLE Table_name

 Example
TRUNCATE TABLE Customer

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 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')
Note 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
 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.

INSERT INTO Vendor VALUES(21225,'Bryson,


Inc.','Smithson','615','223-3234','TN','Y')
Inserting Rows with Null Attributes with NULL keyword
when all the attribute values must be specified
INSERT INTO Product
VALUES ('BRT-345','Titanium drill bit','18-Oct-15', 75, 10, 4.50,
0.06, NULL)

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
INSERT INTO Product(P_Code, P_Descript)
VALUES('BRT-345','Titanium drill bit')

You can insert more than one record at a time.


Example
INSERT INTO Vendor VALUES
(21226,'SuperLoo, Inc.','Flushing','904','215-8995','FL','N'),
(21231,'D&E Supply‘ ,'Singh' ,'615','228-3245','TN','Y'),
(21344,'Gomez Bros.' ,'Ortega' ,'615','889-2546','KY','N')
51
INSERT Statement
End-user applications are best created with utilities
to create a form-based data view and entry screen

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.

Value1, value2,…can be an expression.


If more than one attribute is to be updated in the row,
separate the corrections with commas.
The WHERE clause is optional, that specifies which
record(s) that should be updated.
If you omit the WHERE clause, all records in the table
will be updated!
Update statement
Example
UPDATE Product
SET P_InDate = '01-18-2016'
WHERE P_Code = '13-Q2/P2'

UPDATE Product
SET P_InDate = '01-18-2016', P_Price = 17.99, P_Min = 10
WHERE P_CODE = '13-Q2/P2'

Use can use the command to list contents of table


SELECT * FROM Product
UPDATE statement
Restoring Table Contents by ROLLBACK statement
Used restore the database to its previous condition
Only applicable if COMMIT command has not been used
to permanently store the changes in the database
Syntax ROLLBACK;

Use BEGIN TRANSACTION before DML commands


before using ROLLBACK command.
COMMIT and ROLLBACK only work with data
manipulation commands that are used to add,
modify, or delete table rows
58
DELETE statement
The DELETE statement is used to delete existing
records in a table.

The WHERE clause is optional, that specifies which


record(s) should be deleted.
If you omit the WHERE clause, all records in the table
will be deleted!
DELETE statement
Example
DELETE FROM Product
WHERE P_Code = 'BRT-345'

DELETE FROM Product


WHERE P_Min = 5
DELETE statement
TRUNCATE vs DELETE
TRUNCATE is a DDL whereas DELETE is a DML
You can use WHERE clause(conditions) with
DELETE but you can't use WHERE clause with
TRUNCATE
You can't rollback data in TRUNCATE but in
DELETE you can rollback data
TRUNCATE is faster than DELETE.
Exercises
Complete the previous exercise with DML
commands.

62

You might also like