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

2 D

Uploaded by

notaugusto7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

2 D

Uploaded by

notaugusto7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

1

SYLLABUS

•Structure of Relational Databases - Integrity Constraints, Synthesizing ER


diagram to relational schema
•Introduction to Relational Algebra - select, project, cartesian product operations,
join - Equi-join, natural join. query examples,
•Introduction to Structured Query Language (SQL), Data Definition Language
(DDL), Table definitions and operations – CREATE, DROP, ALTER,
INSERT, DELETE, UPDATE.
Relational data model

•Represent database as a collection of relations


•Relation is a table which has values and rows in table is a collection of related data values
•Each row in table is a fact
•Row in relational table is called a tuple, column header is attribute and table is a relation

Attributes
Relation name

EMPLOYEE
EMP_NO Name Address Mobile number Age Salary
Tuples 101 RAM XYZ 9898989898 20 10000
102 SAM CVF 9999999999 21 20000
103 SITA FDFD 888888888 22 30000
4
•In the relational model, all data is logically structured within relations (also called table)
•Informally a relation may be viewed as a named two- dimensional
table representing an entity set.

•A relation has a fixed number of named columns and variable number of rows.
Components of relational database

•The main components of relational database structure are as follows:


1. Domains
2. Tuples (rows)
3. Columns (attributes)
4. Keys
5. Relations (Tables)
Domain
•It has three parts
Name

Data type

Format

•A Domain is allowed set of atomic values.


•Atomic means each value in the domain is indivisible to the relational model.
7

•A domain has a logical definition: e.g.“USA_phone_numbers” are the set of 10


digit phone numbers valid in the U.S.

•A domain may have a data-type or a format defined for it.


The USA_phone_numbers may have a format: (ddd)-ddd- dddd where each d is a
decimal digit. E.g.,
Dates have various formats such as month name, date, year or yyyy-mm-dd, or dd
mm,yyyy etc
8
•A tuple is an ordered set of values
•Tuple is a portion of a table containing data that described only entity, relationship, or
object
•Also known as record
•Each value is derived from an appropriate domain.

• <Kumar,Singh, 52/57 store, 9889898989> is a tuple belonging to


223001, CUSTOMER relation. the
Columns
•Columns in a table are also called attributes or fields of the relation.
•A single cell in a table called field value, attribute value or data element.
•For example, for the entity person, attributes could include eye colour and height.
10 Key of a Relation
•Each row has a value of a data item (or set of items) that uniquely identifies that row in
the table called the key
•Sometimes row-ids or sequential numbers are assigned as keys to identify the rows in a
table called artificial key or surrogate key
Relations
•A table of values
(Tables)

•A relation may be thought of as a set of rows.


•A relation may alternately be thought of as a set of columns.
•That is a table is perceived as a two-dimensional structure composed of rows and
columns.

•Each row represents a fact that corresponds to a real-world entity or relationship.


•Each row has a value of an item or set of items that uniquely identifies that row in the table
•Sometimes row-ids or sequential numbers are assigned to identify the rows in the
table.
•Each column typically is called by its column name or column header or
attribute name.
Schema of a
Relation
•It is basically an outline of how data is organized
•It is denoted by R (A1, A2, .....An)
Here R is relation name and
it has some attributes A1 to An
•Each attribute have some domain and it is represented by dom(Ai)
•Relation schema is used to describe a relation and R is name of the relation
•Each attribute has a domain or a set of valid values.
For example, the domain of Cust-id is 6 digit numbers.
Degree of a relation

•Degree of a relation is number of attributes in a relation


•Eg
STUDENT(Id, Name, Age,

Departmentno) Has degree 4

•Using datatype of each the definition can be written as

STUDENT(Id:Integer, Name:String,Age:integer, Departmentno:integer)


Relation State
•The relation state is a subset of the Cartesian product of the domains of its attributes
each domain contains the set of all possible values the attribute can take.
•Example: attribute Cust-name is defined over the domain of character strings of maximum
length 25

dom(Cust-name) is varchar(25)
•The role these strings play in the CUSTOMER relation is that of the name of a
customer.
15 •A relation state r(R) is a mathematical relation of degree n on the domains dom(A1),
dom(A2)…, dom(An) which is a subset of Cartesian product(X) of domains that define
R

•Cartesian product specifies all possible combination of values from


underlying domains
Cardinality in domain D
•Cardinality in domain D by |D| then the total number of tuples in Cartesian product is
•|dom(A1)| X |dom(A2)| ……. X |dom(An)|

Current relation state

•Reflects only a particular state of real world


•As the state of real world changes, so does the relation state, by being transformed into
another relation state


Alternative Definition of a Relation

•ordering of values in a tuple is unnecessary


•a relation schema R = {A1, A2, ..., An} is a set of attributes, and
•a relation state r(R) is a finite set of mappings r = {t1, t2, ..., tm}, where each tuple ti is
a mapping from R to D, and

•D is the union (denoted by 𝖴) of the attribute domains; that is,


D = dom(A1) 𝖴 dom(A2) 𝖴 ... 𝖴 dom(An).
•Here t[Ai] must be in dom(Ai) for 1 ≤ i ≤ n for each mapping t in r.
•Each mapping ti is called a tuple.
18

Tuple can be considered as a set of (<attribute>,


<value>) pairs, where each pair gives the value of the mapping from an attribute
Ai to a value vi from dom(Ai).
The ordering of attributes is not important, because the attribute name appears
with its value.
Formal Definitions - Summary

•Formally,
Given R(A1, A2, .........., An)
r(R) ⊂ dom (A1) X dom (A2) X ....X dom(An)
•R(A1, A2, …, An) is the schema of the relation
•R is the name of the relation
•A1, A2, …, An are the attributes of the relation
•r(R): a specific state (or "value" or “population”) of relation R –
this is a set of tuples (rows)

r(R) = {t1, t2, …, tn} where each ti is an n-tuple


ti = <v1, v2, …, vn> where each vj element-of dom(Aj)
Formal Definitions - Example
•Let R(A1, A2) be a relation
schema: Let dom(A1) = {0,1}

Let dom(A2) = {a,b,c}


•Then: dom(A1) X dom(A2) is all possible combinations:
{<0,a> , <0,b> , <0,c>, <1,a>, <1,b>, <1,c> }
•The relation state r(R) dom(A1) X dom(A2)
•For example: r(R) could be {<0,a> , <0,b> , <1,c> }
this is one possible state (or “population” or “extension”) r of the relation
R, defined over A1 and A2.

