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

Chapter-3

Chapter 03 provides an introduction to SQL, detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and integrity constraints. It covers basic SQL operations including querying, modifying data, and handling null values, as well as aggregate functions and nested subqueries. The chapter emphasizes the structure of SQL queries, set operations, and the importance of proper syntax and commands for effective database management.

Uploaded by

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

Chapter-3

Chapter 03 provides an introduction to SQL, detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and integrity constraints. It covers basic SQL operations including querying, modifying data, and handling null values, as well as aggregate functions and nested subqueries. The chapter emphasizes the structure of SQL queries, set operations, and the importance of proper syntax and commands for effective database management.

Uploaded by

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

Chapter 03

Introduction to SQL
3.1

OVERVIEW OF THE SQL QUERY


LANGUAGE
The SQL language has several parts:
1. Data-definition language (DDL).
– The SQL DDL provides commands for:
• Defining relation schemas.
• Deleting relations.
• Modifying relation schemas.

2. Data-manipulation language (DML).


– The SQL DML provides the ability to:
• Query information from the database.
• Insert tuples into database.
• Delete tuples from database.
• Modify tuples in the database
The SQL language has several parts:
3. Integrity.
– The SQL DDL includes commands for specifying
integrity constraints that the data stored in the
database must satisfy.
• Updates that violate integrity constraints are disallowed.

4. View definition.
– The SQL DDL includes commands for defining views.

5. Transaction control.
– SQL includes commands for specifying the
beginning and ending of transactions.
The SQL language has several parts:

6. Embedded SQL and dynamic SQL.


– Embedded and dynamic SQL define how SQL
statements can be embedded within general-
purpose programming languages, such as C,
C++, and Java.

7. Authorization.
– The SQL DDL includes commands for specifying
access rights to relations and views.
3.2

SQL DATA DEFINITION


SQL Data Definition
• The SQL DDL allows specification of not only a
set of relations, but also information about
each relation, including:
– The schema for each relation.
– The types of values associated with each attribute.
– The integrity constraints.
– The set of indices to be maintained for each
relation.
– The security and authorization information for each
relation.
– The physical storage structure of each relation on
disk.
Basic Types
1. char(n):
– A fixed-length character string with user-specified length n.
– The full form, character, can be used instead.

2. varchar(n):
– A variable-length character string with user-specified
maximum length n.
– The full form, character varying, is equivalent.

3. int:
– An integer (a finite subset of the integers that is machine
dependent).
– The full form, integer, is equivalent.

4. smallint:
– A small integer (a machine-dependent subset of the integer
type).
Basic Types
5. numeric(p, d):
– A fixed-point number with user-specified precision.
– The number consists of p digits (plus a sign), and d of
the p digits are to the right of the decimal point.
• Thus, numeric(3,1) allows 44.5 to be stored exactly, but neither
444.5 or 0.32 can be stored exactly in a field of this type.

6. real, double precision:


– Floating-point and double-precision floating-point
numbers with machine-dependent precision.

7. float(n):
– A floating-point number, with precision of at least n
digits.
Basic Schema Definition
Basic Schema Definition
Basic Schema Definition
drop table
• To remove a relation from an SQL database,
we use the drop table command.

• The drop table command deletes all


information about the dropped relation
from the database.
alter table
• We use the alter table command to add
attributes to an existing relation.
– All tuples in the relation are assigned null as the
value for the new attribute.
– The form of the alter table command is

• We can drop attributes from a relation by


the command:
3.3

BASIC STRUCTURE OF SQL QUERIES


Basic Structure of SQL Queries
• The basic structure of an SQL query consists
of three clauses:
– select
– from
– where.

• The query takes as its input the relations listed in the


from clause, operates on them as specified in the
where and select clauses, and then produces a
relation as the result.
Queries on a Single Relation
• Example:
– Find the names of all
instructors.

– Select name from


instructor;
Queries on a Single Relation
• Example:
– Find the names of all departments.

– Select distinct dept_name from instructor;


