rdbms(eltp)

125
Introduction to DBMS As information systems specialist You must Analyze database requirements Design and implement databases

Upload: sbukka

Post on 11-Apr-2015

1.547 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Rdbms(Eltp)

Introduction to DBMS

As information systems specialist

You mustAnalyze database requirementsDesign and implement databases

Page 2: Rdbms(Eltp)

CONCEPTS

Data refers to known facts

Database is an organized collection of logically related data.

Organized means data are structured so that they can be easily stored, manipulated, and retrieved by users

Related means that the data describes a domain of interest to users

Page 3: Rdbms(Eltp)

INFORMATION

Information is data that has been presented in such a way that that it can increase the knowledge of the person

who uses it.

Page 4: Rdbms(Eltp)

METADATA

Data that describe the properties of data

Metadata are removed from data

Metadata does not include data

Data without clear meaning can be confusing and misinterpreted

Page 5: Rdbms(Eltp)

METADATA EXAMPLE

Data Item Value Name Type Length Min Max Description

Course Alphanumeric 30 Course name

Section Integer 1 1 9 Section number

:

:

:

Score Decimal 3 0.0 4.0

Page 6: Rdbms(Eltp)

TRADITIONAL FILE PROCESSINGOrders Department

Prog BProg A Prog C

Order Filling

CustomerMaster

InventoryMaster

Back OrderMaster

Page 7: Rdbms(Eltp)

Accounting Department

Prog A Prog B

Invoicing System

Inventory Pricing CustomerMaster

Page 8: Rdbms(Eltp)

DISADVANTAGES OF FILE PROCESSING SYSTEMS

Program-data dependence Duplication of data Limited data sharing Lengthy development times Excessive program maintenance

Page 9: Rdbms(Eltp)

Many of these can be limitations of databases when

Many separately managed databases No control on metadata Uncontrolled data duplication

Page 10: Rdbms(Eltp)

THE DATABASE APPROACH

The database model emphasizes integration and sharing of data throughout organization.

Requires shift in thought process. Management should learn that information

is a competitive weapon

Page 11: Rdbms(Eltp)

COSTS AND RISKS OF DATABASE APPROACH

New specialized personnel Installation and management cost and

complexity Conversion costs Explicit backup and recovery Organizational conflict

Page 12: Rdbms(Eltp)

COMPONENTS OF DATABASE ENVIRONMENT

CASE Tools to design databases and application programs

Repository – storehouse for all data definitions, relationships

DBMS Commercial software used to define, create, maintain, and provide controlled access to database

Database Organized collection of logically related data designed to meet information needs of organization

Page 13: Rdbms(Eltp)

Components of the Database Environment

Application programs – Create and maintain database and provide information to users.

User interface – facilities by which users interact.

Page 14: Rdbms(Eltp)

COMPONENTS OF DATABASE ENVIRONMENT

Data administrators – Overall in-charge of data. Improve productivity of database planning and design.

Systems developers – design and develop new applications.

End users – persons in organization who add, delete, and modify data. Request for information from it.

Page 15: Rdbms(Eltp)

THE RELATIONAL DATA MODEL

Introduced in 1970 by E F Codd

Represents data in the form of tables

Easily understood

Comprises of Relational Data structure, Data manipulation, and Data integrity components

Page 16: Rdbms(Eltp)

Relation is a named, two-dimensional table of data.

Consists of a set of named columns and arbitrary number of unnamed rows.

EMPLOYEE

101 Dev Marketing 48000

102 Ram Finance 52000

Emp_ID Name Dept_Name Salary

EMPLOYEE(Emp_ID,Name,Dept_Name,Salary)

Page 17: Rdbms(Eltp)

RELATIONAL KEYS

Need to store and retrieve a row from relation Every relation must have a Primary key. Primary key is a value or a combination of values

that uniquely identifies each row in a relation. Primary key is underlinedEMPLOYEE(Emp_ID,Name,Dept_Name, Salary)

A Composite key is a primary key that consists of more than one value

Page 18: Rdbms(Eltp)

PROPERTIES OF RELATIONS

Each relation has a unique name An entry at the intersection of row and

column is single valued Each row is unique Each column in a table has a unique name The sequence of columns is insignificant The sequence of rows is insignificant

Page 19: Rdbms(Eltp)

INTEGRITY CONSTRAINTS

Relational model includes several types of constraints to facilitate maintaining the accuracy and integrity of data.

