This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
The purpose of this 3 day Course is to provide programmers with the tools necessary to understand database and write SQL queries
Welcome
tools necessary to understand database and write SQL queries.
This Course will cover the following topics:– Introduction to RDBMS– Introduction to SQL– Introduction to execute records using different Queries– Introduction to commonly used concepts in programming like– DDL
• Explain Data Definition Language, Data Manipulation Language
• Describe the database constraints• Describe Aggregate functions, joins and sub queries,
Views
Learn by Doing• Hands-on programming
Course Approach
Activity-based Learning• Activities are designed to be difficult but doable• Activities have time limits to encourage wise use of your time• Activities will force you to research on the required knowledge
Resource-rich EnvironmentU il bl (i li / ffli t i l h
Participate• Don’t just listen to discussions, interact!• If in doubt, ask questions to clarify.• Spot problems and suggest alternatives or workarounds.
Teamwork• Cooperate, coordinate, collaborate!
Course Approach (Cont.)
• Work together to complete the deliverables for the course.
Be resourceful • Don’t ask for answers or solutions, find them!• The course environment provides all the necessary tools
• Understand the purpose of storing data.• Understand drawbacks of file systems• Understand drawbacks of file systems.• Understand the meaning of Database.• Compare Databases with traditional methods.• Understand the Multi-Tier Architecture.• Understand Data Models.
Data dependency means that the application program is dependant on the data So any modifications made on the data affects the application programDependency data. So any modifications made on the data affects the application program using it, forcing it to be rewritten.
Redundancy Redundancy is the repetition of data. Data duplication was allowed in the traditional approach. Data redundancy caused data inconsistency to occur in the data.
Sharing Data Sharing was difficult or impossible with traditional systems.
Security Data stored on the computer must be secured.
It was difficult to enforce independent information security in traditional approach.
Transaction Control
Transaction is unit of work.If one is performing some work ( for e.g. inserting some records) other persons should not be able to use that particular data.There was no way to isolate independent units of work in traditional approach.
Introduction to DBMS
• DBMS is Data Base Management System.• It is a program that lets one or more computerIt is a program that lets one or more computer
users create and access data in a database. • It allows data definition, storage, and management
of data in the centralized pool that can be shared by many users.
2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL
Data ConcurrencyDatabases allow multiple users to access the same database simultaneously.Data RedundancyA properly set-up database minimizes data redundancy. It will avoid data repetition in the databases.
Data ValidityDatabases allow you to set up rules that ensure that data remains consistent when add or
dif d tmodify data. Data SharingSharing data is also much easier using a database. You can share data among a number of users on the same computer or among users on different computers linked via a network or the Internet. Databases also allow more than one person to access the database at the same time and change the data stored; the database management system handles simultaneous changes.
Data SecurityOne final advantage of databases is security. Most database management systems allow you to create users in order to indicate various levels of security. Before someone accesses the database, he or she must log on as a specific user. Each user has various rights and limits. Someone who maintains the database has full ability to edit data, modify the database’s structure, add and delete users, and so on. Other users may only have the ability to view data but not change it, or you may even want to limit what data they can view. Many database management systems provide a granular level of security, that is, they are very
2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL
This diagram shows how application programs interact with the DBMS. DBMS actually is a repository of data which provide information to the application programs as well as storing information from the application programs.This is a typical example of a client-server system, where different application programs will access the DBMS via network. All the applications will access only one database. The DBMS is physically stored as Files in the Hard Disk of the system.
2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL
Two tier architectureTwo tier architectures consist of three components distributed in two layers: client (requester of services) and server (provider of services). The three components are User System Interface (such as session, text input, dialog, and display management services) Processing Management (such as process development processProcessing Management (such as process development, process enactment, process monitoring, and process resource services) Database Management (such as data and file services) The two tier design allocates the user system interface exclusively to the client. It places database management on the server and splits the processing management between client and server, creating two layers. In general the user system interface client invokes services from theIn general, the user system interface client invokes services from the database management server. In many two tier designs, most of the application portion of processing is in the client environment. The database management server usually provides the portion of the processing related to accessing data (often implemented in store procedures). Clients commonly communicate with the server through SQL statements or a call-level interface. It should be noted that
connectivity between tiers can be dynamically changed depending upon the user's request for data and services.
16
2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL
Hierarchical Model : This data model explicitly makes use of the hierarchies by providing a tree by which all data are accessible. The network model allows each record to have multiple parent and child records, forming a lattice structure. Relational Model : Each table represents some real-world person, place, thing, or event about which information is collected. A relational database is a collection of two-dimensional tables. The relational database is built around the Relational Model designed by E. F. Codd at IBM in 1970. We will explore Relational Model in detail in the coming slides.
Basic Terms and Definitions• The term 'database' has many interpretations - one
definition is that database is a 'collection of persistent data‘.
• A relational database is one in which the data consists of a 'collection of tables related to each other through common values‘.
• A relational database management system (RDBMS)uses matching values in multiple tables to relate the information in one table with the information in the other table.
# 1 Information rule • Database must consist of tables related to each other and data should be stored in the form of tables only.
# 2 Guaranteed access Rule
• The data can be accessed by specifying the table name and the columns that define the primary key. Primary key ensures that each value is unique and accessible.
# 3 Systematic treatment of null values
• A Null is an unknown value and every database must have a provision for storing NULL values.
# 4 Dynamic on-line catalog based on the
l ti l d l
• In addition to user data, a relational database contains data about itself, there are 2 types of tables.
relational model • User tables - that contain the 'working' data and system tables contain data about the database structure.
• Metadata –that describes the structure of the database itself and includes object definitions (tables, indexes, stored procedures, etc.) and how they relate to each other.
• The collection of system tables is also referred to as the system catalog or data dictionary.
Codd’s 12 rules (Contd…)
Rule No. Rule Description
# 5 Comprehensive Data Sublanguage Rule
• There must be a single language that handles all communication with the database management system.
• The language must support relational operations with respect to: data modification, data definition and administration.
# 6 View Updating Rule • Database must allow for presenting data to the user in different combinations through views.
• Views are nothing but virtual tables which contains extraction of data from the source tables
• Data is logically stored in tables and physically in files. For any change in the structure of tables and relationships, the application need not be re-created.
# 10 Integrity Independence
• In order to be considered relational, data integrity must be an internal function of the DBMS; not the application program.
• Data integrity means the consistency and accuracy of the data in the database (i.e., keeping the garbage out of the database).
22
2_IntroductionToRDBMS.pptIntroduction to RDBMS and SQL
0. Foundation RuleInterestingly Codd defined a Rule 0 for relational database systems."For any system that is advertised as, or claimed to be, a relational database management system, that system must be able to manage databases entirely through its relational capabilities, no matter what additional capabilities the system may support." (Codd, 1990)That means no matter what additional features a relational database mightThat means, no matter what additional features a relational database might support, in order to be truly called relational it must comply with the 12 rules. Codd added this rule in 1990. Also he expanded this 12 rules to 18 to include rules on catalogs, data types (domains), authorization and other. Codd himself had to admit the fact that based on the above rules there is no fully relational database system available. This has not changed since 1990. To be more specific rules 6, 9, 10, 11 and 12 seem to be difficult to satisfy.y
• Understand Database design techniques.• Understand the need for normalization.U de sta d t e eed o o a at o• Understand different types of normalization.• Understand Functional dependencies.• Understand Denormalization.
• A relational table is said to be in a normal form if it satisfies a certain set of constraints.
• They are special properties and constraints that a table schema should possess in order to achieve certain desired goals like minimizing redundancy of data.
• There are six normal forms that have been defined
2 Pens 1000 M1002 Magnum D1002 World 10012 14-May-07 10
3 Mobiles 4000 M1003 Coral D1003Alpha Company
1001010012 16-May-07 15
27
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
A design is in the first normal form if:There are no repeating groupsAll the key attributes are definedAll attributes are dependent on the primary key
A table is said to be in the 1NF when each cell of the table contains precisely one value.Consider the following project Table.ECODE DEPT Projecode HoursECODE DEPT Projecode Hours
In the example, Employee Name has a functional dependency on Employee p , p y p y p yID, because a particular Employee ID value corresponds to one and only one Employee Name value. The reverse is not true because there could be several employees having the same name and hence one Employee name value could correspond to more than one Employee ID. Employee ID is therefore not functionally dependent on Employee Address.
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
Let us take another example to understand Full functional dependence andPartial functional dependence. Suppose we have a transaction relation asshown here. For the Transaction relation, we may now say that:
Cname is fully functionally dependent on C#Ccity is fully functionally dependent on C#Cphone is fully functionally dependent on C#Qnt is fully functionally dependent on (C#, P#, Date – composite key)C i t f ll f ti ll d d t (C# P# D t ) it i lCname is not fully functionally dependent on (C#, P#, Date), it is only partially dependent on it (and similarly for Ccity and Cphone).
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
A relation is in 2NF if and only if it is in 1NF and every non-key attribute is irreducibly dependent on the primary key
orA table to be in 2NF , the non key attributes must be fully functionally dependent on the Whole Key and not part of a Key.
The example discussed before is in first normal form To convert into SecondThe example discussed before is in first normal form. To convert into Second Normal form, apply functional dependency on the attributes of the table.
Two tables are created out of the above example.1st table – Items and 2nd table – Orders.
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
Example :Let’s take an example in which a project manager manages a number of projects. Now the relation ‘Project’ has a candidate key ‘ProjectNum’. The ProjectNum field determines the values for all other fields – ProjectTitle, ProjectMgr and Phone. For a particular projectNum, there will always be a unique value in these other fields. So ProjectTitle, ProjectMgr and Phone are fully functionally dependent on ProjectNum.Now consider the attribute ‘Phone’. The phone number is dependent on the manager and manager is dependent on the project number. This is transitive dependency. Note that project manager is not a candidate key since the same manager manages more than one project.
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
Boyce-Codd normal form (BCNF) is a more rigorous version of the 3NF deal with relational tables that had
(a) multiple candidate keys(b) composite candidate keys and (c) candidate keys that overlapped .
Fourth Normal FormA relational table is in the fourth normal form (4NF) if it is in BCNF and all multivalued dependencies are also functional dependencies.
Fifth Normal FormA table is in the fifth normal form (5NF) if it cannot have a losslessA table is in the fifth normal form (5NF) if it cannot have a lossless decomposition into any number of smaller tables.
3_DatabaseDesignTechniques.pptIntroduction to RDBMS and SQL
In the example the relation Item, item_id is the primary key. The item_iddetermines the values for all the other fields – Item_Desc, Price,manufacturer_id, Distributor_id.Manufacturer name is dependent onmanufacturer_id which is not a candidate key.
The attribute manufacturer_name is dependent on the manufacturer_id andmanufacturer_id is dependent on the item_id. This is transitive dependency.The manufacturer_id is not a candidate key since the same manufacturercan supply many items.
Same is the case with Distributor_id and Distributor_name. The attributedistributor_name is dependent on the Distributor_id and Distributor_id isdependent on the item_id. This is transitive dependency. The Distributor_idyis not a candidate key since the same distributor can supply many items.
DENORMALIZATION• What is DENORMALIZATION?• Denormalization is a technique which is the opposite of normalization. In order
to speed up the database access, it suggests to move from higher level of normalization to lower normal forms of database modelingnormalization to lower normal forms of database modeling.
• NEED FOR DENORMALIZATION• Consider 2 tables –Orders and OrderItems which stores the order and items to
be ordered respectively. As per your analysis, you have created a view called Order_Item_View. This is one of the most heavily used views in the database. To read data from Order and the OrderItems table will require a join statement and access to many physical pages. To write data will require several update statements. Moreover 90 percent of Orders have no more than 5 positions. To avoid joins, you can merge the two tables into 1 table.
avoid joins, you can merge the two tables into 1 table.• Data is normalized to avoid maximum redundancy. They are not optimized for
minimum access time. In the case of denormalization process, time does not play a role. The only reason why denormalization is done is to enhance the performance.
• A design is said to be in first normal form(1NF) when there are no repeating groups and all attributes are dependent on the primary keyon the primary key.
• An entity type is in second normal form (2NF) if it is in 1NF and all its attributes are dependent on the primary key.
• A transitive dependency is a type of functional dependency in which the value in a non-key field is determined by the value in another non-key field and that fi ld i did k
• Attributes are the significant properties or characteristics of an entity that help in describing y p gthe entity and provide the information needed to interact with it or use it.
Relationships are the associations between entities. They can involve one or more entities and belong to particular relationship typesbelong to particular relationship types.
Mapping cardinalities • Cardinality is a quantity relationship between elements.• The number of rows in the table is called as cardinality.• Mapping cardinalities or cardinality ratio, expresses the
number of entities to which another entity can be associated via a relationship set.
• The following are the different mapping cardinalities– One to one.
candidates to become a primary key since choosing any one of them will make a row unique. In these cases we have to choose voluntarily one column as primary key.
Candidate Key (Contd...)• Overlapping candidate key: Two candidate keys overlap
if they involve two or more attributes each (composite candidate key) and have one or more attribute in common.
• E – R model is the building block of any database.• E – R Model is essential for any good database design.• Keys play a vital role in Maintaining data accuracy in a
Database• Primary key enforce entity integrity by uniquely
identifying entity instances.• Candidate key is a Key that uniquely identifies row in a
5_IntroductionToSQL.pptIntroduction to RDBMS and SQL
Data Definition Language : It is a method of data definition and storage.The Data Definition Language is used to create object (e.g. Table), alter thestructure of an object and also to drop the object created.The conceptRelating to Data Definition Language are explained in paragraph.
DDL is a language used by a database management system which allows users todefine the database and its objects, specifying data types, structures andconstraints on the data
It allows the Specification like:•structure for each relation and integrity constraints•set of indices to be maintained for each relation (Indexes)•security and authorization information for each relation•The physical storage of each relation on disk•It is a language that enables users to access or manipulate data asorganized by the appropriate data model•DML Manipulation commands are the most frequently used SQL commands.•They are used to query and Manipulate existing objects like tables
Transaction Control Language (TCL)• We can use SQL to control transactions.• Transactions:
– Collections of operations that form a single logical unit of work.
– It ensures that all changes made are either committed to the database or if there is a failure at any point of time then none of the changes are committed in the database
• Understanding Data Types• Creating/Altering/Dropping a User• Creating/Altering/Dropping a User• Assigning and Revoking permissions on user• Creating a Table• Altering a Table• Truncate Table
The above example adds a foreign key constraint FK_DEPTNO2 to the EMP_INFO1 table on the DEPTNO column which references the primary key of the DEPT_INFO Table.
Unique Constraint• Unique Key Constraints are used to enforce the
uniqueness of a column. • If a column has a Unique Constraint on it duplicate values• If a column has a Unique Constraint on it, duplicate values
cannot be inserted on that column.• Unique key allows Null value to be stored.• Example: Create a table emp_sal to add the unique
The above example adds a unique key constraint UK_JOB_HDATE on the job and hiredate columns of the EMP_SAL table.
CHECK constraint
• Check Constraints are the most elementary form of integrity constraints.
• Check constraint is also known as Domain Integrity.• This powerful feature allows to establish range for data.• Check Constraints are created by specifying a domain
(Range) for a column.• If we specify a domain constraint for a particular
Default• The default keyword is assigned to a column of a table at the
time of creating a table or altering it.• The value in the default keyword is applied when no value is y pp
inserted in the table using the INSERT statement.• Example: Create a table products1 to create default
CREATE TABLE PRODUCTS1 (PRODUCT_NO NUMBER(2) NOT NULL, NAME VARCHAR2(40) NOT NULL, STATE VARCHAR2(2) DEFAULT 'MH')INSERT INTO PRODUCTS1 (PRODUCT NO NAME)
Learning ObjectivesAt the end of this presentation, you should be able to:
• Insert new data into the table• Update existing data• Delete existing data• Retrieve data from the table using SELECT• Filter rows using WHERE clause• Sort the results retrieved from the table• Char Number and Date Functions
8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL
Sometimes changes to the database become imminent. For example DEPT table, to reflect such changes to the existing record in a DEPT table the update command is used. With the update command we can update rows in the Table. A single column may be updated or more than one column could be updated. Specific rows could be updated based on a specific condition.
UPDATE Dept SET state=‘MH’;UPDATE Dept SET state= MH ;
It will update all the state as ‘KANPUR’ from the dept table.
UPDATE Dept SET state=‘MH’WHERE DeptNo=1;
It will update the state as a MH where DEPTNO is 1It will update the state as a MH where DEPTNO is 1
8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL
One or More rows could be deleted using delete command. Alternatively, all rows of DEPT table could also be deleted while structure remains unaltered. To delete specific rows from a table the ‘where’ clause is used in combination with the delete command. To delete several rowsFrom a table, select the rows with appropriate condition in a ‘where’ clause . The ‘where’ clause can also include a query.The Delete command consists of a ‘From’ clause followed by an optional ‘where’The Delete command consists of a From clause followed by an optional whereclause.
Example 1:DELETE FROM DEPT;It Will delete all the rows from the DEPT table.
Example 2:DELETE FROM DEPT WHERE DEPTNO=1;It will delete all the rows from DEPT table where DEPTNO = 1.
• The IN operator is generally used to retrieve values from a list of values called as inclusive list.I l i li t i li t hi h t i lti l l t b• Inclusive list is a list which contains multiple values to be retrieved for the same column.
• The IN operator checks the database to see if the specified column matches one or more of the values listed inside the list.Example : To get the list of Employees working as MANAGER and ANALYST:
SELECT EMPNO,ENAME FROM EMPWHERE JOB IN (‘MANAGER’ ,’ANALYST’);
MANAGER and ANALYST:EMPNO ENAME
================•7566 JONES7698 BLAKE7782 CLARK•7788 SCOTT7902 FORD
Sample Output
Using BETWEEN Operator• The BETWEEN operator allows to specify a range of values.• Where the range consists of lower range and a higher range.
It eliminates the use of > and < Relational operators• It eliminates the use of >= and <= Relational operators• BETWEEN operator can be modified using AND
Example: To get EMPNO,ENAME,JOB,SAL where salary is in the range 1000 to 2000 (inclusive) :
8_DataManipulationLanguage.pptIntroduction to RDBMS and SQL
Column standing position is the position of the column in the select statement.The column standing position comes handy when we are applying some aggregatefunctions on a column name and that column has to be used in the order by clause
Example : SELECT ENAME,JOB FROM P WHERE DEPTNO IN (10,20) ORDER BY 1 DESC, 2;
then result1 is returned, else expression is compared to search2 and if found equal returns result2 and so on. If no match found, then “default” is returned.
Learning Objectives• Understand aggregate functions• Work with Group By and Having By Clause.• Work with Set Operators.• Work with Sub queries and Correlated sub queries• Work with EXISTS and NOT EXISTS• Work with different types of joins• Understand the difference between joins and subqueries
COUNT(Qty) Returns the number of rows that do not have NULL Value in the column Qty.
COUNT(*) Returns the number of rows in the table.
5
117
9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL
The aggregate functions ignore the null values while applying aggregation.
Example:
SELECT AVG(COMM) FROM EMP will return 550, however
SELECT AVG(NVL(COMM,0)) FROM EMP will return 157.14
The difference in result is due to the null values ignored in the earlier example. Withthe use of NVL function, the null values are converted to 0 and hence they are usedwhile performing the average function.
Using HAVING Clause• HAVING Clause is used to filter data and is used only with
GROUP BY clause
• Aggregate functions can be used with the HAVING clause.
• Both the WHERE and HAVING clause are used for filtering the data. However, the WHERE clause is applied before the GROUP BY whereas the HAVING clause is applied after GROUP BY.
• For the above operators to work correctly, same number of columns must be specified in each SELECT statement and the data types should also match.
• The order by clause can be used at the end of the last select statement and can be sorted only on the columns specified in the first SELECT statement.
12
122
Introduction to RDBMS and SQL 9_AggregateFunctions_Joins_Subquries.ppt
Example: To get a list of all the deptno where the employees are working along with the list of those deptno where noare working along with the list of those deptno where no employees are working in it.
SELECT DEPTNO FROM DEPTUNIONSELECT DEPTNO FROM EMP
• The query which is placed before the inner query is called• The query which is placed before the inner query is called as the Outer query or Parent Query
• In Independent Sub queries– Inner query is executed independent of outer query.– The inner query executes only once.
ALL e u ed by a sub que y o a a ues e u edby the subquery. Used when subquery returns multiple rows along with comparison operators.
EXISTS It always returns data in terms of TRUE or False value. Used with co-related subqueries.
22
127
9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL
Contents:If the option of subquery was not available then to solve the query of finding theemployees who are receiving the salary less than the average salary, 2 separatequeries will be required as shown below:
1) Find the average salary• SELECT AVG(SAL) FROM EMP
2) Get the average salary and find the employee names2) Get the average salary and find the employee names.• SELECT ENAME FROM EMP WHERE SAL < 2073.21
Instead of executing these two queries separately, you can execute it through asubquery. The advantage here is that if there are any change in the EMP table, i,enew record is added in emp table or the salary is updated or a record is deleted,then the second query will not give the correct result since the average is changedthen the second query will not give the correct result since the average is changed.So, for every change in the EMP table, the first query has to be run first, theaverage has to be noted and then execute the second query. To avoid this situatuionsubquery can be used as shown below:
• SELECT ENAME FROM EMP WHERE SAL < (SELECT AVG(SAL) FROM EMP);
WHERE E1.MGR E2.EMPNO);•CLARK•SCOTT•TURNER•ADAMS•JAMES•FORD•MILLER
28
Using EXISTS
• Exists clause checks for the existence of rows and does not compare columns or its values.It i d t h k th i t f d t di t• It is used to check the existence of data rows according to the condition specified in the inner query and passes the existence status to the outer query to produce the result set.
• EXISTS clause, always returns data in terms of a TRUE or FALSE value.
• EXISTS clause can also be used with the not operator
Example: To display the ename, job, sal and dname in which the employees are working along with the dname in which no employees are workingare working.
SELECT ENAME,JOB,SAL, DNAME FROM DEPT DLEFT JOIN EMP E ON D.DEPTNO =
9_AggregateFunctions_Joins_Subqueries.pptIntroduction to RDBMS and SQL
The above example will retrieve rows from order_master table which do not haveany matching records in the order_detail table.Such a retrieval is due to thepresence of an outer join(+).
Example: To display the ename, job, sal and dname in which the employees are working along with the dname in which no employees are workingare working.
SELECT ENAME,JOB,SAL, DNAME FROM EMP ERIGHT JOIN DEPT D ON E.DEPTNO =
Full Outer Join• A full outer join is essentially a combination of
left and right outer joins i.e..,The records from the table on left are included even if– The records from the table on left are included even if there are no matching records on the right
– The records from the table on the right are included even if there are no matching records on the left.
Example: To find out the manager names for each of theemployee
S l O t tSELECT E1.ENAME||'REPORTS TO '|| E2.ENAME AS REPORTS FROM EMP E1, EMP E2 WHERE E1.MGR=E2.EMPNO;
Sample Output :•REPORTS•==============•SMITH REPORTS TO FORD•ALLEN REPORTS TO BLAKE•WARD REPORTS TO BLAKE•JONES REPORTS TO KING•MARTIN REPORTS TO BLAKE
•BLAKE REPORTS TO KING•CLARK REPORTS TO KING•SCOTT REPORTS TO JONES•TURNER REPORTS TO BLAKE•ADAMS REPORTS TO SCOTT•JAMES REPORTS TO BLAKE•FORD REPORTS TO JONES•MILLER REPORTS TO CLARK
44
Sample Output :
9: Aggregate Functions, Joins and Sub queriesActivity (4 of 4)
• Aggregate Functions are applied on rows and return single value.GROUP BY clause works on rows which can be grouped• GROUP BY clause works on rows which can be grouped on the basis of non-aggregate columns.
• SUBQUERIES are SQL statements within SQL statement.• SUBQUERIES can be independent or correlated.• Joins are used to retrieve data from more than one table.• Different types of JOINS
from a single table • Views can be used as a security mechanism to
restrict the data available to end users • Views can also be used to aggregate data.
4
143
10_Views.pptIntroduction to RDBMS and SQL
This example shows creating a view called EmpView from the EMP table.This view contains two columns EmpNo and Empname which are taken from EMP table. The actual data will be in the EMP table, which can be manipulated from the EmpView.The EmpView will not occupy memory. But those who are using this view can see only EmpNo and Empname columns.They won’t be able to see the entire EMP tableThey won t be able to see the entire EMP table.
This example shows how to create a view from an existing table. Ask the participants to create a table Supplier with columns supp_no, supp-name, city, state, postal_code.Ask the participants to enter few data.The example creates a view called v_supp which is derived from the Supplier table. It contains supp_no, supp_name and supp_city columns from the Supplier table.
Second example creates a v_supp_city View from Supplier table. But this view contains rows which belong to the MUM city.
The syntax of Complex view is similar to Create ViewComplex view is a view which contains normally GROUP BY functions as well as joins.The above example creates a complex view v_dept_emp which selects the dname column, maximum sal, minimum sal and average sal.The example uses three Aggregate functions and it joins two tables Dept and Emp.
Faculty Notes:The With Check option clause specifies that Inserts and Updates performed through the View are not allowed to create rows which the view cannot select, and therefore allows integrity constraints and data validation checks to be enforced on data begin Inserted or Updated.
Overview This exercise will require participants to design the database using normalization techniques. Participants should identify the primary key and will link the two tables via a foreign key.
Instructions The normalized structure should be created using the Microsoft Word.
1. In order to proceed with normalization, first analyze the given data structure and identify all related data elements. If required or needed create new data elements create new tables or reuse the data elements. Data elements and tables should be unique. Name the tables with <tablename>_INFO.
Hints 1. Ensure the following while normalizing the table:
Each course has many sections and the sections are taught by different instructors.
A student may enroll in 1 section or many sections or may not enroll in any sections. i.e., the student may come just for inquiry of a particular course but may not necessarily enroll.
A student is awarded a grade based on the sections that he/she has enrolled for. Each section may have different grade types and it also stores how many times the student has taken an exam and has received a grade.
1
Introduction To RDBMS and SQL Module 3: Database Design Techniques
Overview This exercise will require participants to create an entity relationship diagram. Participants should identify the types of relationship between the tables, primary key and will link the two tables via a foreign key.
Instructions The entity relationship diagram should be created using Microsoft Word.
1. In order to proceed with the entity relationship, first identify the tables from the given data structure and define the relationship between them.
2. Naming conventions should be followed for creating the entity relationship as follows:
Symbols Element Name
Table Name
# Primary Key
* Not Null
Numeric Values
Varchar Values
Date Values
Hints 1. Ensure the following while designing the Entity Relationship diagram:
The symbols shown above should be placed before the column name. Each table should be placed in a rectangle with the specific symbol.
• <tableName> Each column should be placed with a specific symbol.
• # emp_id number primary key The tables should be identified with proper symbols for identifying the
Overview This exercise will require participants to create the tables in Oracle SQL PLUS using the SQL language.
Instructions The creation of the tables should be done in Oracle SQL PLUS.
1. In order to proceed with creating the tables, first create a new user in SYSTEM login and grant resource and connect permissions to that user.
2. Login using that user and then proceed to create the tables. Name the tables with <tablename>_INFO.
Hints 1. Ensure the following while creating the table:
Each table name should end with the word INFO. Create a notepad file and save the file in C:\RDBMS\Day2\Tables.sql. In the notepad file write the SQL syntax for creating the tables. Run the file in SQL Plus as @ c:\RDBMS\Day2\Tables.sql. After running the file give the command “SELECT * FROM TAB” to view the
tables created after executing Tables.sql.
5
Introduction To RDBMS and SQL Module 6: Data Definition Language
Overview This exercise will require participants to alter the tables in Oracle SQL PLUS using the SQL language.
Instructions The altering of the tables should be done in Oracle SQL PLUS.
1. In order to proceed with altering the tables, login using your user name created in Exercise 01 and then proceed to alter the tables.
Hints 1. Ensure the following while altering the table:
Create a notepad file and save the file in C:\RDBMS\Day2\AlterTables.sql. In the notepad file write the SQL syntax for creating the tables. Run the file in SQL Plus as @ c:\RDBMS\Day2\AlterTables.sql. After running the file give the command “SELECT * FROM TAB” to view the
tables created after executing Tables.sql.
8
Introduction To RDBMS and SQL Module 6: Data Definition Language
Overview This exercise will require participants to alter the tables in Oracle SQL PLUS using the SQL language.
Instructions Creating constraints on the tables should be done in Oracle SQL PLUS.
1. In order to proceed with creating constraints on the tables, login using your user name created in Exercise 01 and then proceed to create the constraints on the tables.
Hints 1. Ensure the following while creating the constraints on the table:
All the tables are created and end with the word INFO. Create a notepad file and save the file in C:\RDBMS\Day2\constraints.sql In the notepad file write the SQL syntax for creating the constraints. Run the file in SQL Plus as @ c:\RDBMS\Day2\constraints.sql
11
Introduction To RDBMS and SQL Module 7: Constraints
Overview This exercise will require participants to insert record in the tables in Oracle SQL PLUS using the SQL language.
Instructions Inserting records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with inserting records in the tables, login using your user name created in Exercise 01 and then proceed to create the constraints on the tables.
Hints 1. Ensure the following while inserting records in the table:
Execute the file C:\RDBMS\Day2\createSchema.sql.
14
Introduction To RDBMS and SQL Module 8: Data Manipulation Language
1) Display the structure of the course table. 2) Display the zipcode, city and state. Observe the column heading of state column. If not appearing correctly, give a proper heading. Save the SQL statement in the sql file. C:\RDBMS\Day2\zipquery.sql.
3) Run the zipquery.sql. 4) Display the unique states. 5) Display the student_id, name. Concatenate the first_name and last name. 6) Display the Zipcode, city and state as a single column. Separate the data with a comma. E.g 400050, Mumbai, MH. Give the column heading as Address.
7) Display the description of the course. 8) In the above query also display the cost. 9) Display all the columns of the course_info table. 10) Display the instructor's last name and the zip in which the instructor resides. 11) There are many students who are living in the area, display unique zip's only. 12) Write a select statement to list the first and last names of all students. 13) Write a select statement to list all cities, their states and zip codes.
SELECT using WHERE 1) Display the student_id, section_id and numeric_grade of those students who have the grade
code type as ‘FI’. 2) Display the Zipcode and cities for the state ‘MI’. 3) Display the student details that have enrolled in the month of Jan 1999. Sort the data in the
ascending order of student names. Note: Names should be concatenated. 4) Display the section and the instructor id of the course 10 and 20. Sort the data in the ascending
order of instructor id. 5) Display the student_id, section_id and numeric_grade. Sort the section_id in ascending order
followed by numeric_grade in descending order. 6) Display the course_no, description and cost of the courses. The courses should have the word
‘Intro’. 7) Display the course details whose third from last letter is ‘a’. 8) Display the student names whose student_id is in the range of 300 to 350. 9) Display the course details whose cost ranges from 4000 to 7000. 10) Write a select statement that displays the instructor's first name whose last name is 'Schumer'. 11) Write a select statement that displays the instructor's first name whose last name is not
'Schumer'. 12) Display the course name and cost of those courses whose cost is more than 4000. 13) Display the course name and cost of those courses whose cost is in the range of 3000 and 7000. 14) Display the course name and cost of those courses whose cost is 4000 and 4500. 15) Write a select statement that displays the student's first name and address whose last name
starts with 'S'. 16) Write a select statement that displays the student's first name and address whose last name
contains 'o' as the second letter.
17
Introduction To RDBMS and SQL Module 8: Data Manipulation Language
17) Write a select statement that displays the instructor's first name whose last name does not start with 'S'.
18) Display the course name and cost of those courses whose cost is in range of 4000 and 4500 and the course name starts with 'I'.
19) Display the course name and cost and prerequisite of those courses whose cost is 2000 and prerequisite is 20 and all courses whose prerequisite is 25.
20) Display the course name and cost and prerequisite of those courses whose cost is 2000 and all records whose prerequisite is 20 and 25.
21) Display the records of the course_info table which have no prerequisite. 22) Write a select statement to list the last names of students living either in zip code 10048, 11102
and 11209. 23) Write a select statement to list the first and last names of instructors with the letter 'i' in any case
in the last name and living in zip code 10025. 24) Write a select statement to list descriptions of courses which have prerequisites and cost is less
than 1100. 25) Write a select statement to list the cost of courses that do not a prerequisite. In the result the cost
should not be repeated. 26) Display the course_no and the coursename who do not a prerequisite. Sort the data on the basis
of coursename. 27) For the above query sort in the descending order of coursename. 28) Write a select statement to list each city in state New York or Connecticut sorted in ascending
order by zipcode. 29) Display the zip, first and last name of students with the last name Graham. Order the result by zip
in descending order and the first name in ascending order. 30) Display the city and state as 1 column. 31) Display the first name of the student. Only the first letter of the first name should be in
uppercase. 32) Write a select statement that displays the instructor's first name followed by comma and a space
which is followed by last_name. The result should be displayed in 1 result set. 33) Display the select statement that displays the cost, add 10 to cost, subtract 20 from cost, multiply
cost by 30 and divide cost by 5. 34) Write a select statement that displays unique numeric grade, half these values and do not
display this value in decimals. This calculation should be displayed as a separate column.
SELECT with TO_CHAR/DECODE/IS NULL
1) Display the cost in the following format for all the courses whose course_no is less than 25.
EX. 4,000
3,500
2) Write a query to format the cost column. The cost displayed should have a leading $ sign followed by a comma to separate the thousands and should display 2 decimals. E.g $2,000.00
3) For those courses having no pre-requisites display data as 'Not Applicable'
4) Display the state as 'New York' for NY, 'New Jersey' for NY and 'Others' for any other state.
18
Introduction To RDBMS and SQL Module 9: Aggregate Functions
Module 9 Activity 6.0: Aggregate functions against the table
Estimated Completion Time: 60 minutes
Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.
Instructions Querying records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to use the aggregate functions.
Hints 1. Ensure the following while creating the queries on the table:
Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\agg.sql append.
19
Introduction To RDBMS and SQL Module 9: Aggregate Functions
1) Display the count of records in the course table. 2) Display the total number of records in enrollment table. 3) Display sum of numeric_grade from grade_info. 4) Display the average, total, minimum and maximum numeric grade. 5) Display the count of grade code type. 6) Write a SELECT statement that displays the total number of courses which do not have any pre-requisite.
7) Display the date of the student who got recently enrolled.
Group by and Having Clause
1) Display the count of cities for each state. 2) Display the minimum numeric grade section wise for each student. 3) Display the average numeric grade for each student. 4) Display the count of students enrolled in each section. Display only those sections where the
number of students enrolled is more than 5. 5) Display the average numeric grade for each student and section. The average numeric grade
should be more than 75. 6) For the above query display the data for student_id more than 280. 7) Display each prerequisite and its count from the course_info table. 8) Display student_id and number of courses they are enrolled in. Those students who are enrolled
in more than 2 courses should be displayed. 9) Display the average capacity of each course. 10) For the above query display those courses which have exactly 2 sections.
20
Introduction To RDBMS and SQL Module 9: Union-Intersect-Minus
Module 9 Activity 6.1 – Union/Intersect/Minus functions against the table
Estimated Completion Time: 45 minutes
Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.
Instructions Querying records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to use the SET operators.
Hints 1. Ensure the following while creating the queries on the table:
Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\UnIntMin.sql append.
21
Introduction To RDBMS and SQL Module 9: Union-Intersect-Minus
Module 9 Activity 6.2: Subqueries against the table
Estimated Completion Time: 100 minutes
Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.
Instructions Querying records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the subqueries.
Hints 1. Ensure the following while creating the subqueries on the table:
Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\subqueries.sql append.
23
Introduction To RDBMS and SQL Module 9: Subqueries
1) Display the course_no, description and cost. Those records should be displayed whose cost is equal to the minimum cost.
2) Display the name of the students enrolled in section no 8 and course number 20.
3) Display the student id’s who registered first.
4) Display the course_no and sum of capacity where the total capacity is less than the average capacity.
Subqueries returning multiple rows
1) Display the course number and description whose cost is same as that of the course whose prerequisite is 20.
2) Modify the above query to display the records whose cost is not same as that of the course whose prerequisite is 20.
3) Display the course description and cost of the courses where the capacity is less than or equal to the average capacity and cost is equal to minimum cost.
4) Display the student id and section id who are living in zip 06820.
5) Display the course no and description taught by instructor Frank Hank.
6) Display the students enrolled in course 'Introduction to Java'.
7) Display the last_name and enrollment_date from student_info of those students who have enrolled on 22nd of Jan 2001.
8) Display the student names who have enrolled on Tuesday.
Co-related subqueries with exists
1) Display the student id and section id along with numeric grade of those students where the numeric grade is less than the average numeric grade for that section.
2) Display the instructor details only if the instructor teaches a section.
3) Display the details of those instructors who do not teach a section.
4) Display the names of the students who are enrolled.
5) Display the courses enrolled by the students.
6) Display the courses who do not have sections.
7) Display the sections in which no student is enrolled.
24
Introduction To RDBMS and SQL Module 9: Subqueries
Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.
Instructions Querying records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the joins on the tables.
Hints 1. Ensure the following while creating the joins on the table:
Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\joins.sql append.
1) Display the course and the section information.
2) Display the instructor details along with the city and the state that they live in.
3) Display the student details of all students and city and state. Sort the result on the basis of zip code.
4) Write a query to display the first and last names of only the enrolled students and order on the basis of last name in descending order.
5) Display the zip, city and state and instructor names who are living in state 'NY'.
6) Write a query to display the student number, course number, enrollment date and section id for students who are enrolled in course number 20 on January 30 2000.
7) Display the course number, description, cost, section id, and the instructor names who are teaching the course.
8) Display the student number, section id and grade type code along with numeric grade and the month of enroll date for student id =220 and section id =119.
9) Display the student id, course number and section number of enrolled students where the instructor of the section lives in zip code 10025. Also, the course should not have any pre-requisites.
10) Display the instructor details along with the city, state who are teaching the section 2.
11) Display the list of enrolled student numbers who are living in state 'CT'.
12) Write a query to display the details of student 'Fenny Crawford' for section id 86.
13) Display the final examination numeric grade and details of all enrolled students living in state 'NY' of course number 300.
14) Display the student number, section id, numeric grade and last name who received grade less than 75 or less in class project.
Outer Join
1) Display the course number, description and pre-requisite along with section id. Those courses who do not have sections defined should also be displayed.
2) For the above query also include courses where no instructor is assigned.
3) For students with id's 102 and 301 display the student id, section id and numeric grade and the grade type. Display the details even if the student is not enrolled or has not received any grade.
1) Many courses have pre-requisite. Display the course no and the description along with the pre-requisite and the description.
e.g. - 20 Intro to Java 10 Java Programming where 20 is the course no and 10 is the pre-requisite.
2) For the students who have enrolled in section id 86 find the students who have received a lower grade in their final examination than in their mid term. In the result set, display the student id, grade type code and numeric grade.
e.g. .studentid grade_type numeric_grade grade_type numeric_grade
100 FI 70 MI 75
3) Display the names of the students living at the same address and their zipcode.
Overview This exercise will require participants to query on the tables in Oracle SQL PLUS using the SQL language.
Instructions Querying records in tables should be done in Oracle SQL PLUS.
1. In order to proceed with querying records in the tables, login using your user name created in Exercise 01 and then proceed to create the views on the tables.
Hints 1. Ensure the following while creating the views on the table:
Execute the query in SQL PLUS. After each successful command save the command in the file. To save the file - C:\RDBMS\Day3\views.sql append.
1) Create a view named stud_enroll that displays student id, lastname and number of sections that the student is enrolled.
2) Create a view named stud_zip that has stduent_id, names of students (first and last name), city and state. In this view students not living in state New Jersey, New York and Connecticut should be displayed.
3) Create a view named lowcost_course that has the course number, course name and cost less than 4000.
4) Issue an insert command on this view and insert cost more than 4000 and check if the record gets inserted.
5) Modify the view to include the WITH CHECK OPTION and try inserting the record again.
6) Modify the above view in such a way that it should not allow you to perform any DML statement.