0% found this document useful (0 votes)
14 views

Mdb Unit 123-09-22 Updated Ppt 1

The document provides an overview of Database Management Systems (DBMS) and Structured Query Language (SQL), detailing their definitions, characteristics, applications, advantages, and disadvantages. It covers essential SQL concepts including data definition, data types, schema creation, and basic constraints, along with examples of SQL commands. The lecture aims to equip students with foundational knowledge of DBMS and SQL for effective data management and manipulation.

Uploaded by

9449ydarshan
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)
14 views

Mdb Unit 123-09-22 Updated Ppt 1

The document provides an overview of Database Management Systems (DBMS) and Structured Query Language (SQL), detailing their definitions, characteristics, applications, advantages, and disadvantages. It covers essential SQL concepts including data definition, data types, schema creation, and basic constraints, along with examples of SQL commands. The lecture aims to equip students with foundational knowledge of DBMS and SQL for effective data management and manipulation.

Uploaded by

9449ydarshan
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/ 275

Established as per the Section 2(f) of the UGC

Act, 1956
Approved by AICTE, COA and BCI, New Delhi

Lecture 1.1
Modern Databases
School of CSE

D r. S . D e e p a j o t h i
[email protected]
1
OUTLINE
Recap of previous Lecture

Topic for the Lecture


Objective and Outcome of Lecture
Lecture Discussion
Introduction to DBMA and SQL
SQL Data Definition and Data Types
Schema Change Statements
Specifying Basic Constraints in SQL
Basic & Complex queries in SQL.
Introduction to DBMS
Objective and Outcome of
Lecture
UNIT – 1

Overview of DBMS and SQL: Introduction to


DBMS and SQL, SQL Data Definition and Data
Types, Schema change statements in SQL,
Specifying basic constraints in SQL, Basic
Queries in SQL, More Complex Queries in SQL.

4
1. INTRODUCTION TO DBMS
INTRODUCTION TO DBMS

WHAT IS DATA?
• Data is a collection of a distinct small unit of information. It can be used in a
variety of forms like text, numbers, media, bytes, etc. it can be stored in pieces of
paper or electronic memory, etc.
• Word 'Data' is originated from the word 'datum' that means 'single piece of
information.' It is plural of the word datum.
• In computing, Data is information that can be translated into a form for efficient
movement and processing. Data is interchangeable.

6
DATABASE
WHAT IS DATABASE

• The database is a collection of inter-related data which is used to


retrieve, insert and delete the data efficiently. It is also used to organize
the data in the form of a table, schema, views, and reports, etc.
• For example: The college Database organizes the data about the
admin, staff, students and faculty etc.
• Using the database, you can easily retrieve, insert, and delete the
information.

8
DATABASE
MANAGEMENT
SYSTEM
DATABASE MANAGEMENT SYSTEM

• Database management system is a software which is used to manage


the database. For example: MySQL, Oracle, etc are a very popular
commercial database which is used in different applications.
• DBMS provides an interface to perform various operations like
database creation, storing data in it, updating data, creating a table in
the database and a lot more.
• It provides protection and security to the database. In the case of
multiple users, it also maintains data consistency.

10
CHARACTERISTICS OF DBMS

• It uses a digital repository established on a server to store and manage the


information.
• It can provide a clear and logical view of the process that manipulates data.
• DBMS contains automatic backup and recovery procedures.
• It contains ACID properties which maintain data in a healthy state in case of
failure.
• It can reduce the complex relationship between data.
• It is used to support manipulation and processing of data.
• It is used to provide security of data.
• It can view the database from different viewpoints according to the requirements 13
of the user.
APPLICATIONS

1. Banking Management
2. Business Organization
3. Manufacturing
4. Education
5. Medical Field
6. Railways
DBMS ALLOWS USERS THE FOLLOWING TASKS:

• Data Definition: It is used for creation, modification, and removal of definition


that defines the organization of data in the database.
• Data Updation: It is used for the insertion, modification, and deletion of the
actual data in the database.
• Data Retrieval: It is used to retrieve the data from the database which can be used
by applications for various purposes.
• User Administration: It is used for registering and monitoring users, maintain
data integrity, enforcing data security, dealing with concurrency control,
monitoring performance and recovering information corrupted by unexpected
failure.

15
ADVANTAGES OF DBMS
• Controls database redundancy: It can control data redundancy because it stores
all the data in one single database file and that recorded data is placed in the
database.
• Data sharing: In DBMS, the authorized users of an organization can share the
data among multiple users.
• Easy Maintenance: It can be easily maintainable due to the centralized nature of
the database system.
• Reduce time: It reduces development time and maintenance need.
• Backup: It provides backup and recovery subsystems which create automatic
backup of data from hardware and software failures and restores the data if
required.
• multiple user interface: It provides different types of user interfaces like
graphical user interfaces, application program interfaces 16
DISADVANTAGES OF DBMS

• Cost of Hardware and Software: It requires a high speed of data processor and
large memory size to run DBMS software.

• Size: It occupies a large space of disks and large memory to run them efficiently.

• Complexity: Database system creates additional complexity and requirements.

• Higher impact of failure: Failure is highly impacted the database because in most
of the organization, all the data stored in a single database and if the database is
damaged due to electric failure or database corruption then the data may be lost
forever. 17
Established as per the Section 2(f) of the UGC
Act, 1956
Approved by AICTE, COA and BCI, New Delhi

Lecture 1.1
Introduction to SQL
School of CSE

1
OUTLINE
Recap of previous Lecture

Topic for the Lecture


Objective and Outcome of Lecture
Lecture Discussion
SQL Data Definition and Data Types
Specifying Basic Constraints in SQL
Schema Change Statements
Basic & Complex queries in SQL,Update operations.
Views and other additional features.
Introduction to SQL
Objective and Outcome of
Lecture
OBJECTIVE AND OUTCOME OF
LECTURE

Lecture Explain the basic definition of SQL, datatypes,basic clauses,simple


Objective queries,complex queries,additional features and views in SQL

Lecture Understanding the basic definition,writing the queries in all


Outcome possible ways.
Introduction to SQL
D e fi n i t i o n
SQL - THE RELATIONAL DATABASE
STANDARD
• This chapter presents the main features of the SQL standard for
commercial relational DBMSs.
• SQL (Structured Query Language) language provides a high-level
declarative language interface.
• SQL includes some features from relational algebra, but it is based to a
greater extent on the tuple relational calculus
• SQL is a comprehensive database language. it include
• statements for data definition,
• statements for query,
• statements for update.

Hence, it is both a DDL (Data Definition Language) and a


DML (Data Manipulation Language). 23
SQL - THE RELATIONAL DATABASE STANDARD

• In addition, it has facilities for

• defining views on the database

• specifying security and authorization

• defining integrity constraints

• specifying transaction controls

• It also has rules for embedding SQL statements into a general-


purpose programming language such as C ,C++, java or
PASCAL.
24
1.3. SQL Data Definition and DATA
Types
SQL DATA DEFINITION AND DATA TYPES

1. In SQL terminology ,
1. A relation is called a table
2. A tuple is called a row
3. An attribute is called a column
2. The main SQL commands for data definition is the CREATE
statement
3. CREATE statement can used to create
Schemas
tables
domains
views
26
Assertion
SQL DATA DEFINITION AND DATA TYPES

Schema and Catalog Concepts in SQL


An SQL schema is identified by a schema name, and includes
1. an authorization identifier to indicate the user or account who owns
the schema
2. descriptors for each element in the schema.

Schema elements include


3. tables
4. constraints
5. views,
6. domains,
7. and other constructs (such as authorization grants) that describe the
schema
SQL DATA DEFINITION AND DATA TYPES

Schema and Catalog Concepts in SQL


1. A schema is created via the CREATE SCHEMA statement, which
can include all the schema elements’ definitions.
Example:
The following statement creates a schema called COMPANY, owned by
the user with authorization identifier JSMITH
CREATE SCHEMA COMPANY AUTHORIZATION JSMITH;

In general , not all users are authorized to create


schema and schema elements .
The privilege for these must be given by Database
Administrator (DBA) 28
SQL DATA DEFINITION AND DATA TYPES

Schema and Catalog Concepts in SQL


SQL catalog
A named collection of schemas in an SQL environment.

1. A catalog always contains a special schema called


INFORMATION_SCHEMA

2. INFORMATION_SCHEMA provides information on all the element


descriptors of all the schemas in the catalog to authorized users.

29
SQL DATA DEFINITION AND DATA TYPES
The CREATE TABLE Command
1. The CREATE TABLE command is used to specify a new relation
by giving it a name and specifying its attributes and constraints
The attributes are specified first, and each attribute is given a name
Followed by a data type to specify its domain of values.
Followed by any attribute constraints such as NOT NULL.
The key, entity integrity, and referential integrity constraints can be specified—
within the CREATE TABLE statement—after the attributes are declared.

2. Syntax :
CREATE TABLE COMPANY.EMPLOYEE… OR

CREATE TABLE EMPLOYEE ... 30


SQL DATA DEFINITION AND DATA
TYPES

The CREATE TABLE Command Example : Company


Database

31
SQL DATA DEFINITION AND DATA TYPES
The CREATE TABLE Command Example : Company
Database

32
SQL DATA DEFINITION AND DATA
TYPES
The CREATE TABLE Command Example : Company
Database

33
SQL DATA DEFINITION AND DATA TYPES
The CREATE TABLE Command

• The relations declared through CREATE TABLE statements are


called base tables (or base relations)

• The relations declared through CREATE VIEW statements are


called virtual tables (or virtual relations)

• In SQL the attributes in a base relation are considered to be


ordered in the sequence in which they are specified in the
CREATE table statement.

• Rows are not considered to be ordered within a relation 34


SQL DATA TYPES

1. SQL data types can be broadly divided into following categories.


2. Numeric data types such as int, tinyint, bigint, float, real, etc.
3. Date and Time data types such as Date, Time, Datetime, etc.
4. Character and String data types such as char, varchar, text, etc.
5. Unicode character string data types, for example nchar, nvarchar, ntext,
etc.
6. Binary data types such as binary, varbinary, etc.
7. Miscellaneous data types - clob, blob, xml, cursor, table, etc.
SQL DATA DEFINITION AND DATA TYPES
SQL DATA TYPES IMPORTANT POINTS