It has three 2-tuples: <0,a> , <0,b> , <1,c>


21

Informal Terms Formal Terms


Table Relation
Column Header Attribute
All possible Domain
Column Values
Row Tuple

Table Definition Schema of a Relation


Populated Table State of the Relation
22
Characteristics of Relation
•Ordering of tuples in a relation r(R):
The tuples are not considered to be ordered, even though they appear to be in the tabular
form.

•Ordering of attributes in a relation schema R (and of values within each tuple):


We will consider the attributes in R(A1, A2, ..., An) and the values in t=<v1, v2, ..., vn> to
be ordered .

(However, a more general alternative definition of relation does not require this ordering).
•Values in a tuple:
24
All values are considered atomic (indivisible).

Each value in a tuple must be from the domain of the attribute for that column
If tuple t = <v1, v2, …, vn> is a tuple (row) in the relation state r of R(A1, A2, …,

An) Then each vi must be a value from dom(Ai)

A special null value is used to represent values that are unknown or inapplicable to certain
tuples.

•Notation:

Component values of a tuple t by:t[Ai] or t.Ai

This is the value vi of attribute Ai for tuple t


Similarly, t[Au, Av, ..., Aw] refers to the sub-tuple of t containing the values of attributes Au, Av, ...,
Aw, respectively in t
Relational Integrity Constraints

•Constraints are conditions that must hold on all valid relation states.
•There are three main types of constraints in the relational model:
✔ Key constraints
✔ Entity integrity constraints
✔ Referential integrity constraints
•Another implicit constraint is the domain constraint
Every value in a tuple must be from the domain of its attribute (or it could be null,
if allowed for that attribute)
Types of keys:
Primary key
Key used to identify one and only one instance of an entity uniquely.
An entity can contain multiple keys, as we saw in the PERSON
table.
The key which is most suitable from those lists becomes a primary key.
EMPLOYEE table, ID can be the primary key since it is unique for each employee.
In the EMPLOYEE table, we can even select License_Number and
Passport_Number as primary keys since they are also unique.
Candidate key

•A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
•Except for the primary key, the remaining attributes are considered a candidate key.
•The candidate keys are as strong as the primary key.
Eg. EMPLOYEE table, id is best suited for the primary key. The rest of the attributes, like
SSN, Passport_Number, License_Number, etc., are considered a candidate key.
Super key

Super key is an attribute set that can uniquely identify a


tuple. A super key is a superset of a candidate key.
EMPLOYEE table- (EMPLOEE_ID, EMPLOYEE_NAME), the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this
combination can also be a key.

The super key would be EMPLOYEE-ID or (EMPLOYEE_ID, EMPLOYEE-NAME), etc.


Foreign key
Foreign keys are the column of the table used to point to the primary key of another
table.
Every employee works in a specific department in a company, and employee and
department are two different entities. So we can't store the department's information in
the employee table. That's why we link these two tables through the primary key of one
table. We add the primary key of the DEPARTMENT table, Department_Id, as a new
attribute in the EMPLOYEE table.
In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.
Alternate key

There may be one or more attributes or a combination of attributes that uniquely


identify each tuple in a relation.
These attributes or combinations of the attributes are called the candidate keys.
One key is chosen as the primary key from these candidate keys, and the
remaining candidate key, if it exists, is termed the alternate key.
Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite
key. This key is also known as Concatenated Key.

Artificial key
The key created using arbitrarily assigned data are known as artificial keys.
These keys are created when a primary key is large and complex and has no
relationship with many other relations.

The data values of the artificial keys are usually numbered in a serial order.
Key Constraints

•Super key of R:
Is a set of attributes SK of R with the following condition:
No two tuples in any valid relation state r(R) will have the same value for

SK That is, for any distinct tuples t1 and t2 in r(R), t1[SK] ≠ t2[SK]

•This condition must hold in any valid state r(R)

• Key of R:
✔ A "minimal" super key
✔ That is, a key is a super key K such that removal of any attribute from K results
in a set of attributes that is not a super key (does not possess the superkey
uniqueness property)
Entity Integrity
The primary key attributes PK of each relation schema R in S cannot have null
values in any tuple of r(R).

✔ This is because primary key values are used to identify the individual tuples.
✔ t[PK] ≠ null for any tuple t in r(R)
✔ If PK has several attributes, null is not allowed in any of these attributes
Note: Other attributes of R may be constrained to disallow null values, even though
they are not members of the primary key.
Referential Integrity

•A constraint involving two relations


The previous constraints involve a single relation.
•Used to specify a relationship among tuples in two relations:

The referencing relation and the referenced relation.

• Tuples in the referencing relation R1 have attributes FK (called foreign key

attributes) that reference the primary key attributes PK of the referenced relation

R2.

• A tuple t1 in R1 is said to reference a tuple t2 in R2 if t1[FK] = t2[PK].


• A referential integrity constraint can be displayed in a relational database schema as a
directed arc from R1.FK to R2.
36 Statement of the constraint
The value in the foreign key column (or columns) FK of the the
referencing relation R1 can be either:
(1)a value of an existing primary key value of a correspondingprimary key PK in the
referenced relation R2, or

(2) a null.
•In case (2), the FK in R1 should not be a part of its own primary key.
Relational Database Schema
A set S of relation schemas that belong to the same
database. S is the name of the whole database schema

S = {R1, R2, ..., Rn}


R1, R2, …, Rn are the names of the individual relation schemas within the database S
Displaying a relational Database Schema and its S

Constraints
•Each relation schema can be displayed as a row of attribute names
•The name of the relation is written above the attribute names
•The primary key attribute (or attributes) will be underlined
•A foreign key (referential integrity) constraints is displayed as a directed arc (arrow)
from the foreign key attributes to the referenced table

Can also point the primary key of the referenced relation for clarity
Populated database state

•Each relation will have many tuples in its current relation state
•The relational database state is a union of all the individual relation states
•Whenever the database is changed, a new state arises
•Basic operations for changing the database:
INSERT a new tuple in a relation
DELETE an existing tuple from a relation
MODIFY an attribute of an existing tuple
40
Update Operations on Relations

1. INSERT a tuple.
2. DELETE a tuple.
3. MODIFY a tuple.
• Integrity constraints should not be violated by the update operations.
•Several update operations may have to be grouped together.
•Updates may propagate to cause other updatesautomatically.
• This may be necessary to maintain integrity constraints.
42