Queries on a Single Relation
• Example:
Queries on a Single Relation
• Example:
Queries on Multiple Relations
The Natural Join
The Natural Join
Chapter 03

Introduction to SQL
3.4

ADDITIONAL BASIC OPERATIONS


The Rename Operation
Example
• Find the names of all instructors whose
salary is greater than at least one instructor
in the Biology department.
String Operations
• Equality:
– ‘comp. sci.’ = ‘Comp. Sci.’

• Concatenating:
– Fname || lname
• Select fname || lname as Name from
emp;
String Operations
• Converting strings:
– Upper(s)
– Lower(s)
• Select ID from emp where
upper(name)=“ALI”;

• Removing spaces at the end of the string:


– Trim(s)
String Operations
• Pattern matching:
– Pattern matching can be performed on strings,
using the operator like.

– We describe patterns by using two special


characters:
• % : The % character matches any substring.
• _ : The underscore character matches any character.

See next slide “Examples”


String Operations [Con.]
• Pattern matching examples:
– ’Intro%’
• matches any string beginning with “Intro”.

– ’%Comp%’
• matches any string containing “Comp” as a substring

– ’_ _ _ ’
• matches any string of exactly three characters.

– ’_ _ _%’
• matches any string of at least three characters.
String Operations [Con.]
• Find the names of all departments whose
building name includes the substring
‘Watson’.
Escape Character \
• like ’ab\%cd%’:
– Matches all strings beginning with “ab%cd”.

• like ’ab\\cd%’:
– Matches all strings beginning with “ab\cd”.
Attribute Specification in Select
Clause
Ordering the Display of Tuples
Where Clause Predicates
• Find the names of instructors with salary
amounts between $90,000 and $100,000
Where Clause Predicates
• Find the instructor names and the courses
they taught for all instructors in the Biology
department who have taught some course.
Chapter 03

Introduction to SQL
3.5

SET OPERATIONS
Set Operations
• The SQL operations union, intersect, and
except operate on relations and correspond
to the mathematical set-theory operations
∪, ∩, and −.
Set Operations
• The set of all courses taught in the Fall 2009
semester:

• The set of all courses taught in the Spring


2010 semester:
The Union Operation
• To find the set of all courses taught either in
Fall 2009 or in Spring 2010, or both, we
write:
The Union Operation
• To find the set of all courses taught either in
Fall 2009 or in Spring 2010, or both, we
write:
The Intersect Operation
• To find the set of all courses taught in the
Fall 2009 as well as in Spring 2010 we
write:
The Intersect Operation
• To find the set of all courses taught in the
Fall 2009 as well as in Spring 2010 we
write:
The Except Operation
• To find all courses taught in the Fall 2009
semester but not in the Spring 2010
semester, we write:
The Except Operation
• To find all courses taught in the Fall 2009
semester but not in the Spring 2010
semester, we write:
3.6

NULL VALUES
Null
• Null values present special problems in
relational operations:
– Arithmetic operations.
– Comparison operations.
– Set operations.
Arithmetic Expression Involving Null
• The result of an arithmetic expression
(involving, for example +, −, ∗, or /) is null if
any of the input values is null.

• For example, if a query has an expression


r.A+5, and r.A is null for a particular tuple
then the expression result must also be null
for that tuple.
Comparisons Involving Nulls
• Comparisons involving nulls are more of a
problem.

– For example, consider the comparison “1 < null”.


• It would be wrong to say this is true since we do not
know what the null value represents.
• It would be wrong to claim this expression is false
although.

• SQL therefore treats as unknown the result


of any comparison involving a null value
Boolean Operations Involving Null
X Y X and Y X or Y Not X
true unknown unknown true false
false unknown false unknown true
unknown unknown unknown unknown unknown

• You can verify that if r.A is null:


– Then “1 < r.A” as well as “not (1 < r.A)” evaluate to
unknown.

• If the where clause predicate evaluates to either