1. Not all data types are supported by every relational database vendor. For example,
Oracle database doesn’t support DATETIME and MySQL doesn’t support CLOB
data type. So while designing database schema and writing SQL queries, make
sure to check if the data types are supported or not.
2. Data types listed here doesn’t include all the data types, these are the most
popularly used data types. Some relational database vendors have their own data
types that might be not listed here. For example, Microsoft SQL Server
has money and smallmoney data types but since it’s not supported by other
popular database vendors, it’s not listed here.
3. Every relational database vendor has its own maximum size limit for different data
types, you don’t need to remember the limit. Idea is to have the knowledge of what
data type to be used in a specific scenario.
SQL NUMERIC DATA TYPES
SQL DATE AND TIME DATA TYPES
SQL CHARACTER AND STRING DATA TYPES
SQL UNICODE CHARACTER AND STRING DATA TYPES
SQL BINARY DATA TYPES
SQL MISCELLANEOUS DATA TYPES
SQL DATA DEFINITION AND DATA TYPES
Data Types and Domains in SQL(
• Numeric data types include
• integer numbers of various sizes
INTERGER or INT and SMALLINT
• floating points of various precision
FLOAT or REAL
DOUBLE PRECISION
• Formatted numbers can be declared by using
• DECIMAL (i , j) or DEC(i , j) or NUMERIC( i , j) where i is the precision and j is the
scale
• The default scale is zero and default for precision is implementation defined .
44
4.2 SQL DATA DEFINITION AND DATA TYPES
Data Types and Domains in SQL

• Character-string 2 types
• fixed-length
CHAR(n) or CHARACTER(n), where n is the
number of characters.
varying-length
VARCHAR(n) or CHAR VARYING(n) or CHARACTER
VARYING(n), where n is the maximum number of
characters. Literal string value is placed
between single quotation marks and it is case
sensitive. 45
4.2 SQL DATA DEFINITION AND DATA
TYPES
Data Types and Domains in SQL

• Bit-string  2 types
• fixed length

BIT(n), where n is the maximum number of bits.

• varying length

BIT VARYING(n), where n is the maximum number of bits.


The default for n, the length of a character string or bit
string, is one.
46
• Literal bit strings are placed between single quotes but
4.2 SQL DATA DEFINITION AND DATA
TYPES
Data Types and Domains in SQL
• date and time

• The DATE data type has ten positions, and its components are
YEAR, MONTH, and DAY typically in the form YYYY-MM-DD.
• The TIME data type has at least eight positions, with the
components HOUR, MINUTE, and SECOND, typically in the form
HH:MM:SS.
• The < (less than) comparison can be used with dates or
times.
47
• Literal values are represented by single quoted strings
4.2 SQL DATA DEFINITION AND DATA TYPES
Data Types and Domains in SQL

• timestamp
• A timestamp data type (TIMESTAMP) includes both the DATE
and TIME fields, plus a maximum number of six positions for
decimal fractions of seconds and an optional WITH TIME ZONE
qualifier

• Literal values are specified as follows:

TIMESTAMP’2002 -09-27 09:12:47 648302’


48
(Minimum one space between date and time )
4.2 SQL DATA DEFINITION AND DATA TYPES
Data Types and Domains in SQL

interval

• INTERVAL data type specifies an interval—a relative


value that can be used to increment or decrement an
absolute value of a date, time, or timestamp.

49
1. 4 Specifying Basic Constraints
in SQL
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Attribute Constraints and Default Values
• Not Null constraints :
• This should always be specified for the primary key
attributes of each relation,
• Also for any other attributes whose values are required not
to be NULL.
Example : DNAME VARCHAR(20) NOT NULL

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
); 52
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

PRIMARY KEY

1. The PRIMARY KEY constraint uniquely identifies each record in a


table.
2. Primary keys must contain UNIQUE values, and cannot contain NULL
values.
3. A table can have only ONE primary key; and in the table, this primary
key can consist of single or multiple columns (fields).
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

MYSQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

• The PRIMARY KEY clause.


• specifies one or more attributes that make up the primary key of a relation.
PRIMARY KEY (DNUMBER,DLOCATION)
• If primary key single attribute then the clause can follow the
attribute directly
DNUMBER INT PRIMARY KEY

55
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
COMPOSITE KEY
• A composite key is a combination of two or more columns in
a table that can be used to uniquely identify each row in the
table.
Example: Result_Info
Reg.No Sub-Code Marks Result
Student S1 CS1 45 PASS
Stud T1 Subjects T2 S1 CS2 25 RA
S1 CS3 50 PASS
Reg No –P.K Sub Code–P.K S2 CS1 50 PASS
S2 CS2 40 PASS
Name Sub Name
S3 CS3 20 RA
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

COMPOSITE KEY
• When the columns are combined uniqueness is guaranteed.
But when it taken individually it does not guarantee
uniqueness.
• A composite key is also known as compound key in RDBMS.
Syntax:
Create table ResultInfo(Col1 VARCHAR(50), Col2
Varchar(30), primarykey(col1,Col2));
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
FOREIGN KEY
A primary key of one table is referred as a foreign key in another table.

Parent table Child Table F.Key


Dept-ID-P.K Dept-Name Prof-ID P-Name Dept-ID-F.K
101 CSE 1 Raya 101
102 ECE 2 Smith 102
103 CIVIL 3 Jack 102
104 MECH 4 Williams 103
5 Johnson 104

The table with the F.K is called the child table and The table with the P.K is called the
referenced (or) Parent table.
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

FOREIGN KEY

A F.Key is a field (or) collection of fields in one table


Single column F.Key accepted NULL Values.
The F.Key Constraints prevents:
• Invalid data from being inserted into the F.Key column
(or) field. Because It has to be one of the values
contained in the parent table.
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

FOREIGN KEY CONSTRAINTS


1. Cascade : On update Cascade
On Delete cascade
•Delete or update the row from the parent table and
automatically delete or update the matching rows in the child
table. Both ON DELETE CASCADE and ON UPDATE
CASCADE are supported.
Note
Cascaded foreign key actions do not activate triggers.
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

SYNTAX
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (col_name, ...)
REFERENCES tbl_name (col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION |
SET DEFAULT
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

Syntax:
create table dept(did int(5) primary key, dname varchar(50));

PARENT TABLE-Deapartment

Did-P.K Dname
101 CSE
102 Tamil
103 English
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

ON DELETE CASCADE
CHILD TABLE-Prof
Pid- Pname did-F.K
P.K
1 Raya 101
2 John 101
3 Maya 102
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
FOREIGN KEY CONSTRAINTS
2. SET NULL : On Update SET NULL
On Delete SET NULL
Delete or update the row from the parent table and set the foreign key column or
columns in the child table to NULL. Both ON DELETE SET NULL and ON
UPDATE SET NULL clauses are supported.
Syntax:
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

If you specify a SET NULL action, make sure


that you have not declared the columns in
the child table as NOT NULL.
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:

FOREIGN KEY CONSTRAINTS

3. SET DEFAULT : On Update SET DEFAULT


On Delete SET DEFAULT

• If the referenced values in the parent table are updated


(or) deleted. The related values in the child table with
F.Key columns will be set to its default value.
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Key and Referential Integrity Constraints:
FOREIGN KEY CONSTRAINTS
4. On update Restrict/No Action
On Delete Restrict / No Action

• Rejects the delete or update operation for the parent


table. Specifying RESTRICT (or NO ACTION) is the
same as omitting the ON DELETE or ON
UPDATE clause.
4.3 SPECIFYING BASIC CONSTRAINTS IN SQL
Specifying Key and Referential Integrity Constraints:
• FOREIGN KEY clause.
• Specifies referential integrity constraint
FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER)
• Options to avoid violations
• The options include SET NULL, CASCADE, and SET DEFAULT.
• An option must be qualified with either ON DELETE or ON UPDATE.
• The action for CASCADE ON DELETE is to delete all the referencing tuples,
• The action for CASCADE ON UPDATE is to change the value of the foreign key
to the updated (new) primary key value for all referencing tuples.

• Example:

FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ON


DELETE SET DEFAULT ON UPDATE CASCADE.
70
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Attribute Constraints and Default Values
• DEFAULT : The DEFAULT Constraint is used to fill a column with a
default and fixed value. The value will be added to all new records
when no other value is provided.
• It is also possible to define a default value for an attribute by
appending the clause DEFAULT <value> to an attribute definition.

Example : DNO INT NOT NULL DEFAULT 1

CREATE TABLE person ( ID int NOT NULL, Name varchar(255), Age


int, Location varchar(255) DEFAULT 'Noida');
Output: Select * from person;
ID Name Age Location
INSERT INTO person VALUES (4, 'Mira', 23, 'Delhi');
4 Mira 23 Delhi
INSERT INTO person VALUES (5, 'Hema', 27);
5 Hema 27 Noida
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Attribute Constraints and Default Values

• CHECK The CHECK constraint is used to limit the value range


that can be placed in a column.
• If you define a CHECK constraint on a column it will allow only
certain values for this column.
• If you define a CHECK constraint on a table it can limit the values
in certain columns based on values in other columns in the row.
Example : DNUMBER INT NOT NULL CHECK (DNUMBER > 0 AND DNUMBER < 21 )

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL
Specifying Attribute Constraints and Default Values

• Unique key is a constraint that is used to uniquely identify a


tuple in a table. Multiple unique keys can present in a table.
NULL values are allowed in case of a unique key. These can also be
used as foreign keys for another table.
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
4.3 SPECIFYING BASIC CONSTRAINTS IN SQL

Specifying Key and Referential Integrity Constraints:

• Giving Names to Constraints

• Constraints may be given a name, following the keyword


CONSTRAINT.
Example :
CONSTRAINT DEPTPK PRIMARY
KEY(DNUMBER)
– The names all the constraints must be unique within a schema.
– Constraints can be dropped or replaced with another
constraint. 74
4.3 SPECIFYING BASIC CONSTRAINTS IN
SQL

Specifying Key and Referential Integrity Constraints:

• Specifying Constraints on Tuples Using CHECK