•In case of integrity violation, several actions can be taken:


Cancel the operation that causes the violation (RESTRICT or REJECT option)
Perform the operation but inform the user of the violation
Trigger additional updates so the violation is
(CASCADE
corrected SET NULL option) option,

Execute a user-specified error-correction routine


Possible violations for each operation
•INSERT may violate any of the constraints:

• Domain constraint:
•if one of the attribute values provided for the new tuple is not of the specified
attribute domain

• Key constraint:
•if the value of a key attribute in the new tuple already exists in another tuple in the relatio

• Referential integrity:
•if a foreign key value in the new tuple references a primary key value that does not
exist i the referenced relation

• Entity integrity: if the primary key value is null in the new tuple
44

DELETE may violate only referential integrity:


If the primary key value of the tuple being deleted is referenced from other tuples in the
database
Can be remedied by several actions: RESTRICT, CASCADE, SET
NULL RESTRICT option: reject the deletion
CASCADE option: propagate the new primary key value into the foreign keys of the
referencing tuples

SET NULL option: set the foreign keys of the referencingtuples to NULL
One of the above options must be specified during database design for each foreign
key constraint
45 •UPDATE may violate domain constraint and NOT NULL constraint on an attribute being
modified

•Any of the other constraints may also be violated, depending on the attribute being updated:
Updating the primary key (PK):
Similar to a DELETE followed by an
INSERT Need to specify similar options to
DELETE

Updating a foreign key (FK):


May violate referential integrity
Updating an ordinary attribute (neither PK nor FK):
Can only violate domain constraints
Synthesizing ER Diagram to relational schema Entities and Simple
attributes

•An entity type within ER diagram is turned into a table.


•Each attribute turns into a column in the table.
•The key attribute of the entity is the primary key of the table which is usually
underlined.
•It is highly recommended that every table should start with its primary key
attribute conventionally named as TablenameID.
47

Person_id
DoB

Person
Name Gender

•The initial relational schema is expressed in the following format writing the table names with
the attributes list inside a parentheses as shown below for

PERSONS( personid , name, dateOfBirth, gender)


•personid is the primary key for the table : Persons
48

PePrNO
H O
s o Phone Phone
-1 -2
Person_id nN_Ei-d
DoB Person_id
Phone
Person
Name Gender

•If you have a multi-valued attribute, take the attribute and turn it into a new entity or table
of its own.
•Then make a 1: N relationship between the new entity and the existing one.
•Create a table for the attribute.
Add the primary (id) column of the parent entity as a foreign key within the new
table PERSONS( personid , name, dateOfBirth, gender)
PERSONS_PHONE(personid ,phone)
personid within the table Phones is a foreign key referring to the personid of Persons
1: 1 Relationship

PHONE
-NO DoB Wife_id
Person_id

Person Has-a Wife Name


Name

Gender

•For cases when the Person is not married i.e. has no wifeID, the attribute can set
to NULL
PERSONS( personid , name, dateOfBirth, gender,wifeid)

PERSONS_PHONE(personid ,phone) WIFE(wifeid , name )


1: N Relationship Phone Phone
-1 -2
PHONE
Person_id
-NO DoB Phone
Person_id

Person Has-a House Number


Name

Gender House_id Addr

•For instance, the Person can have a House from zero to many , but a House
can be owned by only one Person.
•To represent such relationship the personid asthe Parent node must be
placed within the Child table as a foreign key
PERSONS( personid , name, dateOfBirth, gender)
PERSONS_PHONE(personid ,phone)
HOUSE(houseid, personid, number, address)
M:N Relationships
Weak
Entity

BUILDING( Building_No, Building_name, Address)


APARTMENT(Buiding_No ,Door_No, floor )
53
54

CAR(Car_ID,
Serial_Number,Model_Number,Color,Year,Customer_ID,Emp_ID)
CUSTOMER(Customer_ID,Name, PhoneNumber, Address, Country,
City)
EMPLOYEE(Emp_ID, Name, Address)

EMPLOYEE_QUALIFICATION(Emp_ID,Qualification

) INVOICE(Invoice_ID,Date,Emp_ID,Customer_ID)
55
56

EMPLOYEE(Emp_ID, First_Name,Last_Name,DOB,Company_Id,Project_Id)
EMPLOYEE_CONTACT_NUMBER(Emp_ID,Contact_Number)
COMPANY(Company_Id,Company_Name,Location)
PROJECT(Project_Id,Project_Name,Start_Date)
SALARY(EMP_Id,Amount,Date_Of_Salary,Mode_of_Payment)
•select
• project
•cartesian product operations
•join - Equi-join
•natural join
•query examples

57
58

•Relational algebra is a procedural query language, which takes instances of relations as


input and yields instances of relations as output.

•It uses operators to perform queries. An operator can be either unary or binary.
•They accept relations as their input and yield relations as their output.
•Relational algebra is performed recursively on a relation and intermediate results are also
considered relations.
59

•The basic set of operations for the relational model is the relational algebra.
•These operations enable a user to specify basic retrieval requests as
relational algebra expressions.
•The result of a retrieval is a new relation, which may havebeen formed from one or
more relations.
•The algebra operations thus produce new relations, which can be further manipulated
using operations of the same algebra.
•A sequence of relational algebra operations forms a relational algebra expression,
whose result will also be a relation that represents the result of a database query
60
61

1. SELECT
2. PROJECT
3. RENAME
The SELECT Operation
•The SELECT operation is used to choose a subset of the tuples from a relation that
satisfies a selection condition.
•SELECT operation restricts the tuples in a relation to
tuples thatsatisfy the
only those condition

•Horizontal partition of the relation into two sets of tuples


•Those tuples that satisfy the condition and are selected, and those tuples that do not satisfy the
conditions are discarded.
62 SELECT Operation
Select the EMPLOYEE tuples whose department is 4, or those whose salary is greater
than $30,000 σDno=4(EMPLOYEE)
σ (EMPLOYEE)
Salary>3000
In general, the SELECT operation is denoted by σ<Selection Condition> (R)
R is generally a relational algebra expression whose result is a relation—the simplest
such expression is just the name of a database relation.

The relation resulting from the SELECT operation has the same attributes as R.
•The Boolean expression specified in <selection condition> is made up of a number of
clauses of the form

