Mdb Unit 123-09-22 Updated Ppt 1
Mdb Unit 123-09-22 Updated Ppt 1
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
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
8
DATABASE
MANAGEMENT
SYSTEM
DATABASE MANAGEMENT SYSTEM
10
CHARACTERISTICS OF DBMS
1. Banking Management
2. Business Organization
3. Manufacturing
4. Education
5. Medical Field
6. Railways
DBMS ALLOWS USERS THE FOLLOWING TASKS:
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.
• 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
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
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
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
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
• varying length
• 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
interval
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
PRIMARY KEY
MYSQL:
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.
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
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:
• Example:
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.
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.
1. schema
2. tables
3. domains
4. constraints.
– 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
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
– CASCADE option , when dropping a table , will remove table and all its
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
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement:
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:
Example
DROP CONSTRAINT
ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint;
using MySQL
ALTER TABLE table_name DROP INDEX MyUniqueConstraint;
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>
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'.
FROM 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'
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
• The join condition MGRSSN=SSN relates the department to the employee who manages that
department.
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
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
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 *
Q10A : SELECT *
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
Query 11 : Retrieve the salary of every employee (Q11) and all distinct salary values (Q11A)
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
Syntax
SELECT column_name FROM table1
INTERSECT
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
SELECT Name
FROM Students
EXCEPT Output:
SELECT NAME 1. Rohan
FROM TA;
2. Mansi
3. Megha
4.5 BASIC QUERIES IN SQL
UNION
14
0
4.5 BASIC QUERIES IN SQL
MultiSet Operations
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
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
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
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
14
7
4.5 BASIC QUERIES IN SQL
MultiSet Operations
Result
SELECT * FROM SummerFruits
INTERSECT
SELECT * FROM Fruits;
Result
Examples
• The LIKE comparison operator can be used for string pattern matching.
_
2. the underscore ( ) replaces a single character.
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
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.
Q3. Select all students with a studentname that have “li” in any positio
Q4. Select all students with a studentname that have “o” in the second position:
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”
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
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.
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
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
2. Unavailable values :
16
8
4.6 MORE COMPLEX SQL QUERIES
Comparisons Involving NULL and Three-Valued Logic
16
9
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
17
1
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
17
2
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
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,
17
5
4.6 MORE COMPLEX SQL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
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
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.
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.
18
2
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
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
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
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
19
4
4.6 MORE COMPLEX SQL QUERIES
Nested Queries and Set Comparisons
1. Example :
(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.)
WHERE PNUMBER IN
OR
•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.
•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
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
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.
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
20
7
The EXISTS and UNIQUE Functions in SQL
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
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”.
21
6
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
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”.
21
9
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
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”.
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
22
4
4.6 MORE COMPLEX SQL QUERIES
The EXISTS and UNIQUE Functions in SQL
EXCEPT
(SELECT PNO FROM WORKS_ON WHERE
22
SSN=ESSN) ); 5
4.6 MORE COMPLEX SQL QUERIES
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.
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.
23
4
4.7 AGGREGATE FUNCTIONS IN SQL
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
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:
10
23
7
4.7 AGGREGATE FUNCTIONS IN SQL
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
7
23
8
4.7 AGGREGATE FUNCTIONS IN SQL
SELECT COUNT(DISTINCT
COMPANY)
FROM PRODUCT_MAST;
Output:
3
23
9
4.7 AGGREGATE FUNCTIONS IN SQL
2. SUM Function
2. SUM Function
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670 24
3
4.7 AGGREGATE FUNCTIONS IN SQL
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output: 24
320 4
4.7 AGGREGATE FUNCTIONS IN SQL
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
Output:
Com1 335 24
Com3 170 6
4.7 AGGREGATE FUNCTIONS IN SQL
3. AVG function
3. AVG function
Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
24
8
4.7 AGGREGATE FUNCTIONS IN SQL
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
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
Output:
30
25
0
4.7 AGGREGATE FUNCTIONS IN SQL
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;
• 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:
• 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
QUERY 25 : For each project, retrieve the project number, the project
QUERY 26 : For each project on which more than two employees work,
retrieve the project number, the project name, and the number of
26
0
4.8 GROUPING: THE GROUP BY AND HAVING CLAUSES
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 (*)
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
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:
26
7
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
TOTAL_SAL)
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 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
FROM DEPARTMENT
WHERE DNAME='Research');
27
U4D: DELETE FROM EMPLOYEE; (becomes empty table) 1
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
27
3
4.9 INSERT, DELETE, AND UPDATE STATEMENTS IN SQL
The UPDATE Command