• These are called tuple based constraints which are specified at


the end of a CREATE TABLE statement.
Example : CHECK ( DEPT_CREATE_DATE <MGRSTARTDATE);

75
4.3 SPECIFYING BASIC CONSTRAINTS IN SQL
Specifying Key and Referential Integrity Constraints:

76
4.4 Schema Change
Statement in SQL
4.4 SCHEMA CHANGE STATEMENT IN
SQL
What is a schema in SQL Server
A schema is a collection of database objects including
tables, views, triggers, stored procedures, indexes, etc. A schema is associated with
a username which is known as the schema owner, who is the owner of the logically
related database objects.

A schema always belongs to one database. On the other hand, a database may have
one or multiple schemas. For example, in our BikeStores sample database, we
have two schemas: sales and production.

An object within a schema is qualified using the


schema_name.object_name format like sales.orders.
4.4 SCHEMA CHANGE STATEMENT IN SQL

Built-in schemas in SQL Server


SQL Server provides us with some pre-defined schemas which have the same
names as the built-in database users and roles, for example: dbo, guest, sys,
and INFORMATION_SCHEMA.

Note that SQL Server reserves the sys and INFORMATION_SCHEMA schemas for
system objects, therefore, you cannot create or drop any objects in these schemas.

SQL Server CREATE SCHEMA statement:


CREATE SCHEMA schema_name
[AUTHORIZATION owner_name]
4.4 SCHEMA CHANGE STATEMENT IN SQL
• A schema can be changed by adding or dropping tables , attributes,
constraints and other schema elements.

The DROP Command

• Drop command is used to drop :

1. schema

2. tables

3. domains

4. constraints.

• DROP has two options : CASCADE & RESTRICT

Example : DROP SCHEMA COMPANY CASCADE;

– CASCADE option , when dropping a schema , will remove database schema and all its
tables, domains, and other elements.
– If RESTRICT option is chosen ,then schema is dropped only if it has no elements in it;80
otherwise, the DROP command will not be executed
4.4 SCHEMA CHANGE STATEMENT IN SQL

SQL Server DROP SCHEMA statement overview


The DROP SCHEMA statement allows you to delete a schema from a database.
The following shows the syntax of the DROP SCHEMA statement:
DROP SCHEMA [IF EXISTS] schema_name;
In this syntax:
1. First, specify the name of the schema that you want to drop. If the schema contains
any objects, the statement will fail. Therefore, you must delete all objects in the
schema before removing the schema.
2. Second, use the IF EXISTS option to conditionally remove the schema only if the
schema exists. Attempting to drop a non existing schema without the IF
EXISTS option will result in an error.
4.4 SCHEMA CHANGE STATEMENT IN SQL

SQL SERVER DROP SCHEMA STATEMENT EXAMPLE


First, create a new schema named logistics:
CREATE SCHEMA logistics;
GO
Next, create a new table named deliveries inside the logistics
schema:
CREATE TABLE logistics.deliveries
(
order_id INT PRIMARY KEY,
delivery_date DATE NOT NULL,
delivery_status TINYINT NOT NULL
);
4.4 SCHEMA CHANGE STATEMENT IN SQL
Then, drop the schema logistics:
DROP SCHEMA logistics;
SQL Server issued the following error because the schema is not empty.
Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'logistics' because it is being referenced by object
'deliveries'.
After that, drop the table logistics.deliveries:
DROP TABLE logistics.deliveries;
Finally, issue the DROP SCHEMA again to drop the logistics schema:
DROP SCHEMA IF EXISTS logistics;
Now, you will find that the logistics schema has been deleted from the database.
4.4 SCHEMA CHANGE STATEMENT IN SQL

MySQL: DROP TABLE Statement


The MySQL DROP TABLE statement allows you to remove or delete a
table from the MySQL database.
Syntax
DROP TABLE table_name;
However, the full syntax for the MySQL DROP TABLE statement is:
DROP [ TEMPORARY ] TABLE [ IF EXISTS ]
table_name1, table_name2, ...
[ RESTRICT | CASCADE ];
4.4 SCHEMA CHANGE STATEMENT IN
SQL
Parameters or Arguments
table_name
The name of the table to remove from the database.

table_name1, table_name2
The tables to remove from the database, if removing more than one table
in the DROP TABLE statement.

IF EXISTS
Optional. If specified, the DROP TABLE statement will not raise an error
if one of the tables does not exist.
4.4 SCHEMA CHANGE STATEMENT
IN SQL
Note
If you use the MySQL DROP TABLE statement to drop one or more tables that do
not exist, the database will raise an error (unless you specify the IF
EXISTS parameter in the DROP TABLE statement).
Example
Drop One Table
DROP TABLE customers;
Drop Multiple Tables
DROP TABLE customers, suppliers;
This DROP TABLE statement example would delete two tables
- customers and suppliers. If we were worried that one of the tables doesn't exist
and we don't want to raise an error, we could modify our DROP TABLE statement
as follows:
DROP TABLE IF EXISTS customers, suppliers;
This example would delete the customers and suppliers tables and would not raise an
error if one of the tables didn't exist.
4.4 SCHEMA CHANGE STATEMENT IN
SQL

1. The DROP Command

Example : DROP TABLE DEPEDENT ;

– CASCADE option , when dropping a table , will remove table and all its

definitions (including constraints)

– RESTRICT option is chosen, the table is dropped only if it is not

referenced in any constraints or views . Otherwise DROP command will not

be executed.

87
4.4 SCHEMA CHANGE STATEMENT IN
SQL
2. The ALTER TABLE Command
• The definition of a base table can be changed by using the ALTER TABLE
command.
• ALTER TABLE is used to

1. add a column (attribute)


2. drop a column (attribute)
3. change column definition,
4. add or dropping table constraints.
Examples:
1. ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);
2. ALTER TABLE EMPLOYEE DROP ADDRESS CASCADE;
3. ALTER TABLE DEPARTMENT ALTER MGRSSN DROP DEFAULT;
4. ALTER TABLE DEPARTMENT ALTER MGRSSN SET DEFAULT "333445555";
5. ALTER TABLE COMPANY.EMPLOYE DROP CONSTRAINT EMPSUPERFK 88
CASCADE;
4.4 SCHEMA CHANGE STATEMENT IN
SQL

SQL ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

ALTER TABLE - ADD Column


ALTER TABLE table_name
ADD column_name datatype;
4.4 SCHEMA CHANGE STATEMENT IN
SQL

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that


some database systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Oracle 10G and later:
ALTER TABLE table_name
MODIFY column_name datatype;
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example
Persons" table:

Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement:

ALTER TABLE Persons ADD DateOfBirth date;


4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-
digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example
RENAME COLUMN IN TABLE

Syntax
To rename a column in an existing table, the SQL ALTER TABLE syntax is:

For Oracle:
ALTER TABLE table_name RENAME COLUMN old_name TO new_name;
Example
ALTER TABLE supplier RENAME COLUMN supplier_name TO sname;

For MySQL:
ALTER TABLE table_name CHANGE COLUMN old_name TO new_name;
Example:
ALTER TABLE supplier CHANGE COLUMN supplier_name sname VARCHAR(100);
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example
RENAME TABLE

Syntax
To rename a table, the SQL ALTER TABLE syntax is:

For Oracle and MySQL :

ALTER TABLE table_name RENAME TO new_table_name;

Example

ALTER TABLE supplier RENAME TO vendor;


4.3 SPECIFYING BASIC CONSTRAINTS IN SQL

Specifying Key and Referential Integrity Constraints:

• Giving Names to Constraints

• Constraints may be given a name, following the keyword


CONSTRAINT.
Example :
CONSTRAINT DEPTPK PRIMARY
KEY(DNUMBER)
– The names all the constraints must be unique within a schema.
– Constraints can be dropped or replaced with another
constraint. 96
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example

Add a NOT NULL constraint to a column


Syntax
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

ADD UNIQUE CONSTRAINT to a table


ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint
UNIQUE(column1, column2...);

ADD CHECK CONSTRAINT


ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK
(CONDITION);

ADD PRIMARY KEY


ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY
(column1, column2...);
4.4 SCHEMA CHANGE STATEMENT IN
SQL
ALTER TABLE - ALTER/MODIFY COLUMN Example

DROP CONSTRAINT
ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint;

using MySQL
ALTER TABLE table_name DROP INDEX MyUniqueConstraint;

DROP PRIMARY KEY constraint


ALTER TABLE table_name DROP CONSTRAINT MyPrimaryKey;

using MySQL
ALTER TABLE table_name DROP PRIMARY KEY;
4.5 Basic Queries in SQL
4.5 BASIC QUERIES IN SQL
• SQL has one basic statement for retrieving information from a database: the
SELECT statement.
• An SQL table is not a set of tuples. So any 2 tuples can be identical in all their

Theattributes.
SELECT-FROM-WHERE Structure of SQL
Queries
• General form :
SELECT <attribute list>

FROM <table list>

WHERE <condition>

• <attribute list> is a list of attribute names whose values are to be retrieved by the query.

• <table list> is a list of the relation names required to process the query.

• <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query.
10
Logical Comparison Operators : =,>,<,>=,<=,<> (not equal) 0
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company
relational schema

10
1
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company relational schema

Populated
Databas
e

10
2
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company relational schema
Query 0: Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.

SELECT BDATE, ADDRESS

FROM EMPLOYEE

WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’

• the result of the query may contain duplicate tuples

•Q0 is similar to the following relational algebra


expression—except that duplicates, if any, would not
be eliminated:
πBDATE , ADDRESS ( FNAME=‘John’ AND MINIT=‘B’ AND LNAME=‘Smith’ (EMPLOYEE))

10
3
4.5 BASIC QUERIES IN SQL
Relational Algebra in DBMS: Operations with
Examples
9. Inner Join
1. SELECT(σ)
10.Theta Join
2. Projection(π)
11.EQUI join
12.NATURAL JOIN (⋈)
3. Rename (ρ)
4. Union operation (υ)
13.OUTER JOIN
5. Set Difference (-)
14.Left Outer Join
6. Intersection
15.Right Outer Join:
7. Cartesian product(X)
16.Full Outer Join:
8. Join Operations
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company relational schema