•Clauses can be connected by the standard Boolean operators and, or, and not to form a
general selection condition.
63
Select the tuples for all employees who either work in department 4 and
make over $25,000 per year, or work in department 5 and make over $30,000,
σ(Dno=4 AND Salary>25000) OR (Dno=5 AND Salary>30000) (EMPLOYEE)
64

•Result of a SELECT operation can be determined as follows:


•The <selection condition> is applied independently to each individual tuple t
in R.
•This is done by substituting each occurrence of an attribute Ai in the
selection condition with its value in the tuple t[Ai].

•If the condition evaluates to TRUE, then tuple t is selected.


•All the selected tuples appear in the result of the SELECT operation.
65

Interpretation of Boolean conditions AND, OR, and


NOT
•(cond1 AND cond2) is TRUE
if both (cond1) and (cond2) are TRUE;
otherwise, it is FALSE.

•(cond1 OR cond2) is TRUE


if either (cond1) or (cond2) or both are TRUE;
otherwise, it is FALSE.
•(NOT cond) is TRUE
if cond is FALSE;
otherwise, it is
FALSE.
66

•its number of attributes


•is the same as the degree of R.
•The number of tuples in the resulting relation is
than or equal to
always less number of tuples in R. the

• |σ c (R) |<= | R|

•The fraction of tuples selected by a selection referred to as


condition is the
selectivity of the condition.
67

•SELECT operation is commutative

σ c1(σ c2(R)) = σ c2(σ c1(R))

•a sequence of SELECTs can be applied in any order.


•we can always combine a cascade (or sequence) of SELECT operations into a single
SELECT operation with a conjunctive (AND) condition; that is,

σc1 (σc2 (. . . (σcn (R)))) = σc1 AND c2 AND ... AND cn (R)
68
•PROJECT operation selects certain columns from the table and discards the other columns.
•If we are interested in only certain attributes of a relation, we use the PROJECT operation to project
the relation over these attributes only

•vertical partition of the relation into two relations


one has the needed columns (attributes) and contains the result of the operation, and the other
contains the discarded columns.

The general form of PROJECT :π<attribute list>(R)

•Example: list each employee’s first and last name and salary

πLname,Fname,SALARY (EMP LOY EE)


69
Consider the Student
relation

πName, Age(Student) π
ID, Name(Student)
70

•The result of the PROJECT operation has only the attributes


specified in <attribute
list> in the same order as they appear in the list.

•Hence, its degree is equal to the number of attributes in <attribute list>.


Duplicate Elimination in PROJECT

# of tuples of π attribute list(R) ≤ # of tuples of R


•The PROJECT operation removes any duplicate tuples, so the result of the PROJECT
operation is a set of distinct tuples, and hence a valid relation.

•This is known as duplicate elimination.


71
72 •The number of tuples in a relation resulting from a PROJECT operation is always
less than or equal to the number of tuples in R.

•as long as <list2> contains the attributes in <list1>;


•otherwise, the left-hand side is an incorrect expression.
•commutativity does not hold on PROJECT.

•πlist1 (πlist2 (R)) = πlist1 (R) when list2


contains the attributes of list1
73
74

•For most queries, we need to apply several relational algebra operations one after the
other.
Either we can write the operations as a single relational algebra expression by
nesting the operations, or
we can apply one operation at a time and create intermediate result

relations we must give names to the relations that hold the intermediate

results.
75

Retrieve the first name, last name, and salary of all employees who work in
department number 5
we must apply a SELECT and a PROJECT operation

Example- Intermediate Relation


76

•The results of the operations that we are performing are saved without any name.
•If we want to give some name to the result of any operation then we
can rename the
result of the operations using the rename operation.

•It can also be used to rename an old relation. It is denoted by


symbol rho (ρ).
•Notation 1: Naming the result of an operation
ρh(E) where the result of expression E is stored as
h.

•Notation 2: Renaming an already existing column


ρ (E)
77
To rename the attributes in a relation, we simply list the new attribute names in
parentheses,
78

•If no renaming is applied, the names of the attributes in the resulting relation of a
SELECT operation are the same as those in the original relation and in the same
order.
•PROJECT operation with no renaming, the resulting relation has the same attribute
names as those in the projection list and in the same order in which they appear in the
list.
79

•RENAME operation when applied to a relation R of degree n is denoted by any of


the
following three forms

•symbol ρ (rho) is used to denote the RENAME operator,


•S is the new relation name, and B1, B2, ..., Bn are the new attribute
names. First expression renames both the relation and its attributes,

Second renames the relation only,

and Third renames the attributes

only.
80

•UNION:
✔ The result of this operation, denoted by R 𝖴 S, is a relation that includes all tuples that are
either in R or in S or in both R and S.

✔ Duplicate tuples are eliminated.


•INTERSECTION:
The result of this operation, denoted by R ∩ S, is a relation that includes all tuples that
are in both R and S.

•SET DIFFERENCE (or MINUS):


The result of this operation, denoted by R – S, is a relation that includes all tuples that
are in R but not in S.

• UNION, INTERSECTION, and SET DIFFERENCE are binary operations;


that is, each is applied to two sets
81

•Two relations R(A1, A2, ..., An) and S(B1, B2, ..., Bn) are said to be union compatible
(or type compatible)

if they have the same degree n and if dom(Ai) = dom(Bi) for 1 <=i<=n.
This means that the tworelations have the same number of attributes
and each
corresponding pair of attributes has the same domain.
82
(a)T
.

83

(d)STUDENT − INSTRUCTOR

( e)INSTRUCTOR −
STUDENT
84

•Retrieve the Social Security numbers of all employees who either work in department 5
or directly supervise an employee who works in department 5, we can use the UNION
operation as follows

•UNION operation produces the tuples that are in either RESULT1 or RESULT2
or both, while eliminating any duplicates.
85

DEP5_EMPS DEP5_EMPS ← σDno=5(EMPLOYEE)


RESULT1 ← πSsn(DEP5_EMPS)
RESULT2(Ssn) ←

πSuper_ssn(DEP5_EMPS) RESULT ←

RESULT1 ∪ RESULT2
86

•UNION and INTERSECTION are commutative operations

•Both UNION and INTERSECTION can be treated as n-ary operations applicable to


any number of relations because both are also associative operations.

•The MINUS operation is not commutative; that is, in general,

•INTERSECTION can be expressed in terms of union and differenceas


