0% found this document useful (0 votes)
17 views63 pages

CSE311 IAH Slide07 SQL+Advanced+Quries

Uploaded by

sadaenparvess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views63 pages

CSE311 IAH Slide07 SQL+Advanced+Quries

Uploaded by

sadaenparvess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

SQL Advanced Queries

Slides Credit: Fundamentals of Database Systems by Elmasri, Navathei


Modified by: Md. Ishan Arefin Hossain, Full-time Lecturer, NSU ECE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL DDL DML
DDL – Data Definition Language – Create, Remove and Modify
Database Structures
Create

Alter

Drop

DML – Data Manipulation Language – Create, Remove and


Modify Data Values
Insert

Update

Delete

Truncate

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The CREATE TABLE Command in
SQL
 Specifying a new relation
 Provide name of table
 Specify attributes, their types and initial
constraints
 Can optionally specify schema:
 CREATE TABLE COMPANY.EMPLOYEE ...
or
 CREATE TABLE EMPLOYEE ...

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The CREATE TABLE Command in
SQL (cont’d.)
 Base tables (base relations)
 Relation and its tuples are actually created and
stored as a file by the DBMS
 Virtual relations (views)
 Created through the CREATE VIEW statement.
Do not correspond to any physical file.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


COMPANY relational database
schema (Fig. 5.7)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