Query 1: Retrieve the name and address of all employees who work
for the 'Research' department.
Q1: SELECT name, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNUMBER=DNO AND DNAME='Research'

• Similar to a SELECT-PROJECT-JOIN sequence of relational algebra operations


(DNAME='Research') is a selection condition (corresponds to a SELECT
operation in relational algebra)
(DNUMBER=DNO) is a join condition (corresponds to a JOIN operation in
relational algebra)
10
5
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company relational schema

Query 2: For every project located in ‘blore', list the project number, the controlling
department number, and the department manager's name, address, and birthdate.
SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS

FROM PROJECT, DEPARTMENT, EMPLOYEE

WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION=‘blore’ ;

In Q2, there are two join conditions and one select


condition
• The join condition DNUM=DNUMBER relates a project to its controlling department.

• The join condition MGRSSN=SSN relates the department to the employee who manages that
department.

• PLOCATION=‘blore' is selection condition for Project table

10
6
10
7
4.5 BASIC QUERIES IN SQL
SELECT-FROM-WHERE : Example queries on company relational schema

10
Results of the SQL queries- Q0, Q1, Q2 8
4.5 BASIC QUERIES IN SQL

Ambiguous attribute names , Aliasing and Tuple Variables


• A query that refers to two or more attributes with the same
name must qualify the attribute name with the relation name by
prefixing the relation name to the attribute name by using dot(.)
notation to prevent ambiguity.
Example: Suppose that NAME and DNO attributes of EMPLOYEE table
were called NAME and DNUMBER, and DNAME attribute of the
DEPARTMENT was also called NAME. then Query1 must be restated
as follows.

SELECT NAME, EMPLOYEE.NAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.NAME='Research' AND 10
9
EMPLOYEE.DNUMBER=DEPARTMENT. DNUMBER
4.5 BASIC QUERIES IN SQL
SQL - Alias Syntax
You can rename a table or a column temporarily by giving another name known
as Alias. The use of table aliases is to rename a table in a specific SQL statement.
The renaming is a temporary change and the actual table name does not change in
the database. The column aliases are used to rename a table's columns for the
purpose of a particular SQL query.
Syntax
The basic syntax of a table alias is as follows.
SELECT column1, column2.... FROM table_name AS alias_name WHERE
[condition];
The basic syntax of a column alias is as follows.
SELECT column_name AS alias_name FROM table_name WHERE [condition];
4.5 BASIC QUERIES IN SQL
Example Example
Consider the following two tables. Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows. Table 2 − ORDERS Table is as follows.

table alias.
SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT FROM
CUSTOMERS AS C, ORDERS AS O WHERE C.ID = O.CUSTOMER_ID;
4.5 BASIC QUERIES IN SQL
Result.

Column alias.
SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME
FROM CUSTOMERS WHERE SALARY IS NOT NULL;
Result.
4.5 BASIC QUERIES IN SQL
1. How to Solve the “Ambiguous Name Column” Error in SQL
At times you may want to join two tables in SQL and there are in the
tables, columns with the same name.
In this case, if you join the two tables and run the query without
differentiating the names of the columns that are the same, the error
“Ambiguous name column”
For instance, you want to join two tables named TABLE1 and
TABLE2. TABLE1 contains these columns — EmployeeID, Name,
Salary. TABLE2 has these columns — EmployeeID, Name, Age.
create the tables.
CREATE TABLE TABLE1 (EmployeeID INT, Name VARCHAR(20), Salary INT)
CREATE TABLE TABLE2 (EmployeeID INT, Name VARCHAR(20), Age INT)
4.5 BASIC QUERIES IN SQL
Note that the two tables have a “Name” column in common apart from the
EmployeeID — which is always a number.
SELECT [Name], [Salary], [Name], [Age]FROM TABLE1 A INNER JOIN TABLE2
B ON A.EmployeeID = B.EmployeeID
If you run the above query, you will get this error — “Ambiguous name column”.
This means two columns have the same column name — that is the “Name” column. The SQL
Machine is confused as to which “Name” out of the two tables you are referring to. It is ambiguous
— not clear.
To clarify this, add the alias of either or both TABLE1 or TABLE2 to the columns having the same
name. You will notice above, the alias of TABLE1 is A while that of TABLE2 is B.
So, let’s fix the bug.
SELECT A.[Name], [Salary], B.[Name], [Age]FROM TABLE1 A INNER JOIN
TABLE2 B ON A.EmployeeID = B.EmployeeID
Run the query. No error!
4.5 BASIC QUERIES IN SQL
Ambiguous attribute names , Aliasing and Tuple Variables
• Ambiguity also arises if some queries need to refer to the same
relation twice
• In this case, aliases are given to the relation name
1. Query 8: For each employee, retrieve the employee's name,
and the name of his or her immediate supervisor.
Q8: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN
• In Q8, the alternate relation names E and S are called aliases or tuple
variables for the EMPLOYEE relation
• We can think of E and S as two different copies of EMPLOYEE; E represents
employees in role of supervisees and S represents employees in role of
supervisors
11
• Use of AS is optional. E.g. : Use EMPLOYEE E, instead of EMPLOYEE 5
4.5 BASIC QUERIES IN SQL

Unspecified WHERE-clause and use of Asteric (*)


• A missing WHERE-clause indicates no condition; hence, all tuples
of the relations in the FROM-clause are selected.
• This is equivalent to the condition WHERE TRUE

Query 9 and Query 10: Retrieve the SSN values for all employees.
Q9: SELECT SSN
FROM EMPLOYEE
• If more than one relation is specified in the FROM-clause and
there is no join condition, then the CARTESIAN PRODUCT of tuples
is selected.
Q10: SELECT SSN, DNAME 11
FROM EMPLOYEE, DEPARTMENT; 6
4.5 BASIC QUERIES IN SQL
Unspecified WHERE-clause and use of Asteric (*)
• An Asterisk (*) used in SELECT Clause to select all the attributes.

Q1C : SELECT *

FROM EMPLOYEE

WHERE DNO=5;

Q1D : SELECT *

FROM EMPLOYEE, DEPARTMENT

WHERE DNAME=‘Research’ AND DNO=DNUMBER;

Q10A : SELECT *

FROM EMPLOYEE, DEPARTMENT;

Q10A specifies CROSS PRODUCT of EMPLOYEE and DEPARTMENT 11