1. Domain Constraints

2. Entity Integrity

3. Referential Integrity

4. Operational Constraints

Page 20: Rdbms(Eltp)

DOMAIN CONSTRAINTS

All values that appear in a column must be taken from the same domain.

Domain definition consists of domain name, meaning, data type, size and allowable values or allowable ranges (if applicable)

Page 21: Rdbms(Eltp)

INTEGRITY CONSTRAINTS

•Ensures that every relation has a primary key.

•All data values in that primary key are valid.

•Every primary key is non-null.

Page 22: Rdbms(Eltp)

FOREIGN KEY

•Foreign key is value in a relation in a database that serves as the primary key of another relation in the same database.

•Associations between tables defined through Foreign key.

•Maintains consistency among the rows in two relations.

Page 23: Rdbms(Eltp)

REFERENTIAL INTEGRITY

If there is a foreign key in one relation either each foreign key must match with a primary key value in another table or it must be null.

Page 24: Rdbms(Eltp)

Example

Customer_ID Customer_AddressCustomer_Name

Order_ID Order_Date Customer_ID

Order_ID Product_ID Quantity

Product_ID Product_Name Unit_Price

Customer

Order

Pending_Order

Product

Page 25: Rdbms(Eltp)

OPERATIONAL CONSTRAINTS

Business rules

Ex: An student can be allowed to take exam only if he has 75% attendance.

Page 26: Rdbms(Eltp)

ENTITY-RELATIONSHIP MODEL

An Entity is a person, place, object, event, or concept about which

organization wishes to maintain data.

Example

Person: EMPLOYEE,STUDENT

Place:CITY,STATE

Object:MACHINE,AUTOMOBILE

Event: SALE,REGISTRATION

Concept:ACCOUNT,COURSE

Page 27: Rdbms(Eltp)

ENTITY-RELATIONSHIP MODEL

•The E-R model is a detailed, logical representation of the data for a business area.

•It is expressed in terms of entities in the business, the relationships, and the properties of the entities and relationships.

•Uses E-R Diagram

Page 28: Rdbms(Eltp)

E-R MODEL SYMBOLS

Strong Entity

Exists independently of other types. STUDENT, EMPLOYEE

Weak Entity

An entity type whose existence depends on other entity type. DEPENDENT

Page 29: Rdbms(Eltp)

E-R MODEL SYMBOLS

Relation ship

•Relation ships are glue that holds togetherthe various components of E-R model.•An association among the instances of one or more entity types.

Page 30: Rdbms(Eltp)

E-R MODEL SYMBOLS

Entity Type Versus Entity Instances

Entity type: EMPLOYEE

EMPLOYEE NUMBER NUMBER(4)

EMPLOYEE NAME ALPHABETS(30)

DATE HIRED DATE

Entity Instances (Two Instances of EMPLOYEE)

1343 5879

Gregory Peck Albert Einstein

08-08-88 09-09-99

Page 31: Rdbms(Eltp)

An entity that associates the instances of one or moreentity types and contains values that are peculiar to relationship between those entities.

E-R MODEL SYMBOLS

Associative Entity

Page 32: Rdbms(Eltp)

E-R MODEL SYMBOLS

EMPLOYEE CERTIFICATE COURSE

Employee who may complete one or more courses, may be awarded more than one certificate.

A course which may have one or more employeescompleted it may have many certificates awarded.

Page 33: Rdbms(Eltp)

E-R MODEL SYMBOLS

Attribute

A property or characteristic of an entity type that is interest to the organization.

STUDENT: Student_ID,Student_NameAUTOMOBILE: Vehicle_ID, Color,Initial capital followed by lowercase.If it has two words, underscore is used to connect the words a each word starts with a capital letter

Page 34: Rdbms(Eltp)

ATTRIBUTES

FLIGHT

Flight_No Date Captain_Name

Page 35: Rdbms(Eltp)

E-R MODEL SYMBOLS

An attribute that may take on more than one value for a given entity instance

Multi-valued attribute

EMPLOYEE SKILL

Page 36: Rdbms(Eltp)

E-R MODEL SYMBOLS

Derived attribute

An attribute whose value can be calculatedfrom related attribute values

EMPLOYEE Years_Employed

Page 37: Rdbms(Eltp)

E-R MODEL

Degree of Relationship

The number of entity types that participate in a relationship.

Page 38: Rdbms(Eltp)