One possible database state for the
COMPANY relational database schema
(Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


One possible database state for the
COMPANY relational database schema –
continued (Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CREATE TABLE data definition statements
for defining the COMPANY schema from Figure
5.7 (Fig. 6.1)

continued on next slide

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CREATE TABLE data definition
statements for defining the COMPANY
schema from Figure 5.7 (Fig. 6.1)-continued

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL
 Basic data types
 Numeric data types

Integer numbers: INTEGER, INT, and SMALLINT

Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
 Character-string data types

Fixed length: CHAR(n), CHARACTER(n)

Varying length: VARCHAR(n), CHAR
VARYING(n), CHARACTER VARYING(n)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
 Bit-string data types

Fixed length: BIT(n)

Varying length: BIT VARYING(n)
 Boolean data type

Values of TRUE or FALSE or NULL
 DATE data type

Ten positions

Components are YEAR, MONTH, and DAY in the form
YYYY-MM-DD

Multiple mapping functions available in RDBMSs to
change date formats
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Attribute Data Types and Domains in
SQL (cont’d.)
 Additional data types

Timestamp data type
Includes the DATE and TIME fields

Plus a minimum of six positions for decimal fractions of
seconds

Optional WITH TIME ZONE qualifier

INTERVAL data type
Specifies a relative value that can be used to increment or

decrement an absolute value of a date, time, or timestamp



DATE, TIME, Timestamp, INTERVAL data types can be
cast or converted to string formats for comparison.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Attribute Data Types and Domains in
SQL (cont’d.)
 Domain

Name used with the attribute specification

Makes it easier to change the data type for a domain
that is used by numerous attributes

Improves schema readability

Example:

CREATE DOMAIN SSN_TYPE AS CHAR(9);
 TYPE

User Defined Types (UDTs) are supported for object-
oriented applications. (See Ch.12) Uses the command:
CREATE TYPE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Constraints in SQL
Basic constraints:
Relational Model has 3 basic constraint types that

are supported in SQL:


 Key constraint: A primary key value cannot be
duplicated
 Entity Integrity Constraint: A primary key value
cannot be null
 Referential integrity constraints : The “foreign
key “ must have a value that is already present as
a primary key, or may be null.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Attribute Constraints
Other Restrictions on attribute domains:
 Default value of an attribute
 DEFAULT <value>

NULL is not permitted for a particular attribute
(NOT NULL)
 CHECK clause
Dnumber INT NOT NULL CHECK (Dnumber >
0 AND Dnumber < 21);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Key and Referential
Integrity Constraints
 PRIMARY KEY clause
 Specifies one or more attributes that make up the
primary key of a relation
 Dnumber INT PRIMARY KEY;
 UNIQUE clause
 Specifies alternate (secondary) keys (called
CANDIDATE keys in the relational model).
 Dname VARCHAR(15) UNIQUE;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Key and Referential
Integrity Constraints (cont’d.)
 FOREIGN KEY clause
 Default operation: reject update on violation
 Attach referential triggered action clause

Options include SET NULL, CASCADE, and SET
DEFAULT

Action taken by the DBMS for SET NULL or SET
DEFAULT is the same for both ON DELETE and ON
UPDATE

CASCADE option suitable for “relationship” relations

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Giving Names to Constraints
 Using the Keyword CONSTRAINT
 Name a constraint
 Useful for later altering

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Default attribute values and referential
integrity triggered action specification (Fig.
6.2)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Constraints

A "CONSTRAINT" is a rule applied to a TABLE or COLUMN that allows


the database software to maintain data integrity within the database.
The database software will not allow the restrictions of the constraint to
be violated.
Constraints can exist at the TABLE level and/or at the COLUMN level.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Constraints
Table level constraints:
Primary Key Foreign
Key
Column level constraints:
Not Null
Check Default Unique
Primary Key

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Column Constraints
CREATE TABLE items (

itemID INT NOT NULL PRIMARY KEY,


itemcode VARCHAR(5) UNIQUE,

VARCHAR(40) NOT NULL DEFAULT ' ',


itemname INT NOT NULL DEFAULT 0,
REAL NOT NULL DEFAULT 0
quantity
price
The);UNIQUE constraint prevents inserting a row with a duplicate value
The PRIMARY KEY constraint includes a UNIQUE constraint

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Column Constraints
CREATE TABLE items (

itemID INT NOT NULL PRIMARY KEY,


itemcode VARCHAR(5) UNIQUE,
VARCHAR(40) NOT NULL DEFAULT ' ',
itemname INT NOT NULL DEFAULT 0,
DECIMAL(9,2)
CHECK price < 1000
quantity
price
);
The CHECK constraint includes a condition on the column

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Table Constraints
The PRIMARY KEY and FOREIGN KEY constraints (as table-level constraints)
CREATE TABLE items (
itemID INT INT NOT NULL, NOT NULL,
supplierid VARCHAR(5) UNIQUE,
itemcode VARCHAR(40) NOT NULL DEFAULT ' ',
INT NOT NULL DEFAULT 0,
itemname
DECIMAL(9,2) CHECK price < 1000
quantityKEY (itemID)
PRIMARY
price
CONSTRAINT fk_supplier FOREIGN KEY(supplierid) REFERENCES supplier(supplierid)
);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Table Constraints
A concatenated or composite Primary Key can be set at the table level
CREATE TABLE "alanparadise/nw"."items" (

itemID INT NOT NULL, NOT NULL,


supplierid INT UNIQUE,
itemcode VARCHAR(5) NOT NULL DEFAULT ' ',
VARCHAR(40) NOT NULL DEFAULT 0,
itemname INT
DECIMAL(9,2) CHECK price < 1000
quantityKEY (itemID, supplierID)
PRIMARY
price
);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Table Constraints
By giving a table-level constraint a name (fk_supplier), the constraint is modifiable by an ALTER
CREATE TABLE items (

itemID INT NOT NULL,


supplierid INT NOT NULL,
itemcode VARCHAR(5) UNIQUE,
VARCHAR(40) NOT NULL DEFAULT ' ',
itemname INT NOT NULL DEFAULT 0,
DECIMAL(9,2) CHECK price < 1000
quantityKEY (itemID)
PRIMARY
price
CONSTRAINT fk_supplier FOREIGN KEY(supplierid)
REFERENCES supplier(supplierid)
);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Table Constraints
A table-level foreign key constraint can indicate how to handle the situation
when the foreign key in the PARENT table is deleted or updated.

CONSTRAINT fk_supplier FOREIGN KEY(supplierid)


REFERENCES supplier(supplierid)
ON UPDATE <update action>
ON DELETE <delete action>

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Table Constraints

CONSTRAINT fk_supplier FOREIGN KEY(supplierid)


REFERENCES supplier(supplierid)
ON UPDATE <update action>
ON DELETE <delete action>

 ACTION may be:

CASCADE NO The change to the parent is cascaded to all affected child rows
ACTION SET The change to the parent is prohibited
NULL The foreign key column in the child is set to NULL
SET DEFAULT The foreign key column in the child is set to its default value The
RESTRICT change to the parent is prohibited

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Specifying Constraints on Tuples
Using CHECK
 Additional Constraints on individual tuples within a
relation are also possible using CHECK
 CHECK clauses at the end of a CREATE TABLE
statement
 Apply to each tuple individually
 CHECK (Dept_create_date <=
Mgr_start_date);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


INSERT, DELETE, and UPDATE
Statements in SQL
 Three commands used to modify the database:

INSERT, DELETE, and UPDATE
 INSERT typically inserts a tuple (row) in a relation
(table)
 UPDATE may update a number of tuples (rows) in
a relation (table) that satisfy the condition
 DELETE may also update a number of tuples
(rows) in a relation (table) that satisfy the
condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


INSERT
 In its simplest form, it is used to add one or more
tuples to a relation
 Attribute values should be listed in the same
order as the attributes were specified in the
CREATE TABLE command
 Constraints on data types are observed
automatically
 Any integrity constraints as a part of the DDL
specification are enforced

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The INSERT Command
 Specify the relation name and a list of values for
the tuple. All values including nulls are supplied.

 The variation below inserts multiple tuples where


a new table is loaded values from the result of a
query.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


BULK LOADING OF TABLES
 Another variation of INSERT is used for bulk-loading of
several tuples into tables
 A new table TNEW can be created with the same
attributes as T and using LIKE and DATA in the syntax,
it can be loaded with entire data.
 EXAMPLE:

CREATE TABLE D5EMPS LIKE EMPLOYEE


(SELECT E.*
FROM EMPLOYEE AS E
WHERE E.Dno=5)
WITH DATA;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


DELETE
 Removes tuples from a relation

Includes a WHERE-clause to select the tuples to be
deleted
 Referential integrity should be enforced


Tuples are deleted from only one table at a time (unless
CASCADE is specified on a referential integrity
constraint)
 A missing WHERE-clause specifies that all tuples in the

relation are to be deleted; the table then becomes an


empty table
 The number of tuples deleted depends on the number of

tuples in the relation that satisfy the WHERE-clause


Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
The DELETE Command
 Removes tuples from a relation
 Includes a WHERE clause to select the tuples to be
deleted. The number of tuples deleted will vary.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


UPDATE
 Used to modify attribute values of one or more
selected tuples
 A WHERE-clause selects the tuples to be
modified
 An additional SET-clause specifies the attributes
to be modified and their new values
 Each command modifies tuples in the same
relation
 Referential integrity specified as part of DDL
specification is enforced
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
UPDATE (contd.)
 Example: Change the location and controlling
department number of project number 10 to
'Bellaire' and 5, respectively

U5: UPDATE PROJECT


SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


UPDATE (contd.)
 Example: Give all employees in the 'Research' department a
10% raise in salary.
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')
 In this request, the modified SALARY value depends on the
original SALARY value in each tuple


The reference to the SALARY attribute on the right of =
refers to the old SALARY value before modification

The reference to the SALARY attribute on the left of =
refers to the new SALARY value after modification

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Schema Change Statements in SQL
 Schema evolution commands
 DBA may want to change the schema while the
database is operational
 Does not require recompilation of the database
schema

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The DROP Command
 DROP command
 Used to drop named schema elements, such as
tables, domains, or constraint
 Drop behavior options:
 CASCADE and RESTRICT
 Example:
 DROP SCHEMA COMPANY CASCADE;
 This removes the schema and all its elements
including tables,views, constraints, etc.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


The ALTER table command
 Alter table actions include:
 Adding or dropping a column (attribute)
 Changing a column definition
 Adding or dropping table constraints
 Example:
 ALTER TABLE COMPANY.EMPLOYEE ADD
COLUMN Job VARCHAR(12);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Adding and Dropping Constraints
 Change constraints specified on a table
 Add or drop a named constraint

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Dropping Columns, Default Values
 To drop a column
 Choose either CASCADE or RESTRICT
 CASCADE would drop the column from views etc.
RESTRICT is possible if no views refer to it.
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN
Address CASCADE;
 Default values can be dropped and altered :
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn
DROP DEFAULT;
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn
SET DEFAULT ‘333445555’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
During database design, you must define a primary key for each entity.
Sometimes, among the various candidate keys in a collection of
attributes, there is no attribute that can serve as good primary key.
In such a case, it is necessary for the designer to create a surrogate key.
Surrogate keys are typically integers.
Surrogate keys are ideally created by the database software by using a
column defined as an "Identity".
In the MySQL database, identities are called "auto_increment"

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
For each column defined as "Identity", the database software creates and
maintains a "sequence" object.
The sequence can be assigned an initial value, and with each subsequent insert,
the database software increments the sequence.
The starting point and increment size for the identity can be modified by the
ALTER command.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
Let's create a table that uses an identity (sequence) as a
unique identifier for each row that we insert.

CREATE statement

CREATE TABLE shoppers" (

ShopperID int NOT NULL auto increment,


ShopperName varchar(40) NOT NULL , varchar(20) NOT NULL DEFAULT
Phone '0'

);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
Let's insert a new row into the shoppers
table.

INSERT statement
INSERT INTO shoppers (shoppername, phone) VALUES
('AlanParadise', '800-432-6543')

Note that no value was provided for the shopperid identity


column

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
After the insert:
SELECT * FROM shoppers;

The database inserted the first row starting with the


sequence of 1.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
Let's insert some more rows into the shoppers
table.
INSERT INTO shoppers (shoppername, phone) VALUES
('FredFlintstone', '800-123-4567');
INSERT INTO shoppers (shoppername, phone) VALUES
('PeterParker', '800-987-6543');
INSERT INTO shoppers (shoppername, phone) VALUES
('BartSimpson', '800-888-6969');
INSERT INTO shoppers (shoppername, phone) VALUES
('ClarkKent', '800-999-2468');

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
After the SELECT * FROM shoppers;
insert:

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL Auto Increment
 The database incremented the sequence with
each insert.

 This identity column using the sequence


guarantees a unique key value for each new row
that is inserted.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL VIEWS
The VIEW
A “VIEW” is an empty shell of a table definition

The view contains no data until it is queried

Can be considered as a “Virtual Table”

Each time the view is queried, the underlying

query that populates the view is re-executed

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Why use VIEWs?
1. Security, maintaining confidentiality
The view can prevent unauthorized users from seeing

data that must be kept secure or confidential


2. Complexity
The view can hide complex SQL from unauthorized or

inexperienced users

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


First case:
Base Table:

Employees(EmpID, Lastname, Firstname, Salary, HireDate)


View:

Employees(EmpID, Lastname, Firstname, HireDate)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


CREATING a VIEW
CREATE VIEW <view name> AS

SELECT <col1>, <col2>, <col3>


FROM <table1>
WHERE <condition>

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


 Creating:
CREATE VIEW TopEmployeesOrders AS
SELECT LastName, Firstname, sum(unitprice * quantity) as "Total Sales“
from employees E
JOIN orders O ON E.employeeid = O.employeeid
JOIN `order details` D ON O.orderid = D.ordered
GROUP BY LastName, FirstName
Order By 3 desc LIMIT 5;

 Querying:
select * from TopEmployeesOrders

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CASE

The SQL CASE expression allows SQL to process conditional statements,


similar to the IF/THEN/ELSE construct in other programming languages.

CASE is an expression that can be used anywhere in SQL where an


expression is allowd.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CASE
CASE
WHEN <condition_1> THEN
<result_1> WHEN <condition_2>
THEN <result_2> WHEN
ELSE <else_result>
<condition_3> END
THEN <result_3>
(this results if the prior conditions are all
false)
If a CASE condition is true, the CASE ends with that result.
If the CASE condition is false, control passes to the next CASE.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CASE
 Let's Look at an example from the Northwinds database:
You are asked to categorize each Northwinds product
based on its price range.
 Product Categories:

Price < 20: category = "Economy" Price >= 20 and <80:


category = "Standard" Price >= 80: category =
"Premium"

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CASE
SELECT productid, productname, unitprice,
CASE

WHEN unitprice < 20 THEN 'Economy'


WHEN 'Premium'
ELSE unitprice < 80 THEN 'Standard
This text is populated into
'the column
END category "category" in the answer set

FROM products;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


SQL CASE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Summary of SQL Syntax

continued on next slide

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


Summary of SQL Syntax
(continued)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe

You might also like