7
4.5 BASIC QUERIES IN SQL
The keyword DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list
the different (distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Demo Database

11
8
4.5 BASIC QUERIES IN SQL
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the
"Country" column in the "Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct)
customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;

11
9
4.5 BASIC QUERIES IN SQL

The keyword DISTINCT


• SQL does not treat a relation as a set; duplicate tuples can appear
• To eliminate duplicate tuples in a query result, the keyword DISTINCT is used.

Query 11 : Retrieve the salary of every employee (Q11) and all distinct salary values (Q11A)

Q11 : SELECT SALARY FROM EMPLOYEE;

Q11A : SELECT DISTINCT SALARY FROM EMPLOYEE;

12
0
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
• For union , the keyword is UNION
• For set difference the keyword is EXCEPT
• For set intersection the keyword is INTERSECT

• The relations resulting from these operations are


set of tuples ; duplicates tuples are eliminated
from the result.
• The relations must be type compatible
relations 12
1
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


The SQL Set operation is used to combine the two or more SQL SELECT
statements.
Types of Set Operation
1. Union
2. UnionAll
3. Intersect
4. Minus
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


1. Union
• The SQL Union operation is used to combine the result of
two or more SQL SELECT queries.
• In the union operation, all the number of datatype and
columns must be same in both the tables on which UNION
operation is being applied.
• The union operation eliminates the duplicate rows from its
resultset.
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


1. Syntax(UNION)
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations (UNION)
The First table

SELECT * FROM First


UNION
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
The resultset table
SELECT * FROM First
UNION
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


2. Union All
Union All operation is equal to the Union operation. It returns
the set without removing duplication and sorting the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
The First table

SELECT * FROM First


UNION ALL
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
The resultset table
SELECT * FROM First
UNION ALL
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


3. INTERSECT
• It is used to combine two SELECT statements. The Intersect
operation returns the common rows from both the SELECT
statements.
• In the Intersect operation, the number of datatype and
columns must be the same.
• It has no duplicates and it arranges the data in ascending
order by default.
4.5 BASIC QUERIES IN SQL

Set theoretic Operations

Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
The First table

SELECT * FROM First RESULT:


INTERSECT
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


4. Minus
It combines the result of two SELECT statements.
Minus operator is used to display the rows which are
present in the first query but absent in the second
query.
It has no duplicates and data arranged in ascending
order by default.
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


Syntax
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
4.5 BASIC QUERIES IN SQL
Set theoretic Operations
The First table

RESULT:
SELECT * FROM First
MINUS
SELECT * FROM Second;
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


EXCEPT:
1. In SQL, EXCEPT returns those tuples that are returned
by the first SELECT operation, and not returned by the
second SELECT operation.
2. This is the same as using a subtract operator in
relational algebra.
4.5 BASIC QUERIES IN SQL

Set theoretic Operations


Example:
Say we have two relations, Students and TA
(Teaching Assistant). We want to return all those
students who are not teaching assistants. The
query can be formulated as:
4.5 BASIC QUERIES IN SQL
Set theoretic Operations

SELECT Name
FROM Students
EXCEPT Output:
SELECT NAME 1. Rohan
FROM TA;
2. Mansi
3. Megha
4.5 BASIC QUERIES IN SQL

Difference between EXCEPT and NOT IN Clause


EXCEPT automatically removes all duplicates in the
final result, whereas NOT IN retains duplicate tuples.
It is also important to note that EXCEPT is not
supported by MySQL.
4.5 BASIC QUERIES IN SQL
Set theoretic Operations

Example for UNION:


QUERY 4 : Make a list of all project numbers for projects that involve an employee whose last name is
'Smith', either as a worker or as a manager of the department that controls the project.

Q4: (SELECT DISTINCT PNUMBER FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE


DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith’)

UNION

(SELECT DISTINCT PNUMBER

FROM PROJECT, WORKS_ON, EMPLOYEE

WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith');

14
0
4.5 BASIC QUERIES IN SQL
MultiSet Operations

3 multi set operations:


1. UNION ALL
2. EXCEPT ALL
3. INTERSECT ALL

• Their results are multi set (duplicates are not


removed ) Basically, each tuple-whether it is a
duplicate or not -is considered as a different tuple
when applying these operations.
14
1
4.5 BASIC QUERIES IN SQL
MultiSet Operations

3 multi set operations:


1. UNION ALL

1. The UNION ALL command combines the result set of two or more
SELECT statements (allows duplicate values).
When comparing UNION vs. UNION ALL, there is one major
difference:
2. UNION only returns unique
3. UNION ALL returns all records, including duplicates.

14
2
4.5 BASIC QUERIES IN SQL
MultiSet Operations

3 multi set operations:


1. UNION ALL Syntax
2. UNION ALL combines the results of two or
more SELECT statements, showing all values, including
duplicates if they exist.

SELECT column_1, column_2


FROM table_1
[WHERE condition]
UNION ALL
SELECT column_1, column_2
FROM table_2 14
3
[WHERE condition]
4.5 BASIC QUERIES IN SQL
MultiSet Operations

Result
SELECT name, location
FROM book_club
UNION
Result
SELECT name, location
FROM rowing_club SELECT name,
location
FROM book_club
UNION ALL
SELECT name,
location
FROM rowing_club
14
4
4.5 BASIC QUERIES IN SQL
MultiSet Operations

3 multi set operations:


1. Except

1. In SQL, EXCEPT returns those tuples that are returned by the first
SELECT operation, and not returned by the second SELECT
operation.
2. This is the same as using a subtract operator in relational algebra.
Except ALL

To retain duplicates, we must explicitly write EXCEPTALL instead of


EXCEPT.
14
5
4.5 BASIC QUERIES IN SQL
MultiSet Operations
Example:
Say we have two relations, Students and TA (Teaching
Assistant). We want to return all those students who are
not teaching assistants. The query can be formulated as:

Result
SELECT Name FROM
Students EXCEPT Result
SELECT NAME FROM TA; To retain duplicates, we must Output:
explicitly write EXCEPTALL instead Rohan
Output: of EXCEPT.
Rohan Mansi
Mansi SELECT Name FROM Mansi
Megha Students EXCEPTALL Megha
SELECT Name FROM
TA;
14
6
4.5 BASIC QUERIES IN SQL
MultiSet Operations
3 multi set operations:
INTERSECT

Intersect returns the common rows of two or more table. Intersect


removes the duplicate after combining.
INTERSECT ALL

Intersect all does not remove duplicate.


Note :
Both INTERSECT and INTERSECT ALL returns the common rows of
two different SQLs. They differ in the way they handle duplicates.

14
7
4.5 BASIC QUERIES IN SQL
MultiSet Operations
Result
SELECT * FROM SummerFruits
INTERSECT
SELECT * FROM Fruits;
Result

SELECT * FROM SummerFruits Result


INTERSECT ALL
SELECT * FROM Fruits
14
8
4.5 BASIC QUERIES IN SQL
MultiSet Operations

Examples

Figure 8.5 The results of SQL multiset operations. (a) Two


tables, R(A) and S(A). (b) R(A) UNION ALL S(A). (c) R(A)
EXCEPT ALL S(A).
(d) R(A) INTERSECT ALL S(A). 14
9
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators

• The LIKE comparison operator can be used for string pattern matching.

• Partial strings are specified using two reserved characters:

1. % replaces an arbitrary number of zero or more characters

_
2. the underscore ( ) replaces a single character.

QUERY 12 : Retrieve all employees whose address is in Houston.


Q12: SELECT FNAME, LNAME FROM EMPLOYEE
WHERE ADDRESS LIKE '%Houston%';

QUERY 12A : Find all employees who were born during the 1950s.
Q12A: SELECT FROM WHERE
FNAME, LNAME EMPLOYEE
BDATE LIKE ‘195 _ _ _ _ _ _ _'; 15
0
[YYYY-MM-DD]
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators

LIKE Syntax

SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;
15
1
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:

15
2
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

Q1. Select all students starting with “a”

SELECT * FROM students


WHERE studentname LIKE 'a%'; 15
3
Q1. Select all students starting with “a”

4.5 BASIC QUERIES IN SQL


Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

Q2. Select all students with a studentname ending with “i”

SELECT * FROM students


WHERE studentname LIKE '%i’; 15
4
Q1. Select all students starting with “a”

4.5 BASIC QUERIES IN SQL


Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

Q3. Select all students with a studentname that have “li” in any positio

SELECT * FROM students


WHERE studentname LIKE '%li’; 15
5
Q1. Select all students starting with “a”

4.5 BASIC QUERIES IN SQL


Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

Q4. Select all students with a studentname that have “o” in the second position:

SELECT * FROM students


WHERE studentname LIKE '_o%’;
15
6
Q1. Select all students starting with “a”

4.5 BASIC QUERIES IN SQL


Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

elect all students with a studentname that start with “a” and are at least 5 character

T * FROM students
E studentname LIKE '%a____%’;
15
7
Q1. Select all students starting with “a”

4.5 BASIC QUERIES IN SQL


Substring Pattern Matching and Arithmetic Operators
Examples of LIKE operators
Consider the following table on which we will apply various operations of the LIKE
operator.

Select all students with a studentname that start with “s” and end with “y”
ECT * FROM students
ERE studentname LIKE 's%y';
15
8
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators
• If an underscore or % is needed as a literal character in the string, the character should
be preceded by an escape character, which is specified after the string using the
keyword ESCAPE.

For example:
'AB\_CD\%EF' ESCAPE '\' represents the literal string ‘AB_CD%EF',
because \ is specified as the escape character

• If an apostrophe (') is needed, it is represented as two consecutive apostrophes (") so


that it will not be interpreted as ending the string.

15
9
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators
• The standard arithmetic operators for addition (+), subtraction (-),
multiplication (*), and division (/) can be applied to numeric values or
attributes with numeric domains.
Example :
QUERY 13 : Show the resulting salaries if every employee working on the
'ProductX' project is given a 10 percent raise.

Q13: SELECT FNAME, LNAME, 1.1 * SALARY AS INCREASED_SAL


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN AND PNO=PNUMBER AND
PNAME='ProductX'; 16
0
4.5 BASIC QUERIES IN SQL
Substring Pattern Matching and Arithmetic Operators
• Another comparison operator that can be used for convenience is BETWEEN,
which is illustrated in Query 14.
QUERY 14 : Retrieve all employees in department 5 whose salary is between
$30,000 and $40,000.
Q14: SELECT * FROM EMPLOYEE
WHERE (SALARY BETWEEN 30000 AND 40000) AND DNO =5;

Note : The condition (SALARY BETWEEN 30000 AND 40000) in Q14 is equivalent
to the condition ((SALARY >= 30000) AND (SALARY <= 40000)

16
1
4.5 BASIC QUERIES IN SQL
Ordering of Query Results

The SQL ORDER BY Keyword


1. The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
2. The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

16
2
4.5 BASIC QUERIES IN SQL
Ordering of Query Results
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:
Example
SELECT * FROM Customers
ORDER BY Country;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING
by the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
16
3
4.5 BASIC QUERIES IN SQL
Ordering of Query Result
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
and the "CustomerName" column. This means that it orders by Country, but if some rows have the
same Country, it orders them by CustomerName:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
ORDER BY Several Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
16
4
4.5 BASIC QUERIES IN SQL
Ordering of Query Results
• SQL allows the user to order the tuples in the result of a query by the values of one or
more attributes, using the ORDER BY clause.
QUERY 15 : Retrieve a list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, first
name.
Q15: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER
ORDER BY DNAME, LNAME, FNAME;
Note : 1. The default order is in ascending order of values.
2. We can specify the keyword DESC if we want to see the result in a descending
order of values. 16
5
4.6 More Complex
SQL Queries
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

• SQL has 3 kinds of NULL values.

1. Unknown value, but existing

A particular person has a date of birth but it is not


known.

2. Unavailable values :

we do not know whether a person has a home phone


number.
16
3. Not applicable attribute value: 7
4.6 MORE COMPLEX SQL QUERIES

Comparisons Involving NULL and Three-Valued Logic

• SQL uses a three-valued logic with values TRUE, FALSE, and


UNKNOWN

• Table 8.1 shows the result of three-valued logic when logical


connectives AND, OR, and NOT are used .

16
8
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic

• SQL uses a three-valued logic with values TRUE, FALSE, and


UNKNOWN

• Table 8.1 shows the result of three-valued logic when logical


connectives AND, OR, and NOT are used .

16
9
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

NULLs and Three-Valued Logic


• The reason that NULLs can sometimes trip people up has to
do with something called three-valued logic. While binary or
Boolean logic has two values (“true” and “false”), three-
valued logic (abbreviated as 3VL and also known as ternary
logic) has an additional value — “unknown”.
• 3VL with a simple scenario. Suppose we want to obtain the
names of employees who make more than € 1,200 a month.
The employee table looks like this:
17
0
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

NULLs and Three-Valued Logic

SELECT * FROM employee WHERE bonus + salary > 1200;

17
1
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

3VL in SQL Queries


We should see three records in the result set, but there are only two. Why is Peter
White not included? The reason is related to the NULL value in the bonus column.
In SQL, every arithmetic operation that includes an operand with a NULL
value returns a NULL result.
look at how Peter White’s record was evaluated:
1800 + NULL > 1200
Peter’s salary (1,800) and his bonus (NULL) added up to NULL. We can reduce this
condition to :
NULL > 1200

17
2
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

3VL in SQL Queries

So is NULL greater than 1,200? Remember that NULL


represents a nonexistent value, which means we don’t
have anything to compare against 1,200: we can’t know if
this statement is true or false. This is how three-valued
logic works. When we have a NULL value in a condition,
the result of this condition will be “unknown”.

17
3
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
3VL in SQL Queries
how records are filtered in the WHERE clause.
Only records that evaluate to “true” in the WHERE clause are
part of the query result set.
Records evaluating to “false” or “unknown” are not part of the
result.
This is why Peter White’s record was left out of the previous
query results. His total salary evaluates to “Unknown” in the
WHERE clause; “1800 + NULL > 1200” is “Unknown”
because we cannot know what NULL is.
17
4
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
3VL in SQL Queries
AND, OR and NOT tables are also important in three-valued logic,

NOT tables AND tables

Let’s analyze why “false” AND “unknown” equates


to “false”. One “false” is enough to make the
entire result “false” in an AND operation.
OR
tables

17
5
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic

3VL in SQL Queries


A query that uses the OR operator:
SELECT * FROM employee WHERE salary < 1500 OR bonus > 200

Notice that one record containing a NULL value in the “bonus” column is
shown in the result, but the other NULL record is not. The reason is the OR
operator. Since the condition salary < 1500 is true, it is not necessary to 17
6
evaluate the condition bonus > 200.
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic

• SQL allows queries that check whether an attribute value is NULL.


• SQL uses IS or IS NOT rather than using = or <> to compare an
attribute value to NULL. This is because SQL considers each NULL
value as being distinct from every other NULL value, so equality
comparison is not appropriate.
QUERY 18 : Retrieve the names of all employees who do not have
supervisors.
Q18: SELECT FNAME, LNAME FROM EMPLOYEE

WHERE SUPERSSN IS NULL;

17
7
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic
1. The SQL NULL is the term used to represent a missing value. A NULL value in a
table is a value in a field that appears to be blank.
2. A field with a NULL value is a field with no value. It is very important to understand
that a NULL value is different than a zero value or a field that contains spaces.
Syntax
The basic syntax of NULL while creating a table.

SQL> CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) ); 17
); 8
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic
Example
The NULL value can cause problems when selecting data. However, because when
comparing an unknown value to any other value, the result is always unknown and
not included in the results. You must use the IS NULL or IS NOT NULL operators
to check for a NULL value. IS NOT NULL operator.
SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS WHERE SALARY IS NOT
NULL;

17
9
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic
Example
The NULL value can cause problems when selecting data. However, because when
comparing an unknown value to any other value, the result is always unknown and
not included in the results. You must use the IS NULL or IS NOT NULL operators
to check for a NULL value.
IS NULL operator.
SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS WHERE SALARY IS NULL;

18
0
Nested Queries and Set Comparisons
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
• Queries can be conveniently formulated by using nested
queries
• Nested queries are complete select-from-where blocks within
the WHERE clause of another query.
• That other query is called the outer query.

• Comparison operator IN, which compares a value v with a set


of values V and evaluates to TRUE if v is one of the elements in V

18
2
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons

• A Subquery or Inner query or a Nested query is a query within another


SQL query and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as
a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.

18
3
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
There are a few rules that subqueries must follow −
1. Subqueries must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
3. An ORDER BY command cannot be used in a subquery, although the main query
can use an ORDER BY.
4. Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
5. The BETWEEN operator cannot be used with a subquery. However, the
BETWEEN operator can be used within the subquery.

18
4
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons

1. Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement.
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
18
5
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
Example
Consider the CUSTOMERS table having the following records
SQL> SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM
CUSTOMERS WHERE SALARY > 4500) ;
Result