set follows
87
•denoted by ×
•This is also a binary set operation, but the relations on which it is applied do not have
to be union compatible

•Result of R(A1, A2, ..., An) × S(B1, B2, ..., Bm) is a relation Q with degree n + m
attributes Q(A1, A2, ..., An, B1, B2, ..., Bm), in that order.
•The resulting relation Q has one tuple for each combination oftuples—one from R
and one from S.
•Hence, if R has nR tuples (denoted as |R| = nR), and S has nS tuples, then R × S
will have nR * nS tuples.
•Produces new tuples by concatenating all possible combinations of tuples from n
underlying relations
88
89
90

FEMALE_EMPS ← σ Sex=‘F’(EMPLOYEE)
EMPNAMES ← π Fname, Lname,
Ssn
(FEMALE_EMPS)
91
92

ACTUAL_DEPENDENTS ← σSsn=Essn(EMP_DEPENDENTS)

RESULT ← πFname, Lname,


Dependent_name
(ACTUAL_DEPENDENTS)
93

•The CARTESIAN PRODUCT creates tuples with the combined attributes of two relations.
•We can SELECT related tuples only from the two relations by specifying an appropriate
selection condition after the Cartesian product, as we did in the preceding example.
•Because this sequence of CARTESIAN PRODUCT followed by SELECT is quite commonly
used to combine related tuples from two relations, a special operation, called JOIN, was
created to specify this sequence as a single operation
94
•The JOIN operation, denoted by , is used to combine related tuples from two relations into
single “longer” tuples.
•This operation is very important for any relational database with more than a single relation
because it allows us to process relationships among relations.

•Retrieve the name of the manager of each department.


To get the manager’s name, we need to combine each department tuple with the
employee tuple whose Ssn value matches the Mgr_ssn value in the department
tuple.
We do this by using the JOIN operation and then projecting the result over the necessary
attributes, as follows
95

RESULT
Dname Lname Fname
Research Wong Franklin
Administration Wallance Jennifer
Headquaters Borg James
96
•The JOIN operation can be specified as a PRODUCT
CARTESIAN followed by a SELECT operation. operation

•These two operations can be replaced with a single JOIN operation as follows
97

•JOIN operation on two relations R(A1, A2, ..., An) and S(B1, B2, ..., Bm) is

•The result of the JOIN is a relation Q with n + m attributes Q(A1, A2, ..., An, B1, B2,
... , Bm) in that order;
•Q has onetuple for each combination of tuples—one from R andonefrom
S— whenever the combination satisfies thejoin condition
98

•In JOIN, only combinations of tuples satisfying the join condition appear in the
result, whereas in the CARTESIAN PRODUCT all combinations of tuples are
included in the result.
•The join condition is specified on attributes from the two relations R and S and is
evaluated for each combination of tuples.
•Each tuple combination for which the join condition evaluates to TRUE is included in
the resulting relation Q as a single combined tuple.
107 Different Types of SQL
JOINs
•INNER JOIN
Returns records that have matching values in both tables
1. Theta join
2. EQUI join
3. Natural join
• OUTER JOIN
In an outer join, along with tuples that satisfy the matching criteria, we also include
some or all tuples that do not match the criteria.

1. Left Outer JOIN


2. Right Outer Join
3. Full Outer Join
99

< condition > AND < condition > AND… AND < condition
>
where each <condition> is of the form Ai θ Bj,
Ai is an attribute of
R, Bj is an attribute of
S,

Ai and Bj have the same domain, and


θ (theta) is one of the comparison operators {=, <, ≤, >, ≥, ≠}.
•Tuples whose join attributes are NULL or for which the join condition is
FALSE do not appear in the result
• JOIN operation does not necessarily preserve all of the information in the
participating relations, because tuples that do not get combined with matching ones in
100

•denoted by
*,
• NATURAL JOIN requires that the two join attributes (or each pair of join attributes) have
the same name in both relations.
•If this is not the case, a renaming operation is applied first.
101
Project
Pname Pnumber Rocation Dnum Dname Mgr_ssn Mgr_sta1
ProductX 1 Bellaire 5 Research 333445555 1988-05-!
ProductY 2 Sugaland 5 Reseach 333445555 1988-05-!
ProductZ 3 Houston 5 Reseach 333445555 1988-05-!
Computerizati 10 Stafford 4 Administration 987654321 1995-01-1
o n
Reorganization 20 Houston 1 Headquartem 888665555 1981-06-‘
Newbenefits 30 Stafford 4 Administration 987654321 1995-01-1
Dept
Dname Dnumber Mgr_ssn Mgr_start_date Location
Head-quarters 1 888665555 1981-06-19 Houston
Administration 4 987654321 1995-01-01 Stafiord
Research 5 333445555 1988-05-22 Bellaire
Research 5 333445555 1988-05-22 Sugarland
Research 5 333445555 1988-05-22 Houston
102

Combine each PROJECT tuple with the DEPARTMENT tuple that controls the project
First we rename the Dnumber attribute of DEPARTMENT to Dnum
so thatit has the same name as the Dnum attribute in PROJECT andthen we
apply NATURAL JOIN

PROJ_DEPT ← PROJECT * ρ
(Dname, Dnum, Mgr_ssn, Mgr_start_date)(DEPARTMENT)

•The same query can be done in two steps by creating an intermediate table
DEPT
DEPT ← ρ
(Dname, Dnum, Mgr_ssn, Mgr_start_date)(DEPARTMENT)

PROJ_DEPT ← PROJECT DEPT


*
103
PROJ_DEPT ← PROJECT DEPT
*

In the PROJ_DEPT relation, each tuple combines a PROJECT tuple with the
DEPARTMENT tuple for the department that controls the project, but only one join
attribute value is kept.
104

•If the attributes on which the natural join is specified already have the same names in
both relations, renaming is unnecessary
•to apply a natural join on the Dnumber attributes of DEPARTMENT
and DEPT_LOCATIONS

•DEPT_LOCS ← DEPARTMENT DEPT_LOCATIONS


*
105

•Join condition for NATURAL JOIN is constructed by equating each pair of join
attributes that have the same name in the two relations and combining these
conditions with AND.
•There can be a list of join attributes from each relation, and each corresponding pair
must have the same name.

•more general, but nonstandard definition for NATURAL JOIN is

•<list1> specifies a list of i attributes from R, and