E-R MODEL SYMBOLS

Degree of Relationship

Unary Relationship

A relationship between the instances of asingle entity type.

Page 39: Rdbms(Eltp)

DEGREE OF RELATIONSHIPS

PERSON Is_married_to One-to-one

EMPLOYEE ManagesOne-to-many

Unary Relationship

Page 40: Rdbms(Eltp)

DEGREE OF RELATIONSHIPS

Binary Relationship

A relationship between the instances of two entity types

Page 41: Rdbms(Eltp)

DEGREE OF RELATIOSHIPS

EMPLOYEE CABIN

COURSESTUDENT

DEPARTMENTSCOMPANY

Sits_in

One-to-one

Contains

Register_for

One-to-many

Many-to-many

Binary Relationship

Page 42: Rdbms(Eltp)

DEGREE OF RELATIONSHIPS

Ternary Relationship

A simultaneous relationship among instances of three entity types

Page 43: Rdbms(Eltp)

CARDINALITY CONSTRAINTS

A Cardinality constraint specifies the number of instances of one entity that can be associated with each instance of another entity.

Page 44: Rdbms(Eltp)

CARDINALITY CONSTRAINTS

PATIENT Has PATIENT HISTORY

PATIENTPATIENTHISTORY

Has

Mark

Fred

Visit 1 historyVisit 1 history

Visit 2 history

Page 45: Rdbms(Eltp)

ER Diagram ExerciseTeam Exercise

60 Minutes Draw an ER diagram for the following.

A company purchases items from a number of different vendors, who then ship the items to the manufacturer. The items are assembled into products that are sold to to customers who order the products. Each customer order may order one or more products.

Page 46: Rdbms(Eltp)

Sends

SUPPLIER

SHIPMENT Includes

ITEMS

Supplies

Used_in

PRODUCTRequests PRODUCT

Submits

CUSTOMER

Solution

Page 47: Rdbms(Eltp)

NORMALIZATION

The process of decomposing relations with anomalies to produce smaller well-structured relations.

Anomalies: Errors or inconsistencies that may result when user attempts to update a table that contains redundant data.

Well-structured relations contains minimal redundancy and allows users to insert, modify, and delete the rows in a table without errors or inconsistencies.

Page 48: Rdbms(Eltp)

TYPES OF ANOMALIES

Insertion anomaly Modify anomaly Deletion anomaly

Page 49: Rdbms(Eltp)

INSERTION ANOMALY

EMPLOYEEEmp_IDNameDept_NameSalaryCourse_TitleDate_Completed

Page 50: Rdbms(Eltp)

INSERTION ANOMALY

To insert a row in the EMPLOYEE, user must supply both Emp_ID and Course_Title, since these together make a primary key, hence can not be null.

This is an anomaly since the user should be able to enter employee data without course data.

Page 51: Rdbms(Eltp)

DELETION ANOMALY

Suppose the data of an employee has to be deleted then the data that the employee had completed a course on some date will be lost.

This information may of importance to the training department.

Page 52: Rdbms(Eltp)

MODIFICATION ANOMALY

Suppose an employee gets an increase in salary and has done many courses, the increase must be recorded in each of the rows for the employee, otherwise, the data will be inconsistent.

Page 53: Rdbms(Eltp)

STEPS IN NORMALIZATIONThe process of decomposing relations with

anomalies to produce smaller well-structured relations.

First normal form : Any multi-valued attributes have been removed, so there is a single value at the intersection of each row and column of the table.

Page 54: Rdbms(Eltp)

STEPS IN NORMALIZATIONSecond normal form Any partial functional

dependencies have been removed

Third normal form Any transitive dependencies have been removed

Boyce/Codd normal form Any remaining anomalies that result from functional dependencies have been removed

Page 55: Rdbms(Eltp)

FUNCTIONAL DEPENDENCIES AND KEYS

Normalization is based on the analysis of functional dependencies.

Functional dependency A constraint between two attributes or two sets of attributes.

Emp_ID, Course_Name Date_Completed

The date a course is completed is determined by the identity of the employee and the name of the course.

Page 56: Rdbms(Eltp)

TABLE WITH REPEATING GROUPS

Emp_ID Name Dept_Name Salary Course_Name Date_Completed

1233 Andrew Market 48,000 SSAD

MS-Office

06/12/1999

12/05/1998

1245 James Accounting 52,000 Taxation 09/07/1998