18
6
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
2. Subqueries with the INSERT Statement
Subqueries also can be used with INSERT statements. The INSERT
statement uses the data returned from the subquery to insert into
another table. The selected data in the subquery can be modified with
any of the character, date or number functions.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
18
7
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
Example
Consider a table CUSTOMERS_BKP with similar structure as
CUSTOMERS table. Now to copy the complete CUSTOMERS table
into the CUSTOMERS_BKP table, you can use the following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN
(SELECT ID FROM CUSTOMERS) ;

18
8
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
3. Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement.
Either single or multiple columns in a table can be updated when using
a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
18
[ WHERE) ] 9
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
Example
Assuming, we have CUSTOMERS_BKP table available which is backup
of CUSTOMERS table. The following example updates SALARY by
0.25 times in the CUSTOMERS table for all the customers whose AGE
is greater than or equal to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP WHERE AGE >= 27 );

19
0
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons

SQL> UPDATE CUSTOMERS


SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
Result:

19
1
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
4. Subqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement
like with any other statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

19
2
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
Example
Assuming, we have a CUSTOMERS_BKP table available which is a
backup of the CUSTOMERS table. The following example deletes the
records from the CUSTOMERS table for all the customers whose AGE
is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP
WHERE AGE >= 27 );

19
3
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons

SQL> SQL> DELETE FROM CUSTOMERS


WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP
Result:
WHERE AGE >= 27 );

19
4
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
1. Example :

• Query 4 can be rephrased to use nested queries as shown in Q4A.

(Make a list of all project numbers for projects that involve an employee whose last name is 'Smith',
either as a worker or as a manager of the department that controls the project.)

Q4A: SELECT DISTINCT PNUMBER FROM PROJECT

WHERE PNUMBER IN

(SELECT PNUMBER FROM PROJECT, DEPARTMENT, EMPLOYEE

WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME=‘Smith’)

OR

PNUMBER IN (SELECT PNO FROM WORKS_ON, EMPLOYEE

1. WHERE ESSN=SSN AND LNAME='Smith');


19
5
4.6 MORE COMPLEX SQL
QUERIES
Nested Queries and Set Comparisons
• The IN operator can also compare a tuple of values in parentheses with a set or multiset of union-
compatible tuples.

SELECT DISTINCT ESSN FROM WORKS_ON

WHERE (PNO, HOURS) IN

(SELECT PNO, HOURS FROM WORKS_ON WHERE SSN=‘123456789’);

•This query will select the social security numbers of all employees who work the same
(project, hours) combination on some project that employee 'John Smith' (whose SSN
='123456789') works on.
•In this example, the IN operator compares the subtuple of values in parentheses (PNO,
HOURS) for each tuple in WORKS_ON with the set of union-compatible tuples produced by19
6
the nested query.
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
• In addition to the IN operator, ANY , SOME and ALL comparison operators can be
used to compare a single value v (typically an attribute name) to a set or multiset V
(typically a nested query).
• ANY , SOME , ALL can be used with =, >,>=, <, <=, and < >.
Example : Retrieve names of employees whose salary is greater than the salary of all the
employees in department 5:
SELECT LNAME, FNAME FROM EMPLOYEE
WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE WHERE DNO=5)

• The = ANY (or = SOME) operator returns TRUE if the value v is equal to some value in
the set V and is hence equivalent to IN.

19
7
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
• In general, we can have several levels of nested queries. We can
once again be faced with possible ambiguity among attribute names
if attributes of the same name exist-one in a relation in the FROM
clause of the outer query, and another in a relation in the FROM
clause of the nested query.

•The rule is that a reference to an unqualified attribute refers to the


relation declared in the innermost nested query.

•To refer to an attribute of the PROJECT relation specified in the outer


19
query, we can specify and refer to an alias (tuple variable) for that8
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
•To illustrate the potential ambiguity of attribute names in nested
queries, consider Query 16.
QUERY 16 : Retrieve the name of each employee who has a dependent with the same
first name and same sex as the employee.
Q16: SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E
WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE
E.FNAME=DEPENDENT_NAME AND E.SEX=SEX);
•In the nested query of Q16, we must qualify E. SEX because it refers to the SEX attribute of
EMPLOYEE from the outer query, and DEPENDENT also has an attribute called SEX.
•All unqualified references to SEX in the nested query refer to SEX of DEPENDENT.
•However, we do not have to qualify FNAME and SSN because the DEPENDENT relation
does not have attributes called FNAME and SSN, so there is no ambiguity.
19
9
Correlated Nested Queries
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries
• Whenever a condition in the WHERE clause of a nested query references some
attribute of a relation declared in the outer query, the two queries are said to
be correlated.

•We can understand a correlated query better by considering that the nested
query is evaluated once for each tuple (or combination of tuples) in the outer
query

•For example, we can think of Q16 as follows:


For each EMPLOYEE tuple, evaluate the nested query, which retrieves the
20
ESSN values for all DEPENDENT tuples with the same sex and name as that
1
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries

•In general, a query written with nested select-from-


where blocks and using the = or IN comparison
operators can always be expressed as a single block
query. For example, Q16 may be written as in Q16A:
•Q16A: SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.SSN=D.ESSN AND E.SEX=D.SEX AND
E.FNAME=D.DEPENDENT_NAME;

20
2
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries

SQL correlated subquery which is a subquery that uses values from


the outer query.
If a sub query depends on outer query or the outer query depends on
inner query
Finds employees whose salary is greater than the average
salary of all employees:
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE salary >
(SELECT AVG(salary) FROM
employees);
20
3
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries

SQL correlated subquery which is a subquery that uses values from the outer query.
If a sub query depends on outer query or the outer query depends on inner query

Finds employees whose salary is greater than


the average salary of all employees:

SELECT employee_id, first_name, last_name, salary


FROM employees
WHERE salary >
(SELECT AVG(salary) FROM employees);

20
4
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries
Finds employees whose salary is greater than SELECT employee_id, first_name, last_name, salary
the average salary of all employees: FROM employees
WHERE salary >
(SELECT AVG(salary) FROM employees);
In this example, the subquery is used in the WHERE clause.
First, you can execute the subquery that returns the average salary of all employees
independently.

SELECT AVG(salary) FROM employees;

Second, the database system needs to evaluate the subquery only once.
Third, the outer query makes use of the result returned from the subquery. The
outer query depends on the subquery for its value. However, the subquery does not
depend on the outer query. Sometimes, we call this subquery is a plain subquery. 20
5
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries

SQL correlated subquery which is a subquery that uses values


from the outer query.
If a sub query depends on outer query or the outer query depends
on inner query
Syntax:
SELECT column1,column2,…..
FROM table_name T1
WHERE condition IN | NOT IN
(SELECT column1, FROM table_name T2
WHERE T1.column = T2.column)
20
6
4.6 MORE COMPLEX SQL QUERIES
Correlated Nested Queries

SQL correlated subquery which is a subquery that uses values from the outer query.
If a sub query depends on outer query or the outer query depends on inner query

SELECT employee_id, first_name from employee e


where department_id in
(select department_id from departments d
where d.department_id = e.department_id);

20
7
The EXISTS and UNIQUE Functions in SQL
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