false or unknown for a tuple, that tuple is not added
to the result.
Null in a Predicate
• Find all instructors who appear in the
instructor relation with null values of their
salary (unknown salary).
Null in a Predicate
• Find all instructors who appear in the
instructor relation with known salary.
Records with Nulls
• The tuple (‘Ahmad’, NULL) is identical to the
tuple (‘Ahmad’, NULL)

• The above approach of treating tuples as


identical if they have the same values for all
attributes, even if some of the values are
null, is also used for the set operations
union, intersection and except.
Chapter 03

Introduction to SQL
3.7

AGGREGATE FUNCTIONS
Aggregate Functions
• Aggregate functions are functions that take
a collection (a set or multiset) of values as
input and return a single value.

• SQL offers five built-in aggregate functions:


– Average: avg
– Minimum: min
– Maximum: max
– Total: sum
– Count: count
Basic Aggregation
• Find the average salary of instructors in the
Computer Science department.
Basic Aggregation
• Find the total number of instructors who
teach at least one course in the Spring 2010
semester.
Aggregation with Grouping
• Find the average salary in each department.
Aggregation with Grouping
• Find the number of instructors in each department
who teach at least one course in the Spring 2010
semester.

• When an SQL query uses grouping, it is important to


ensure that the only attributes that appear in the
select statement without being aggregated are those
that are present in the group by clause.
The Having Clause
• Find the departments where the average
salary of the instructors is more than
$42,000.
The Having Clause
• For each course section offered in 2009, find
the average total credits of all students
enrolled in the section, if the section had at
least 2 students.

4
Chapter 03

Introduction to SQL
3.8

NESTED SUBQUERIES
Set Membership
• The in connective tests for set membership.
– Where the set is a collection of values produced by a select clause.
• The not in connective tests for the absence of set membership.

Example : Find all the courses taught in the both the Fall 2009 and
Spring 2010 semesters.
Set Membership
• Example, to find all the courses taught in the
Fall 2009 semester but not in the Spring
2010 semester, we can write:
Set Membership
• Selects the names of instructors whose
names are neither “Mozart” nor “Einstein”

• Find the total number of (distinct) students


who have taken course sections taught by
the instructor with ID 110011
Set Comparison
• Find the names of all instructors whose
salary is greater than at least one instructor
in the Biology department.
Set Comparison
• Find the names of all instructors that have a
salary value greater than of each instructor
in the Biology department.
Set Comparison
• Find the departments that have the highest
average salary.
Test for Empty Relations
• The exists construct returns the value true if
the argument subquery is nonempty.

• Find all courses taught in both the Fall 2009


semester and in the Spring 2010 semester.
Test for Empty Relations
• Find all students who have taken all courses
offered in the Biology department.
Test for the Absence of Duplicate
Tuples
• The unique construct returns the value true
if the argument subquery contains no
duplicate tuples.

• Find all courses that were offered at most


once in 2009.
Test for the Absence of Duplicate
Tuples
• Find all courses that were offered at least
twice in 2009.
Subqueries in the From Clause
Subqueries in the From Clause
• Find the maximum across all departments
of the total salary at each department.
The with Clause
• The with clause provides away of defining a
temporary relation whose definition is
available only to the query in which the with
clause occurs.

• Finds the departments with the maximum


budget
Scalar Subqueries
• scalar subqueries is a subquery that
returns only one tuple containing a single
attribute.
Chapter 03

Introduction to SQL

82
3.9

MODIFICATION OF THE DATABASE

83
Deletion

84
Deletion

85
Insertion

86
Updates

87
Updates
• Suppose that all instructors with salary over
$100,000 receive a 3 percent raise, whereas
all others receive a 5 percent raise.
Note that the order of the two
update statements is important. If
we changed the order of the two
statements, an instructor with a
salary just under $100,000 would
receive an over 8 percent raise.

88
Updates
• Suppose that all instructors with salary over
$100,000 receive a 3 percent raise, whereas
all others receive a 5 percent raise.

89

You might also like