1456 Mary MIS 80,000 C++

D2000

Java Basics

03/03/2000

12/01/1998

14/06/1999

1789 Robert MIS 90,000 DB2

CICS

SSAD

03/03/1998

29/10/1999

15/05/1999

EMPLOYEE

Page 57: Rdbms(Eltp)

TABLE IN FIRST NORMAL FORM

Emp_ID Name Dept_Name Salary Course_Name Date_Completed

1233 Andrew Marketing 48,000 SSAD 06/12/1999

1233 Andrew Marketing 48,000 MS-Office 12/05/1998

1245 James Accounting 52,000 Taxation 09/07/1998

1456 Mary MIS 80,000 C++ 03/03/2000

1456 Mary MIS 80,000 D2000 12/01/1998

1456 Mary MIS 80,000 Java Basics 14/06/1999

EMPLOYEE

Page 58: Rdbms(Eltp)

FIRST NORMAL FORM

A relation is in first normal form when it contains no multi-valued attributes.

The value at the intersection of each row and column must be atomic.

Page 59: Rdbms(Eltp)

SECOND NORMAL FORM

A relation that is in first normal form and has every non-key attribute functionally dependent on the primary key.

Page 60: Rdbms(Eltp)

SECOND NORMAL FORMA relation that is in first normal form is in

second normal form if and only if

1. The primary key consists of only one attribute.

2. No non-key attribute exists in the relation.

3. Every no-key attribute is functionally dependent on the primary key.

Page 61: Rdbms(Eltp)

SECOND NORMAL FORM

To convert relation into second normal form, we decompose the relation into new relationships.

Page 62: Rdbms(Eltp)

SECOND NORMAL FORMEMPLOYEE is decomposed into two relations

Emp_ID Name Dept_Name Salary

1233 Andrew Marketing 48,000

1245 James Accounting 52,000

1456 Mary MIS 80,000

Emp_ID Course_Name Date_Completed1233 SSAD 06/12/1999

1233 MS-Office 12/05/1998

1456 C++ 03/03/2000

1456 D2000 12/01/1998

1456 Java Basics 14/06/1999

EMPLOYE2

EMPLOYE1

Page 63: Rdbms(Eltp)

THIRD NORMAL FORM

Transitive dependency

Functional dependency between two nor more non-key attributes.

A relation is in third normal form (3NF), if it is in second normal form and no transitive dependencies exist.

Page 64: Rdbms(Eltp)

3NF

Cust_ID Name Salesperson Region

Relation with transitive dependencySALES

Cust_ID is the primary key. All of the remaining attributes are functionally dependent on this attribute

However, region is functionally dependent on on salesperson and salesperson is functionally dependent on Cust_ID.

Page 65: Rdbms(Eltp)

Normalization Exercise2 Hours (Team exercise)

Page 66: Rdbms(Eltp)

SQL

S-Q-L/Sequel is the de facto standard language for creating and querying relational databases.

DDL – Data Definition Language DML – Data Manipulation Language DCL – Data Control Language

Page 67: Rdbms(Eltp)

Data Definition Language (DDL)• These commands are used to define

database, including creating, altering, and dropping tables, and establishing constraints.

• Generally restricted to database administrator.

Page 68: Rdbms(Eltp)

SQL Commands

DDLDefine the databaseCREATE Tables, Indexes ViewsEstablish foreign keysDrop tables Maintenance

Design

Page 69: Rdbms(Eltp)

SQL Commands

DMLLoad the databaseINSERT dataUPDATE the databaseManipulate the database (SELECT)

Implementation

Page 70: Rdbms(Eltp)

SQL Commands

DCLControl the databaseGRANT, ADD, REVOKE

Maintenance

Implementation

Page 71: Rdbms(Eltp)

DDL Commands

CREATE TABLE Define a new table and its columns.

DROP TABLE Destroys table

(definition and contents as well as any views and indexes associated with it).

Page 72: Rdbms(Eltp)

DDL Commands

ALTER TABLE Add, delete, and redefine table columns.

CREATE INDEX Defines an index on one column or a

concatenation of columns that enables rapid access to the rows of the table.

Page 73: Rdbms(Eltp)

DDL CommandsDROP INDEX Destroys an index.

CREATE VIEW Defines a logical table

from one or more tables

or views.

Page 74: Rdbms(Eltp)

DDL Commands

DROP VIEW Destroys a view definition and

any other views defined from the deleted view.