•The EXISTS function in SQL is used to check whether the result of a


correlated nested query is empty (contains no tuples) or not. If the result of a
correlated nested query contains at least one tuple , it returns TRUE .
Otherwise returns FALSE
Query 16
Q16B: in anE.FNAME,
SELECT alternative form that uses EXISTS. This is shown as QI6B:
E.LNAME
FROM EMPLOYEE AS E
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE E.SSN=ESSN AND
E.SEX=SEX AND E.FNAME=DEPENDENT_NAME);

•In general, EXISTS(Q) returns TRUE if there is at least one tuple in th


20
result of the nested query Q, and it returns FALSE otherwise. 9
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

•The EXISTS condition in SQL is used to check whether the result of a


correlated nested query is empty (contains no tuples) or not. The result of
EXISTS is a boolean value True or False. It can be used in a SELECT,
UPDATE, INSERT or DELETE statement.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name 21
0
WHERE condition);
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Examples:
Consider the following two relation “Customers” and “Orders”.

SELECT fname, lname FROM Customers WHERE EXISTS (SELECT *


21
FROM Orders WHERE Customers.customer_id = Orders.c_id); 1
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
1.Using EXISTS condition with SELECT statement
To fetch the first and last name of the customers who placed atleast
one order.

SELECT fname, lname


FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
21
2
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

•On the other hand, NOTEXISTS(Q) returns TRUE if there are no tuples in the
result of nested query Q, and it returns FALSE otherwise

QUERY 6 : Retrieve the names of employees who have no dependents.


Q6: SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN);

We can explain Q6 as follows:


For each EMPLOYEE tuple, the correlated nested query selects all DEPENDENT tuples whose
ESSN value matches the EMPLOYEE SSN; if the result is empty, no dependents are related to
21
the employee, so we select that EMPLOYEE tuple and retrieve its FNAME and LNAME. 3
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

2. Using NOT with EXISTS


Fetch last and first name of the customers who has not placed any order.

Syntax:
SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);

21
4
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Examples:
Consider the following two relation “Customers” and “Orders”.

SELECT fname, lname FROM Customers WHERE NOT EXISTS (SELECT * 21


FROM Orders WHERE Customers.customer_id = Orders.c_id); 5
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Using NOT with EXISTS
Fetch last and first name of the customers who has not placed any order.

SELECT fname, lname


FROM Customers
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);

21
6
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

3. Using EXISTS condition with DELETE statement


Delete the record of all the customer from Order Table whose last name is
‘Mehra’.

DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
21
7
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Examples:
Consider the following two relation “Customers” and “Orders”.

DELETE FROM Orders WHERE EXISTS (SELECT * FROM Customers WHERE


Customers.customer_id = Orders.c_id AND Customers.lname = 'Mehra'););
21
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Using EXISTS condition with DELETE statement
Delete the record of all the customer from Order Table whose last name is
‘Mehra’.
DELETE FROM Orders WHERE EXISTS (SELECT * FROM customers
WHERE Customers.customer_id = Orders.cid AND Customers.lname =
'Mehra');
SELECT * FROM Orders;

21
9
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

4. Using EXISTS condition with UPDATE statement


Update the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.

UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);

22
0
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Examples:
Consider the following two relation “Customers” and “Orders”.

UPDATE Customers SET lname = 'Kumari' WHERE EXISTS (SELECT * FROM


Customers WHERE customer_id = 401); 22
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
Using EXISTS condition with
DELETE statement
Delete the record of all the customer
from Order Table whose last name is
‘Mehra’.
UPDATE Customers SET lname = 'Kumari'
WHERE EXISTS (SELECT * FROM
Customers WHERE customer_id = 401);

SELECT * FROM Customers;


22
2
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
UNIQUE
As you do with the EXISTS predicate, you use the UNIQUE predicate with a subquery.
Although the EXISTS predicate evaluates to True only if the subquery returns at least
one row, the UNIQUE predicate evaluates to True only if no two rows returned by the
subquery are identical. In other words, the UNIQUE predicate evaluates to True only if
all the rows that its subquery returns are unique.
SELECT FirstName, LastName FROM CUSTOMER WHERE UNIQUE (SELECT CustomerID
FROM SALES WHERE SALES.CustomerID = CUSTOMER.CustomerID);

This statement retrieves the names of all new customers for whom the SALES
table records only one sale. Because a null value is an unknown value, two null
values aren’t considered equal to each other; when the UNIQUE keyword is
applied to a result table that contains only two null rows, the UNIQUE predicate
evaluates to True. 22
3
4.6 MORE COMPLEX SQL QUERIES

The EXISTS and UNIQUE Functions in SQL


QUERY 7 : List the names of managers who have at least one dependent.

Q7: SELECT FNAME, LNAME FROM EMPLOYEE


WHERE EXISTS (SELECT * FROM DEPENDENT WHERE
SSN=ESSN)
AND EXISTS ( SELECT * FROM DEPARTMENT WHERE SSN=MGRSSN);
First selects all DEPENDENT tuples related to an EMPLOYEE, and the second selects all
DEPARTMENT tuples managed by the EMPLOYEE. . If at least one of the first and at least
one of the second exists, we select the EMPLOYEE tuple.

22
4
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

• Query 3 can be stated using EXISTS and NOT EXISTS


in SQL systems.
("Retrieve the name of each employee who works on all the projects controlled by
department number 5,” )
Q3A: SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS ((SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5)

EXCEPT
(SELECT PNO FROM WORKS_ON WHERE
22
SSN=ESSN) ); 5
4.6 MORE COMPLEX SQL QUERIES

The EXISTS and UNIQUE Functions in SQL

• The second option is shown as Q3B.