•<list2> specifies a list of i attributes from S.
•The lists are used to form equality comparison condition between pairs of corresponding
attributes, and the conditions are then AND ed together.
106
108

► In Inner Join, the matched rows are returned and unmatched rows are not returned.
► But, in outer join, we include those tuples which meet the given condition along with that,
we also add those tuples which do not meet the required condition.

► The result also includes the tuples from the left and right tables which do not satisfy the
conditions.

► Based on the tuples that are added from left, right or both the tables, the outer join is
further divided into three types.

► Note: The operators here define the existence of null value which we will use to fill the
table if the required conditions do not match.
109

► Left Outer Join is a type of join in which all the tuples from left relation are included and
only those tuples from right relation are included which have a common value in the
common attribute on which the join is being performed.

► Notation: R1⟕R2 where R1 and R2 are relations.


110

► We have two tables of Student(S_id,Name,Class,Age,C_type) and


Courses (C_type,C_name).
► Student ⟕ Course
111

► Right Outer Join is a type of join in which all the tuples from right relation are
included and only those tuples from left relation are included which have a
common value in the common attribute on which the right join is being
performed.

► Notation: R1 ⟖ R2 where R1 and R2 are relations.


112

► We have two tables of Student(S_id,Name,Class,Age,C_type) and


Courses(C_type,C_name). Now, we will perform right outer on both the tables
i.e

► Student ⟖ Course
113

► Full Outer Join is a type of join in which all the tuples from the left and right relation which
are having the same value on the common attribute. Also, they will have all the remaining
tuples which are not common on in both the relations.

► Notation: R1 ⟗ R2 where R1 and R2 are relations.


114

► We have two tables of and Courses (C_type,C_name). Now, we


Student(S_id,Name,Class,Age,C_type) will perform full outer join on both the
tables i.e
► Student ⟗ Course
115
BOOKS(DocId, Title, Publisher, Year) borrows(DocId, StId, Date)

STUDENTS(StId, StName, Major, Age) has-written(DocId, AName)

AUTHORS(AName, Address) describes(DocId, Keyword)


Assume the following relations:
1. List the year and title of each book.
2. List all information about students whose major is CS
3. List all students with the books they can borrow
4. List all books published by McGraw-Hill before 1990
5. List the name of those authors who are living in Davis
6. List the name of students who are older than 30 and who are not studying CS
7. Rename AName in the relation AUTHORS to Name.
116
► List the year and title of each book.
π (BOOKS)
Year, Title

► List all information about students whose major is CS


π (σMajor = ’CS’(STUDENTS))
► List all students with the books they can borrow
π (STUDENTS × BOOKS)
► List all books published by McGraw-Hill before 1990
π (σ (BOOKS))
Publisher = ’McGraw-Hill’ 𝖠 Year<1990

► List the name of those authors who are living in Davis


π (σ (AUTHORS))
AName Address like ’%Davis%’

► List the name of students who are older than 30 and who are not studying CS
πStName(σAge>30(STUDENTS)) − πStName(σMajor=’CS’(STUDENTS))
► Rename AName in the relation AUTHORS to Name
ρAName/Name(AUTHORS)
117
► Assume the following relations:
BOOKS(DocId, Title, Publisher, Year)
STUDENTS(StId, StName, Major,
Age) AUTHORS(AName, Address)
borrows(DocId, StId, Date)
has-written(DocId,
AName) describes(DocId,
Keyword)
1. List each book with its keywords.
2. List each student with the books she/he has borrowed.
3. List the title of books written by the author ’Ullman’
4. List the authors of the books the student ’Smith’ has borrowed
5. Which books have both keywords ’database’ and
’programming’?
118

Q: List each book with its keywords.


BOOKS ⋈ describes
Note that books having no keyword will not be there in the result.
Q: List each student with the books she/he has borrowed.
BOOKS ⋈ (borrows ⋈ STUDENTS)
Q: List the title of books written by the author
’Ullman’ πTitle(σAName=’Ullman’(BOOKS ⋈
has-written))
Or
πTitle(BOOKS ⋈ σAName=’Ullman’(has-written))
Q: List the authors of the books the student ’Smith’ has borrowed
πAName(σStName=’Smith’(has-written ⋈ (borrows ⋈ STUDENTS))
119

Q: Which books have both keywords ’database’ and


’programming’?
BOOKS ⋈ (πDocId(σKeyword=’database’(describes)) ∩
πDocId(σKeyword=’programming’(describes)))
120

► Assume the following relations:

SALESPERSON(Ssn, Name, StartYear, DeptNo)

TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate,

TripId) EXPENSE(TripId, AccountNo, Amount)

► Write relation algebra expression to get the details of salespersons who have
travelled between Mumbai and Delhi and the travel expense is greater that Rs.
50000.

► πSsn,Name,StartYear,DeptNo(σ(FromCity=‘Mumbai’ and ToCity=‘Delhi’) or


(FromCity=‘Delhi’ and ToCity=‘Mumbai’) and Amount>5000(SALESPERSON ⋈ (TRIP ⋈
EXPENSE))))
121

► Assume the following relations:

SALESPERSON(Ssn, Name, StartYear, DeptNo)


TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate,

TripId) EXPENSE(TripId, AccountNo, Amount)

Specify the subsequent queries in relational algebra:

1. Give the details (all attributes of TRIP) for trips which exceeded $2000 in expenses.

2. Print the SSN of salesman who took trips to ‘Honolulu'

3. Print the trip expenses incurred through the salesman with SSN= ‘234-56-7890'.
122 Assume
► the following relations:
SALESPERSON(Ssn, Name, StartYear, DeptNo)
TRIP(Ssn, FromCity, ToCity, DepartureDate, ReturnDate,
TripId) EXPENSE(TripId, AccountNo, Amount)

Specify the subsequent queries in relational algebra:

1. Give the details (all attributes of TRIP) for trips which exceeded $2000 in expenses.

A: πSsn, FromCity, ToCity, DepartureDate, ReturnDate, TripId (σAmount>2000(TRIP ⋈


EXPENSE))
2. Print the SSN of salesman who took trips to

‘Honolulu‘ A: π Ssn(σToCity=‘Honolulu‘ (TRIP))

3. Print the trip expenses incurred through the salesman with SSN= ‘234-56-7890'.