Page 75: Rdbms(Eltp)

CREATE TABLECREATE TABLE tablename

(column_name datatype, [NULL|NOT NULL]

[DEFAULT Default_value]

[Column_constraint_Clause].....

[column_name datatype, [NULL|NOT NULL]

[DEFAULT Default_value]

[Column_constraint_Clause].....]....

[table_constraint_clause].......);

Page 76: Rdbms(Eltp)

CREATE TABLE

CREATE Table Order

(Order_ID INTEGER NOT NULL,

Order_Date Date,

Order_Quantity INTEGER);

Page 77: Rdbms(Eltp)

CREATE TABLECREATE TABLE EMPLOYEE

(Emp_ID VARCHAR NOT NULL, First_Name CHAR(15),

Last_Name CHAR(15), CONSTRAINT EMP_PK PRIMARY KEY (Emp_ID) CONSTRAINT PROJ_FK FOREIGN KEY REFERENCES PROJECT(Proj_ID)

CREATE TABLE PROJECT(Proj_ID INTEGER NOT NULL, Proj_Location VARCHAR(15));

Page 78: Rdbms(Eltp)

CREATE TABLE

Other constraint clauses

UNIQUE Specifies alternate keys.

UNIQUE(Column_Name)

REFERENCES clause prevents making a change in the foreign key value

Page 79: Rdbms(Eltp)

CREATE TABLEON UPDATE RESTRICT Denies updates that delete or change a

primary key value unless no foreign key value references that value in in any child table.

A Customer Id can only be deleted if it is not found in ORDER table.

CUSTOMER(PK = CUST_ID)

ORDER

(FK=CUST_ID)

Page 80: Rdbms(Eltp)

CREATE TABLE

ON UPDATE CASCADE

Updates change of a primary key value in in any child table.

Changing Customer ID will result in that value changing in the ORDER table.

CUSTOMER(PK = CUST_ID)

ORDER

(FK=CUST_ID)

Page 81: Rdbms(Eltp)

CREATE TABLE

CREATE TABLE CUSTOMER

(CUSTOMER_ID INTEGER NOT NULL,

CUSTOMER_NAME VARCHAR(40),

.......

CONSTRAINT CUSTOMER_PK PRIMARY KEY

(CUSTOMER_ID) ON UPDATE RESTRICT);

Page 82: Rdbms(Eltp)

CHANGING TABLEALTER TABLE

ALTER TABLE CUSTOMER

ADD (CUSTOMER_RATING VARCHAR(2));

The status of the new column is NULL..

Invaluable for adapting to inevitable modifications to databases.

Page 83: Rdbms(Eltp)

REMOVING TABLES

DROP TABLE

DROP TABLE CUSTOMER;

Dropping table will cause associated indexes and privileges granted to be dropped.

Must have DROP ANY TABLE system privilege

Page 84: Rdbms(Eltp)

DML COMMANDS

INSERT Populates table with data

Data values must be ordered in the same order as the columns in the table.

INSERT INTO CUSTOMER VALUES

( 001,’Richard’, ‘1267 First Main Green House’);

Page 85: Rdbms(Eltp)

INSERTING DATA INTO SOME COLUMNS

When data is not entered into some columns

a) Enter the value NULL for that column

b) Specify the columns to which data are to be added

INSERT INTO PRODUCT(PROD_ID, UNIT_PRICE)

VALUES (145, 78.65);

Page 86: Rdbms(Eltp)

DELETING DATARows can be deleted individually or in groups

DELETE FROM CUSTOMER

Deletes all rows of table

DELETE FROM CUSTOMER WHERE STATE = ‘AP’;

Deletes rows that meet a certain criteria.

Page 87: Rdbms(Eltp)

CHANGING TABLE CONTENTS

UPDATE - used to modify column values of one or more selected rows.

UPDATE PRODUCT SET UNIT_PRICE = 775 WHERE PRODUCT_ID = 7;

Page 88: Rdbms(Eltp)

CREATING INDEXES

Indexes provide rapid random access. User need not directly refer to indexes. Indexes are created for Primary Key and

Foreign Key. Index is updated as data is entered or

updated.

Page 89: Rdbms(Eltp)

CREATING INDEXES

CREATE INDEX NAME_IDX

ON EMPLOYEE (EMP_NAME);

DROP INDEX NAME_IDX;

Page 90: Rdbms(Eltp)