Q3B: SELECT LNAME, FNAME FROM EMPLOYEE
WHERE NOT EXISTS (SELECT * FROM WORKS_ON B
WHERE (B.PNO IN (SELECT PNUMBER FROM
PROJECT
WHERE DNUM=5) )
AND
NOT EXISTS (SELECT * FROM WORKS_ON 22
6
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL

• The second option is shown as Q3B.

Q3B: SELECT LNAME, FNAME FROM EMPLOYEE


WHERE NOT EXISTS (SELECT * FROM WORKS_ON B
WHERE (B.PNO IN (SELECT PNUMBER FROM
PROJECT
WHERE DNUM=5) )
AND
NOT EXISTS (SELECT * FROM WORKS_ON 22
7
C
4.6 MORE COMPLEX SQL QUERIES
Explicit Sets and Renaming of Attributes in SQL

• It is also possible to use an explicit set of values in the


WHERE clause, rather than a nested query. Such a set is
enclosed in parentheses in SQL.
QUERY 17 : Retrieve the social security numbers of all
employees who work on project numbers 1,2, or 3.

Q17: SELECT DISTINCT ESSN FROM


WORKS_ON 22
8
4.6 MORE COMPLEX SQL QUERIES
Explicit Sets and Renaming of Attributes in SQL

• In SQL, it is possible to rename any attribute that


appears in the result of a query by adding the qualifier
AS followed by the desired new name. The new names
will appear as column headers in the query result.
Q8A: SELECT E.LNAME AS EMPLOYEE_NAME, S.LNAME AS

SUPERVISOR_NAME FROM EMPLOYEE AS E, EMPLOYEE

AS S 22
9
4.6 MORE COMPLEX SQL QUERIES
Joined Tables in SQL

• The concept of a joined table (or joined relation) is used to specify a table
resulting from a join operation in the FROM clause of a query.
•For example
consider query1, which retrieves the name and address of every
employee who works for the 'Research' department. It may be easier first to
specify the join of the EMPLOYEE and DEPARTMENT relations, and then to
select the desired tuples and attributes.

QIA: SELECT FNAME, LNAME, ADDRESS

FROM (EMPLOYEE JOIN DEPARTMENT ON

DNO=DNUMBER)
23
0
4.6 MORE COMPLEX SQL QUERIES
Joined Tables in SQL
The SQL JOIN joins two tables based on a common column, and selects records that have
matching values in these columns.
Example
SELECT Customers.customer_id, Customers.first_name, Orders.amount FROM Customers
JOIN Orders
ON Customers.customer_id = Orders.customer;

23
1
4.7 AGGREGATE
FUNCTIONS IN SQL
4.7 AGGREGATE FUNCTIONS IN SQL
COUNT, SUM, MAX, MIN, and AVG.

•The COUNT function returns the number of tuples or values as specified in a


query.
•The functions SUM, MAX, MIN, and AVG are applied to a set or multiset of
numeric values and return, respectively, the sum, maximum value, minimum
value, and average (mean) of those values.
•These functions can be used in the SELECT clause or in a HAVING clause
(which we introduce later).
•The functions MAX and MIN can also be used with attributes that have
nonnumeric domains
23
3
4.7 AGGREGATE FUNCTIONS IN SQL
SQL Aggregate Functions:

•SQL aggregation function is used to perform the calculations on multiple rows of a


single column of a table. It returns a single value.
•It is also used to summarize the data.

Types of SQL Aggregation Function

23
4
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.


1. COUNT FUNCTION

•COUNT function is used to Count the number of rows in a database table.


It can work on both numeric and non-numeric data types.
•COUNT function uses the COUNT(*) that returns the count of all the rows
in a specified table. COUNT(*) considers duplicate and Null.

Syntax

COUNT(*)
or 23
COUNT( [ALL|DISTINCT] expression ) 5
4.7 AGGREGATE FUNCTIONS IN SQL
COUNT, SUM, MAX, MIN, and AVG.

23
6
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

SELECT COUNT(*)
FROM PRODUCT_MAST;

Output:
10

23
7
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

COUNT with WHERE

SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;

Output:
7
23
8
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

COUNT() with DISTINCT

SELECT COUNT(DISTINCT
COMPANY)
FROM PRODUCT_MAST;

Output:
3
23
9
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

COUNT() with GROUP BY

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST
GROUP BY COMPANY;
Output:
Com1 5
Com2 3 24
0
Com3 2
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

COUNT() with HAVING

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>2;
Output:
Com1 5
24
Com2 3 1
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

2. SUM Function

Sum function is used to calculate


the sum of all selected columns.
It works on numeric fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression ) 24
2
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

2. SUM Function

Example: SUM()

SELECT SUM(COST)
FROM PRODUCT_MAST;

Output:
670 24
3
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

2. SUM() with WHERE

Example: SUM()

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;

Output: 24
320 4
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

Example: SUM() with GROUP BY

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com3 170 24
5
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

Example: SUM() with HAVING

SELECT COMPANY, SUM(COST)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST)>=170;

Output:
Com1 335 24
Com3 170 6
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

3. AVG function

The AVG function is used to


calculate the average value of the
numeric type. AVG function returns
the average of all non-Null values.
Syntax
AVG()
or 24
AVG( [ALL|DISTINCT] expression ) 7
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

3. AVG function

Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;

Output:
67.00
24
8
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

4. MAX Function
MAX function is used to find the
maximum value of a certain column.
This function determines the largest
value of all selected values of a column.

Syntax
MAX()
or 24
MAX( [ALL|DISTINCT] expression ) 9
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;

Output:
30

25
0
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.


5. MIN Function
MIN function is used to find the
minimum value of a certain
column. This function determines
the smallest value of all selected
values of a column.
Syntax
MIN()
or
MIN( [ALL|DISTINCT] expression ) 25
1
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;

Output:
10
25
2
4.7 AGGREGATE FUNCTIONS IN SQL
COUNT, SUM, MAX, MIN, and AVG.
QUERY 19
Find the sum of the salaries of all employees, the maximum salary, the
minimum salary, and the average salary.
Q19: SELECT SUM (SALARY), MAX (SALARY), MIN (SALARY),AVG
(SALARY)
FROM EMPLOYEE;
QUERY 20 : Find the sum of the salaries of all employees of the
'Research' department, as well as the maximum salary, the minimum
salary, and the average salary in this department.
Q20: SELECT SUM (SALARY), MAX (SALARY), MIN (SALARY), AVG
(SALARY) FROM EMPLOYEE ,DEPARTMENT WHERE DNO=DNUMBER and 25
3
DNAME='Research';
4.7 AGGREGATE FUNCTIONS IN SQL
COUNT, SUM, MAX, MIN, and AVG.

QUERIES 21 AND 22
Retrieve the total number of employees in the company (Q21) and the
number of employees in the 'Research' department (Q22).
Q21: SELECT COUNT (*) FROM EMPLOYEE;
Q22: SELECT COUNT (*) FROM EMPLOYEE,DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research';

Here the asterisk (*) refers to the rows (tuples), so COUNT (*)
returns the number of
25
rows in the result of the query 4
4.7 AGGREGATE FUNCTIONS IN SQL
COUNT, SUM, MAX, MIN, and AVG.

•We may also use the COUNT function to count values in a column rather than
tuples, as in the next example.
QUERY 23
Count the number of distinct salary values in the database.
Q23: SELECT COUNT (DISTINCT SALARY) FROM EMPLOYEE;

• If we write COUNT(SALARY) instead of COUNT(DISTINCT SALARY) in Q23, then


duplicate values will not be eliminated.
• Any tuples with NULL for SALARY will not be counted.
•In general, NULL values are discarded when aggregate functions are applied to a
25
5
particular column (attribute).
4.7 AGGREGATE FUNCTIONS IN SQL

COUNT, SUM, MAX, MIN, and AVG.

• We can specify a correlated nested query with an aggregate function, and then
use the nested query in the WHERE clause of an outer query.
For example, to retrieve the names of all employees who have two or more
dependents (Query 5), we can write the following:

Q5: SELECT LNAME, FNAME FROM EMPLOYEE

WHERE (SELECT COUNT (*)


FROM DEPENDENT
WHERE SSN=ESSN) >= 2 25
6
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES
•The GROUP BY clause specifies the grouping attributes, which should also appea
in the SELECT clause, so that the value resulting from applying each aggregate
function to a group of tuples appears along with the value of the grouping
attributes.
QUERY 24 : For each department, retrieve the department number, the

number of employees in the department, and their average salary.


Q24: SELECT COUNT (*), AVG (SALARY)

FROM EMPLOYEE GROUP BY DNO;

• In Q24, the EMPLOYEE tuples are partitioned into groups-each group having the same
value for the grouping attribute DNO.
25
• The COUNT and AVG functions are applied to each such group of tuples. 7
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES

QUERY 24 :
Grouping EMPLOYEE tuples by the value of
DNO

25
8
4.8 GROUPING: THE GROUP BY AND HAVING
CLAUSES

• If NULLs exist in the grouping attribute, then a separate


group is created for all tuples
with a NULL value in the grouping attribute.

QUERY 25 : For each project, retrieve the project number, the project

name, and the number of employees who work on that project.


Q25: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT,
WORKS_ON
WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME;
25
9
4.8 GROUPING: THE GROUP BY AND HAVING
CLAUSES

QUERY 26 : For each project on which more than two employees work,

retrieve the project number, the project name, and the number of

employees who work on the project.

Q26: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON

WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME

HAVING COUNT (*) > 2

26
0
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES

QUERY 26 : After applying the WHERE clause


but before applying HAVING

26
1
4.8 GROUPING: THE GROUP BY AND HAVING
CLAUSES
QUERY 26 : After applying the HAVING clause
condition

26
2
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES
QUERY 26 : After applying the HAVING clause
condition
QUERY 27
For each project, retrieve the project number, the project
name, and the number of employees from department 5 who
work on the project.
Q27: SELECT PNUMBER, PNAME, COUNT (*)

FROM PROJECT, WORKS_ON, EMPLOYEE

WHERE PNUMBER=PNO AND SSN=ESSN AND

DNO=5 26
3
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES
QUERY 28
For each department that has more than five employees,
retrieve the department number and the number of its
employees who are making more than $40,000.
Q28: SELECT DNUMBER, COUNT (*)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY>40000 AND
DNO IN (SELECT DNO FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT (*) > 5)
GROUP BY DNUMBER;

26
4
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL

In SQL, three commands can be used to modify the database:


INSERT, DELETE, and UPDATE.
The INSERT Command :
• INSERT is used to add a single tuple to a relation.
• We must specify the relation name and a list of values for the
tuple.
• The values should be listed in the same order in which the
corresponding attributes were specified in the CREATE TABLE
Adding a new tuple :
command.
UI: INSERT INTO EMPLOYEE VALUES ('Richard', 'K', 'Marini',
26
5
'653298653', '1962-12-30', '98 Oak Forest,Katy,TX', 'M', 37000,
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN
SQL
Another form of the INSERT Command :
• A second form of the INSERT statement allows the user to
specify explicit attribute names that correspond to the values
provided in the INSERT command.
• This is useful if a relation has many attributes but only a few of
those attributes are assigned values in the new tuple.
• However, the values must include all attributes with NOT NULL
specification and no default value.
• Attributes with NULL allowed or DEFAULT values are the ones
that can be left out.

26
6
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN
SQL
Another form of the INSERT Command :

For example, to enter a tuple for a new EMPLOYEE for whom we know
only the FNAME, LNAME, DNO, and SSN attributes, we can use U1A:

UIA: INSERT INTO VALUES EMPLOYEE (FNAME, LNAME, DNO,


SSN)
('Richard', 'Marini', 4, '653298653');
• Attributes not specified in U lA are set to their DEFAULT or to NULL

26
7
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL

Inserting multiple tuples using select

• A variation of the INSERT command inserts multiple tuples into a


relation in conjunction with creating the relation and loading it with the
result of a query.
• For example, to create a temporary table that has the name,
number of employees, and total salaries for each department, we can
write the statements
U3A: CREATEinTABLE
U3A and (U3B:
DEPT_NAME VARCHAR(15),
NO_OF_EMPS INTEGER,
TOTAL_SAL INTEGER 26
8
);
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL

Inserting multiple tuples using select

U3B: INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS,

TOTAL_SAL)

SELECT DNAME, COUNT (*), SUM (SALARY)

FROM (DEPARTMENT JOIN EMPLOYEE ON DNUMBER=DNO)

GROUP BY DNAME;
• A table DEPTS_INFO is created by U3A and is loaded with the summary
information retrieved from the database by the query in U3B. 26
9
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
The DELETE Command

• The DELETE command removes tuples from a relation. It can include

WHERE clause to select the tuples to be deleted.

• Tuples are explicitly deleted from only one table at a time

• The deletion may propagate to tuples in other relations if referential

triggered actions are specified in the referential integrity constraints of

the DDL

•A missing WHERE clause specifies that all tuples in the relation are to27
0
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
The DELETE Command

U4A: DELETE FROM EMPLOYEE WHERE LNAME='Brown';

U4B: DELETE FROM EMPLOYEE WHERE SSN='123456789';

U4C: DELETE FROM EMPLOYEE WHERE

DNO IN ( SELECT DNUMBER

FROM DEPARTMENT

WHERE DNAME='Research');
27
U4D: DELETE FROM EMPLOYEE; (becomes empty table) 1
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL

The UPDATE Command

• The UPDATE command is used to modify attribute values of one or more


selected tuples.
• As in the DELETE command, a WHERE clause in the UPDATE command
selects the tuples to be modified from a single relation.
• However, updating a primary key value may propagate to the foreign key
values of tuples in other relations if such a referential triggered action is
specified in the referential integrity constraints of the DDL
• An additional SET clause in the UPDATE command specifies the attributes
to be modified and their new values. 27
2
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN
SQL
The UPDATE Command

• For example, to change the location and controlling


department number of project number 10 to 'Bellaire' and 5,
respectively, we use US:

U5: UPDATE PROJECT SET PNUMBER=10 , DNUM = 5

WHERE PLOCATION = 'Bellaire‘;

27
3
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
The UPDATE Command

• Several tuples can be modified with a single UPDATE command. An example is to


give all employees in the 'Research' department a 10 percent raise in salary, as shown
in U6.
U6: UPDATE EMPLOYEE SET SALARY = SALARY *1.1
WHERE DNO IN ( SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research');
• It is also possible to specify NULL or DEFAULT as the new attribute value.
• Notice that each UPDATE command explicitly refers to a single relation only.
27
4
DISCUSSION
5 MINUTES

Identify data, Software for DBMS

You might also like