A: πAmount(σSsn=‘234-56-7890'(TRIP ⋈ EXPENSE))
123

1. Retrieve the name and address of all employees who work for the ‘Research’
department.

2. For every project located in ‘Stafford’, list the project number, the controlling
department number, and the department manager’s last name, address, and birth
date.
124

3. Make a list of 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.
Introduction to Structured Query Language (SQL)
Data Definition Language (DDL)
Table definitions and operations –
CREATE, DROP, ALTER, INSERT, DELETE,
UPDATE.

125
126
► Structured Query Language(SQL) was developed at IBM by Donald D. Chamberlin and

Raymond F. Boyce in the early 1970s.

► This was initially called SEQUEL(Structured English QUEry Language).


► The main objective of SQL is to update, store, manipulate and retrieve data stored in a

relational database.

Donald D. Chamberlin Raymond F. Boyce


127

► The SQL data-definition language (DDL) allows the specification of information about
relations, including:

► The schema for each relation.

► The domain of values associated with each attribute.

► Integrity constraints
128

► char(n). Fixed length character string, with user-specified length n.


► varchar(n). Variable length character strings, with user-specified maximum length
n.
129

► char(n). Fixed length character string, with user-specified length n.

► varchar(n). Variable length character strings, with user-specified maximum length n.

► int. Integer (a finite subset of the integers that is machine-dependent).

► smallint. Small integer (a machine-dependent subset of the integer domain type).


► numeric(p,d). Fixed point number, with user-specified precision of p digits, with d
digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be stores exactly,
but not 444.5 or 0.32)

► real, double precision. Floating point and double-precision floating point numbers,
with machine-dependent precision.

► float(n). Floating point number, with user-specified precision of at least n digits.


130
131
► DDL or Data Definition Language actually consists of the SQL commands that can be used
to define the database schema.

► It simply deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database.

► Examples of DDL commands:


► CREATE – is used to create the database or its objects (like table,
index, function, views, store procedure and triggers).
► DROP – is used to delete objects from the database.
► ALTER-is used to alter the structure of the database.
► TRUNCATE–is used to remove all records from a table, including all spaces allocated
for the records are removed.
► RENAME –is used to rename an object existing in the database.
132

► There are two CREATE statements available in


SQL:

► CREATE DATABASE

► CREATE TABLE
133

► A Database is defined as a structured set of data. So, in SQL the very first step to store the
data in a well structured manner is to create a database.

► The CREATE DATABASE statement is used to create a new database in SQL.

► Syntax:

CREATE DATABASE database_name;

► database_name: name of the database.

► Example

► CREATE DATABASE university;


134
► An SQL relation is defined using the create table
command:
create table R (A1 D1, A2 D2, ..., An
Dn, (integrity-constraint1),
...,
(integrity-constraintk))
► R is the name of the relation

► each Ai is an attribute name in the schema of relation R

► Di is the data type of values in the domain of attribute


Ai
► Example:
ID char(5),
create table instructor (
name varchar(20),
dept_name varchar(20),
salary numeric(8,2));
135

► Types of Integrity Constraints in


DBMS

► Entity Integrity Constraints

► Referential Integrity Constraints

► Domain Constraints
136

► primary key (A1, ..., An )

► The attributes required to be non null and unique

► foreign key (Am, ..., An ) references s


► The values of the attributes (A , ..., A ) for any tuple in the relation must correspond to
m n

values of the primary key attributes of some tuple in relation s.

► not null

► Specifies that the null value is not allowed for that attribute
137
138
► create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references department);
► create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);
create table takes
139
ID varchar(5),
(
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year)
, foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references
section);
► course_id
create table coursevarchar(8),
(
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references
140
► DROP is used to delete a whole database or just a table.
► The DROP statement destroys the objects like an existing database, table, index,
or view.

► A DROP statement in SQL removes a component from a relational


database management system (RDBMS).

► Syntax : DROP object object_name;

► Examples: DROP TABLE table_name;

► table_name: Name of the table to be deleted.

► DROP DATABASE database_name;

► database_name: Name of the database to be deleted.


141
► TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark
the
extents of a table for deallocation (empty for reuse).

► The result of this operation quickly removes all data from a table

► Syntax:

► TRUNCATE TABLE table_name;

► table_name: Name of the table to be truncated.

► Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
► Truncate preserves the structure of the table for future use, unlike drop table where the table
is deleted with its full structure.

► Table or Database deletion using DROP statement cannot be rolled back, so it must be
142

TRUNCATE user
143
► ALTER TABLE is used to add, delete/drop or modify columns in the existing table.

► It is also used to add and drop various constraints on the existing table.

► ALTER TABLE – ADD

► ADD is used to add columns into the existing table.


► Sometimes we may require to add additional information, in that case we do not
require to create the whole database again, ADD comes to our rescue.

► Syntax

ALTER TABLE table_name

ADD (Columnname_1datatype,

Columnname_2 datatype Columnname_n datatype);


144

ROLL_NO NAME

1 Ram

2 Abhi To ADD 2 columns AGE and COURSE to table


3 Rahul
Student.
4 Tanu

ALTER TABLE Student ADD (AGE number(3),COURSE


varchar(40));
ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu
145

► ALTER TABLE – DROP

► DROP COLUMN is used to drop column in a table. Deleting the unwanted


columns from the table.
► Syntax:
ALTER TABLE table_name

DROP COLUMN column_name;


146

ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu

► ALTER TABLE Student DROP COLUMN


COURSE; ROLL_NO NAME AGE

1 Ram

2 Abhi

3 Rahul

4 Tanu
147

► ALTER TABLE-MODIFY
► It is used to modify the existing columns in a table. Multiple columns can also be

modified at once.

► Syntax may vary slightly in different databases.


► Syntax(Oracle,MySQL,MariaDB):

ALTER TABLE table_name

MODIFY column_name column_type;


► Syntax(SQL Server):

ALTER TABLE

table_name
148 ✔ The SQL ALTER TABLE command is used to add, delete or modify columns in anexisting table.

✔ You would also use ALTER TABLE command to add and drop various constraints on an existing table.
✔ The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:

ALTER TABLE table_name ADD column_name datatype;

Eg: ALTER TABLE CUSTOMERS ADD CITY CHAR(20);


The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as

follows: ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as follows:

ALTER TABLE table_name MODIFY COLUMN column_name datatype;


The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as

follows: ALTER TABLE table_name MODIFY column_name datatype NOT NULL;


149

The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as
follows:

ALTER TABLE TableName ADD PRIMARY KEY (ColumnName); OR


ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID);
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as