PROCESSING SINGLE TABLES

SELECT Command with its various clauses allows one to query on data contained in the table.

SELECT commands may be syntactically correct but do not answer the exact question.

Parse queries into smaller parts, examine the results, and then recombine them.

Page 91: Rdbms(Eltp)

Clauses for the SELECT statement

SELECT Lists the column(s) from table

FROMIdentifies tables from which columns will be chosen.

WHERE Includes the conditions for row selection.

Page 92: Rdbms(Eltp)

COMPARISON OPEREATORS IN SQL

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<>/!= Not equal to

Page 93: Rdbms(Eltp)

BOOLEAN OPERATORS

AND Joins two or more conditions and returns results only when all

conditions are true.

OR Joins tow or more conditions and returns results only when any

condition is true.

NOT Negates an expression

Page 94: Rdbms(Eltp)

SELECT STATEMENTQuery: What is the address of customer

named Holmes? Use an alias, NAME for customer name.

SELECT CUSTOMER_NAME AS NAME, CUSTOMER_ADDRESS FROM CUSTOMER WHERE NAME = ‘HOLMES’;

Page 95: Rdbms(Eltp)

SELECT STATEMENT

Result:

NAME CUSTOMER_ADDRESS

HOLMES 1998, Watson Road

Column alias name may be used in the WHERE clause even though it is not defined in the table.

Page 96: Rdbms(Eltp)

USING EXPRESSIONSQuery: What is total value of each product in

inventory?

SELECT PRODUCT_NAME,UNIT_PRICE,QOH,

UNIT_PRICE * QOH AS VALUE FROM PRODUCT;

Page 97: Rdbms(Eltp)

USING EXPRESSIONSResult:PRODUCT_NAME UNIT_PRICE QOH VALUE

Table 400 5 2000Desk 200 3 600Dining Table 800 4 3200

3 rows selected.

Page 98: Rdbms(Eltp)

USING FUNCTIONS

Manipulate data from the row. Resulting table will contain aggregated data

instead of row-level data. Examples COUNT, MIN, MAX, SUM,

AVG..

Page 99: Rdbms(Eltp)

USING FUNCTIONSQuery: How many different items are ordered on

order number?

SELECT COUNT(*) FROM ORDER WHERE ORDER_ID = 1004;

Result:

Count(*)

2

Page 100: Rdbms(Eltp)

RANGESQuery: Which products in the PRODUCT

table have unit price between 200 and 300?

SELECT PRODUCT_NAME,UNIT_PRICE FROM PRODUCT WHERE UNIT-PRICE > 200 AND UNIT_PRICE < 300;

Page 101: Rdbms(Eltp)

RANGES

SELECT PRODUCT_NAME,UNIT_PRICE FROM PRODUCT WHERE UNIT-PRICE BETWEEN 200 AND 300;

NOT BETWEEN CAN ALSO BE USED

Page 102: Rdbms(Eltp)

DISTINCT

DISTINCT rows without duplicates will be displayed.

SELECT ORDER_ID FROM ORDER;

SELECT DISTINCT ORDER-ID FROM ORDER;

Page 103: Rdbms(Eltp)

IN AND NOT IN LISTS

To match a list of values.

SELECT CUSTOMER_NAME,CITY,STATE

FROM CUSTOMER WHERE STATE IN (‘AP’, ‘TN’, ‘MP’, ‘UP’, ‘JK’);

Page 104: Rdbms(Eltp)

SORTING RESULTS

ORDER BY Displays results in a sorted order.

Query: List all customers from AP, TN, MP, UP, and JK, alphabetically by state, and alphabetically by customer within each state.

Page 105: Rdbms(Eltp)

SORTING RESULTS

NAME STATE

Amarnath MP

Ramesh TN

Sruthi AP

Kuldeep UP

Ahmed JK

Laxman AP

Jairaj MP

SELECT CUSTOMER_NAME,CITY FROM CUSTOMER WHERE STATE IN(‘AP, ‘TN’, ‘MP’, ‘UP’, ‘JK’)ORDER BY STATE, CUSTOMER_NAME;

Page 106: Rdbms(Eltp)

SORTING RESULTS

NAME STATE

Amarnath MP

Ramesh TN

Sruthi AP

Kuldeep UP

Ahmed JK

Laxman AP

Jairaj MP

NAME STATE

Laxman AP

Sruthi AP

Ahmed JK

Jairaj MP

Amarnath TN

Ramesh TN

Kuldeep UP

Page 107: Rdbms(Eltp)

CATEGORIZINGGROUP BY

Useful when paired with aggregate functions like SUM or COUNT.

Divides table into subsets.

Provides summary information for that group.

Page 108: Rdbms(Eltp)

GROUP BYQuery: Count the number of customers in each

state.SELECT STATE, COUNT (STATE) FROM

CUSTOMER GROUP BY STATE;

Result:STATE COUNT(STATE)AP 2JK 1MP 1TN 2UP 1

Page 109: Rdbms(Eltp)

HAVING CLAUSE

HAVING clause is similar to WHERE, but it identifies groups that meet a criterion rather than rows.

Query: Find only states with more than one customer.

Page 110: Rdbms(Eltp)

HAVING CLAUSE

SELECT STATE, COUNT (STATE) FROM CUSTOMER GROUP BY STATE HAVING COUNT (STATE) > 1;

Result:

STATE COUNT (STATE)

AP 2

TN 2

Page 111: Rdbms(Eltp)

PROCESSING MULTIPLE TABLES

JOIN A relational operation that causes two tables to be combined into a

single table.

Page 112: Rdbms(Eltp)

EQUI-JOIN

A Join in which the joining condition is based on equality between values in the common columns.

Page 113: Rdbms(Eltp)

EQUI-JOINQuery: What are the names of all customers who have

placed orders?

SELECT CUSTOMER.CUSTOMER_ID, ORDER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER, ORDER WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;

What happens if the WHERE clause is omitted?

Page 114: Rdbms(Eltp)

NATURAL JOINNatural join is same as Equi-join except on of the

duplicate columns is eliminated in the result table.

SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER, ORDER WHERE

CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;

Page 115: Rdbms(Eltp)

OUTER JOINA join in which rows that do not have matching

values in common columns are nevertheless included in the table.

Query: List all customer name, identification number, and order number for all customers listed in the CUSTOMER table. List even if there is no order available for that customer.

Page 116: Rdbms(Eltp)

OUTER JOIN

SELECT CUSTOMER.CUSTOMER_ID,CUSTOMER_NAME, ORDER_ID FROM CUTOMER, ORDER WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMERID (+);

Page 117: Rdbms(Eltp)

OUTER JOIN

The (+) indicates that a match with an all-null row should be returned for any row in CUSTOMER for which there is no match in ORDER table.

Page 118: Rdbms(Eltp)

SUBQUERIES

Subquery technique involves placing an inner query (SELECT, FROM, WHERE) within a WHERE or HAVING clause of another (outer) query.

Subquery is enclosed in parenthesis.

Also called nested queries.

Page 119: Rdbms(Eltp)

SUBQUERIESQuery: What is the name and address of the

customer who placed order number 6878?Join query:SELECT

CUSTOMER_NAME,CUSTOMER_ADDRESS FROM CUSTOMER, ORDER WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID ANDORDER_ID = 6878;

Page 120: Rdbms(Eltp)

SUBQUERY

SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS FROM CUSTOMER WHERE CUSTOMER.CUSTOMER_ID =

(SELECT ORDER.CUSTOMER_ID FROM ORDER WHER ORDER_ID = 6878);

Page 121: Rdbms(Eltp)

SUBQUERIES

Query: Which customers have placed orders?

SELECT CUSTOMER_NAME FROM CUSTOMER WHERE CUSTOMER_ID IN (SELECT DISTINCT CUSTOMER_ID FROM ORDER);

Page 122: Rdbms(Eltp)

VIEWS

Simplifies query commands.Provides valuable data security.Uses little storage space.Does not exist in physical form, a virtual table.I

Page 123: Rdbms(Eltp)

VIEWS

CREATE VIEW INVOICE

SELECT Column names

FROM CUSTOMER, ORDER

WHERE <Conditions>;

SELECT CUSTOMER_ID, CUSTOMER_ADDRESS FROM

INVOICE WHERE ORDER = 7678;

Page 124: Rdbms(Eltp)

Suggested references

1. Modern Database Management, Fred Mcfadden, Jeffrey A Hoffer, Mary B Presscott, Pearson Education Asia

2. Fundamentals of Database Systems, Elmasri R and S B Navathe, Benjamin Cummings

3. An Introduction to Database Systems, Date C J, Addison-Wesley

Page 125: Rdbms(Eltp)

Quiz