follows:

ALTER TABLE table_name DROP CONSTRAINT Primary Key; OR

ALTER TABLE Persons DROP CONSTRAINT PK_Person;


150

► Sometimes we may want to rename our table to give it a more relevant


name.

► For this purpose we can use ALTER TABLE to rename the name of table.

► Syntax may vary in different databases.

► Syntax(Oracle,MySQL,MariaDB):

► ALTER TABLE table_name

► RENAME TO new_table_name;

► Columns can be also be given new name with the use of ALTER TABLE.

► Syntax(MySQL, Oracle):
151

► DML stands for Data Manipulation Language.

► It is a language used for selecting, inserting, deleting and updating data in a database.

► It is used to retrieve and manipulate data in a relational database.


► There are three basic constructs which allow database program and user to enter data
and information are:

► INSERT

► UPDATE

► DELETE
152
2. Data Manipulation Language (DML)
It provides a set of operations to support the basic data manipulation
operations on the data held in the database.
It is used to query, update or retrieve data stored in a
database.

Some of the tasks that come under DML are


SELECT : Used to query and display data from a
database. INSERT : Adds new rows to a table.
UPDATE : Changes an existing value in a column or group of columns in a
table. DELETE : Removes a specified row or set of rows from a table.
153
► The INSERT INTO statement is used to insert new records in a
table.
► It is possible to write the INSERT INTO statement in two
ways:

► Specify both the column names and the values to be inserted:

► Syntax :
► INSERT INTO table_name (column1, column2, column3, ...) VALUES

(value1, value2, value3, ...);

► If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query.

► Make sure that the order of the values is in the same order as the columns in the
table.
154

CustomerID CustomerName ContactName Address City PostalCode Country


White Clover 305 - 14th Ave. S. Suite
89 Karl Jablonski Seattle 98128 USA
Markets 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

► INSERT INTO Customers (CustomerID, CustomerName, ContactName, Address,


City, PostalCode, Country) VALUES (92,'Cardinal', 'Tom B. Erichsen', 'Skagen 21',
'Stavanger', '4006', 'Norway');

CustomerID CustomerName ContactName Address City PostalCode Country


White Clover 305 - 14th Ave. S. Suite
89 Karl Jablonski Seattle 98128 USA
Markets 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway
155
► Insert Data Only in Specified Columns
► It is also possible to only insert data in specific columns.

► Syntax

► INSERT INTO Customers (CustomerID ,CustomerName, City,


Country) VALUES (92, 'Cardinal', 'Stavanger', 'Norway');
► The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country


White Clover 305 - 14th Ave. S. Suite
89 Karl Jablonski Seattle 98128 USA
Markets 3B
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal null null Stavanger null Norway
156

► To insert multiple rows in a table using Single SQL Statement


INSERT INTO
table_name(Column1,Column2,Column3,.......) VALUES
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
............................. ;
► Example
INSERT INTO STUDENT(ID,
NAME,AGE,GRADE,CITY) VALUES(1,"AMIT
KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI"),
157
► The UPDATE statement in SQL is used to update the data of an existing table

in database.

► We can update single columns as well as multiple columns using UPDATE


statement as per our requirement.

► Syntax

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;
► Note: The WHERE clause specifies which record(s) that should be updated. If you omit
the WHERE clause, all records in the table will be updated!
158

CustomerID CustomerName ContactName Address City PostalCode Country


Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City=
'Frankfurt' WHERE CustomerID = 1;
159

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City=
'Frankfurt' WHERE CustomerID = 1;

CustomerID CustomerName ContactName Address City PostalCode Country


Alfreds
1 Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
160

► UPDATE Multiple Records


►It is the WHERE clause that determines how many records will be updated.

UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Juan México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
161

► If you omit the WHERE clause, ALL records will be


updated!

UPDATE Customers
SET ContactName='Juan';
CustomerID CustomerName ContactName Address City PostalCode Country
Alfreds
1 Juan Obere Str. 57 Frankfurt 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Juan México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Juan Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
Berglunds
5 Juan Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp
162

► The DELETE Statement in SQL is used to delete existing records from a table.
► We can delete a single record or multiple records depending on the condition
we specify in the WHERE clause.

► Syntax

►DELETE FROM table_name WHERE condition;


► The WHERE clause specifies which record(s) should be deleted. If you omit
the WHERE clause, all records in the table will be deleted!
163

CustomerID CustomerName ContactName Address City PostalCode Country


Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

► DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';


CustomerID CustomerName ContactName Address City PostalCode Country
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno
3 Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
164

► Delete All Records


► It is possible to delete all rows in a table without deleting the table. This means that
the table structure, attributes, and indexes will be intact:

► Syntax

► DELETE FROM table_name;

► Example

► DELETE FROM customers;


165

✔ SQL SELECT statement is used to fetch the data from a database table which returns data in
the form of result table. These result tables are called result-sets.

✔ Syntax:
✔ The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;
✔ Here, column1, column2...are the fields of a table whose values you want to fetch.
✔ If you want to fetch all the fields available in the field, then you can use the following syntax:

SELECT * FROM table_name;


166

The SQL LIKE clause is used to compare a value to similar values


using wildcard operators. There are two wildcards used in conjunction with the LIKE
operator.

• The percent sign (%)

• The underscore (_)


The percent sign represents zero, one or multiple characters. The underscore represents
a single number or character. These symbols can be used in combinations.

Syntax

The basic syntax of % and _ is as follows −


167

To start with a letter A


SELECT FROM table_name WHERE column LIKE

‘A%’ Contain a Substring XXX

SELECT FROM table_name WHERE column LIKE

'%XXX%’ Should Begin with XX

SELECT FROM table_name WHERE column LIKE 'XX_’

Should end with XXXX Substring may be preceded by single letter

SELECT FROM table_name WHERE column LIKE '_XXXX’


Contain a Substring XXXX - Substring may be preceded and succeeded by single

letter. SELECT FROM table_name WHERE column LIKE '_XXXX_'


168

Category
SELECT DISTINCT category
Gadgets
FROM Product
Photography

Household

Compare to:
Category
SELECT Gadgets

category FROM Gadgets

Photography
Product
Household
169

SELECT pname, price, manufacturer


FROM Product
WHERE category=‘Gadgets ’ AND price >
10 price
ORDER BY

Ordering is ascending, unless specified the DESC keyword.


PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

You might also like