You are on page 1of 66

Experiment No.

Experiment No. 1 Title: Introduction to SQL

Experiment No.1

History SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL, was designed to manipulate and retrieve data stored in IBM's original relational database product, System R. During the 1970s, a group at IBM San Jose Research Laboratory developed the System R relational database management system. Donald D. Chamberlin and Raymond F. Boyce of IBM subsequently created the Structured English Query Language (SEQUEL or SEQL) to manage data stored in System R. The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company The first Relational Database Management System (RDBMS) was RDMS, developed at MIT in the early 1970s, soon followed by Ingres, developed in 1974 at U.C. Berkeley. Ingres implemented a query language known as QUEL, which was later supplanted in the marketplace by SQL. In the late 1970s, Relational Software, Inc. (now Oracle Corporation) saw the potential of the concepts described by Codd, Chamberlin, and Boyce and developed their own SQL-based RDBMS with aspirations of selling it to the U.S. Navy, Central Intelligence Agency, and other U.S. government agencies. In the summer of 1979, Relational Software, Inc. introduced the first commercially available implementation of SQL, Oracle V2 (Version2) for VAX computers. Oracle V2 beat IBM's release of the System/38 RDBMS to market by a few weeks. After testing SQL at customer test sites to determine the usefulness and practicality of the system, IBM began developing commercial products based on their System R prototype including System/38, SQL/DS, and DB2, which were commercially available in 1979, 1981, and 1983, respectively. Types of SQL Data definition language Data manipulation language

Experiment No.1

DATA DEFINITION LANGUAGE Data Definition Language (DDL) describes the portion of SQL that allows you to create, alter, and destroy database objects. These database objects include schemas, tables, views, sequences, catalogs, indexes, and aliases. The term was first introduced in relation to the Codasyl database model, where the schema of the database was written in a Data Definition Language describing the records, fields, and "sets" making up the user Data Model. Initially it referred to a subset of SQL, but is now used in a generic sense to refer to any formal language for describing data or information structures, like XML schemas. Following are the various DDL commands CREATE ALTER DROP CREATE To make a new database, table, index, or stored query. A CREATE statement in SQL creates an object inside of a relational database management system (RDBMS). The types of objects that can be created depends on which RDBMS is being used, but most support the creation of tables, indexes, users, synonyms and databases. Some systems (such as PostgreSQL) allow CREATE, and other DDL commands, inside of a transaction and thus they may be rolled back. DROP To destroy an existing database, table, index, or view. A DROP statement in SQL removes an object from a relational database management system (RDBMS). The types of objects that can be dropped depends on which RDBMS is being used, but most support the dropping of tables, users, and databases. Some systems (such as PostgreSQL) allow DROP and other DDL commands to occur inside of a transaction and thus be rolled back.
3

Experiment No.1

ALTER To modify an existing database object. An ALTER statement in SQL changes the properties of an object inside of a relational database management system (RDBMS). The types of objects that can be altered depend on which RDBMS is being used. DATA M ANIPULATION LANGUAGE The Data Manipulation Language (DML) is used to retrieve, insert and modify database information. These commands will be used by all database users during the routine operation of the database. Data Manipulation Language comprises the 'SQL-data change' statements which modify stored data but not the schema or database objects. Manipulation of persistent database objects (e.g. tables or stored procedures) via the 'SQL-schema' statements, rather than the data stored within them, is considered to be part of a separate Data Definition Language. In SQL these two categories are similar in their detailed syntax, data types, expressions etc., but distinct in their overall function. Following are the various DDL commands SELECT INSERT UPDATE DELETE

SELECT The SQL SELECT statement returns a result set of records from one or more tables. It retrieves zero or more rows from one or more base tables, temporary tables, or views in a database. In most applications, SELECT is the most commonly used Data Manipulation Language (DML) command. As SQL is a non-procedural language, SELECT queries specify a result set, but do not specify how to calculate it: translating the query into an executable "query plan" is left to the database system, more specifically to the query optimizer.
4

Experiment No.1

The SELECT statement has many optional clauses: WHERE specifies which rows to retrieve. GROUP BY groups rows sharing a property so that an aggregate function can be applied to each group. HAVING selects among the groups defined by the GROUP BY clause. ORDER BY specifies an order in which to return the rows. INSERT An SQL INSERT statement adds one or more records to any single table in a relational database. UPDATE A SQL UPDATE statement that changes the data of one or more records in a table, either all the rows can be updated, or a subset may be chosen using a condition. DELETE In the database structured query language (SQL), the DELETE statement removes one or more records from a table. A subset may be defined for deletion using a condition, otherwise all records are removed.

Experiment No.2

Experiment No. 2 Title: Use of SQL for Creation & Modification of Table

Experiment No.2 Table name: Client_Master COLUMN NAME Client_no Name Address City State Pin code Remark SQL to create the table SQL>Create table Client_Master (Client_no varchar2(20), Name varchar2(20), Address varchar2(30), City varchar2(10), State varchar2(15), Pincode number (6), Remark varchar2(30)); Output: Table created DATA TYPE Varchar2 Varchar2 Varchar2 Varchar2 Varchar2 Varchar2 Varchar2 SIZE 6 6 30 10 15 6 30

Experiment No.2 SQL to describe the table SQL>describe Client_Master; Output: NAME CLIENT_NO NAME ADDRESS CITY STATE PINCODE REMARK Table Name: Product_Master NULL? DATA TYPE VARCHAR2(20) VARCHAR2(20) VARCHAR2(30) VARCHAR2(10) VARCHAR2(15) NUMBER(6) VARCHAR2(30)

COLUMN NAME Product_no Description Profit_percent Unit_measure Quantity_on_hand Reorder Sale_price Cost_price

DATA TYPE Number Varchar2 Number Varchar2 Varchar2 Varchar2 Number Number

SIZE 6 30 3 20 30 30 6 6

SQL to create the table SQL>create table Product_Master (Product_no number(6), Description varchar2 (30), Prtfit_percent number(3), Unit_measure varchar2 (20), Quality_on_hand varchar2 (30),
8

Experiment No.2 Reorder varchar2 (30), Sale_price number(6), Cost_price number (6)); Output: Table created SQL to describe the table SQL>describe Product_Master; Output: NAME PRODUCT_NO DESCRIPTION PRTFIT_PERCENT UNIT_MEASURE QUALITY_ON_HAND REORDER SALE_PRICE COST_PRICE SQL to alter the table alter table client_Master Add(country varchar2(10)); Output: Table altered. SQL to rename the table Rename product_Master to product_Masterr; Output: Table renamed. NULL? TYPE NUMBER(6) VARCHAR2(30) NUMBER(3) VARCHAR2(20) VARCHAR2(30) VARCHAR2(30) NUMBER(6) NUMBER(6)

Experiment No.3

Experiment No. 3 Title: Use of SQL with Creation of Table with Constraints

10

Experiment No.3

The basic syntax for a CREATE TABLE statement is: CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... ); Each column must have a data type. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default. For example: CREATE TABLE suppliers ( supplier_id number(10) supplier_name contact_name ); Practice Exercise #1: Create a customers table that stores customer ID, name, and address information. The customer ID should be the primary key for the table. Solution: The CREATE TABLE statement for the customers table is: CREATE TABLE customers ( customer_id customer_name address city number(10) varchar2(50) varchar2(50), not null, not null, not null, not null, varchar2(50) varchar2(50)

varchar2(50), varchar2(10),

state varchar2(25), zip_code ); CONSTRAINT customers_pk PRIMARY KEY (customer_id)

11

Experiment No.3

Practice Exercise #2: Based on the departments table below, create an employees table that stores employee number, employee name, department, and salary information. The primary key for the employees table should be the employee number. Create a foreign key on the employees table that references the departments table based on the department_id field. CREATE TABLE departments ( department_id department_name ); Solution: The CREATE TABLE statement for the employees table is: CREATE TABLE employees ( employee_number employee_name department_id salary number(10) varchar2(50) number(10), not null, not null, number(10) not null, not null, varchar2(50)

CONSTRAINT departments_pk PRIMARY KEY (department_id)

number(6),

CONSTRAINT employees_pk PRIMARY KEY (employee_number), CONSTRAINT fk_departments FOREIGN KEY (department_id) REFERENCES departments(department_id) );

12

Experiment No.3

Practice Exercise #3: Create a courses table that stores code, description, category, duration with code value must be in upper case. Solution: The CREATE TABLE statement for the courses table is: create table courses (code category duration constraint ); VARCHAR2(6) constraint C_PK CHAR(3) NUMBER(2) constraint C_TYPE_NN constraint C_DUR_NN check primary key, not null, not null, (category in not null, (code = upper(code)), description VARCHAR2(30) constraint C_DESC_NN

constraint C_CODE_CHK check C_TYPE_CHK ('GEN','BLD','DSG'))

13

Experiment No.4

Experiment No. 4 Title: Use of SQL for Inserting the Data in Table

14

Experiment No.4

Practice Exercise #1: Create an employee table that stores ID, First name, Last name, start date, end date, salary, city, description of the employee Solution: The CREATE TABLE statement for the customers table is: create table Employee( ID First_Name Last_Name Start_Date End_Date Salary City Description ); VARCHAR2(4) , VARCHAR2(10), VARCHAR2(10), DATE, DATE, Number(8,2), VARCHAR2(10), VARCHAR2(15)

Syntax to insert values in above table insert into Employee values ('01','Jason','Martin',to_date('19960725','YYYYMMDD'),to_date('20060725', 'YYYYMMDD'),1234.56,'Toronto','Programmer'); insert into Employee values ('02','Alison', 'Mathews', to_date('19760321','YYYYMMDD'), to_date('19860221','YYYYMMDD'), 6661.78, 'Vancouver','Tester'); insert into Employee values ('03','James', 'Smith', to_date('19781212','YYYYMMDD'), to_date('19900315','YYYYMMDD'), 6544.78, 'Vancouver','Tester');

15

Experiment No.4

insert into Employee values ('04','Celia', 'Rice', to_date('19821024','YYYYMMDD'), to_date('19990421','YYYYMMDD'), 2344.78, 'Vancouver','Manager'); insert into Employee values ('05','Robert', 'Black', to_date('19840115','YYYYMMDD'), to_date('19980808','YYYYMMDD'), 2334.78, 'Vancouver','Tester'); insert into Employee values ('06','Linda', 'Green', to_date('19870730','YYYYMMDD'), to_date('19960104','YYYYMMDD'), 4322.78,'New York', 'Tester'); insert into Employee values ('07','David', 'Larry', to_date('19901231','YYYYMMDD'), to_date('19980212','YYYYMMDD'), 7897.78,'New York', 'Manager'); insert into Employee values ('08','James', 'Cat', to_date('19960917','YYYYMMDD'), to_date('20020415','YYYYMMDD'), 1232.78,'Vancouver', 'Tester'); Syntax to access the data in the table select * from Employee;
ID FIRST_NAME 01 Jason 02 Alison 03 James 04 Celia 05 Robert 06 Linda 07 David 08 James 8 rows selected. LAST_NAME START_DAT END_DATE Martin Mathews Smith Rice Black Green Larry Cat 25-JUL-96 25-JUL-06 21-MAR-76 21-FEB-86 12-DEC-78 15-MAR-90 24-OCT-82 21-APR-99 15-JAN-84 08-AUG-98 30-JUL-87 04-JAN-96 31-DEC-90 12-FEB-98 17-SEP-96 15-APR-02 SALARY CITY DESCRIPTION Programmer

---- -------------------- -------------------- --------- --------- ---------- ---------- --------------1234.56 Toronto 6661.78 Vancouver Tester 6544.78 Vancouver Tester 2334.78 Vancouver Tester 4322.78 New York Tester 7897.78 New York Manager 1232.78 Vancouver Tester

2344.78 Vancouver Manager

16

Experiment No.5

Experiment No. 5 Title: Study of ER (Entity Relationship) Model

17

Experiment No.5

Introduction The entity-relationship model (or ER model) is a graphical way of representing the logical relationships of entities (or objects) in order to create a database. Creation of an ER diagram is one of the first steps in designing a database. It consist of Entity / Entities Attributes of Entity / Entities Relationship /Relationships between various entities Entity / Entities An entity is defined as any real world object which has its own distinct existence and can be uniquely identified. A single entity may have several properties related to it. Number of entities having same properties can be grouped together to form an entity set. Example: Student is an entity which has various properties like Name, Roll Number, Year, Branch etc. Number of students can be grouped together to form a single entity set (Students) which will have same properties as like entity ( Student). Attributes of Entity / Entities Properties of entity are known as attribute. Following are the various types of attributes. Simple and composite attribute Single valued and multi-valued attribute Stored and derived attribute Null attribute Relationship A relationship is an association between several entities. A relationship set is a set of relationships of the same type. A relationship may also have descriptive attributes. There are several type of relationship based on the type, degree, cardinality and participation.

18

Experiment No.5

Various ER Notations

Strong Entity Set

Weak Entity Set

Relationship Set

Identifying relationship set for weak entity set

Attribute

Multi-valued attribute

Derived Attribute

Partial Participation of Entity set E in relationship set R

Total Participation of Entity set E in relationship set R

19

Experiment No.5

One to One relationship

Many to One relationship

One to Many relationship

Many to Many relationship

20

Experiment No.5

Examples of ER Diagram 1. Construct an ER diagram for a car insurance company that has a set of customers each of whom owns one or more car. Each car has associated with it zero to any number of recorded accidents. Reduce ER diagram to table

2. Construct an E-R diagram for a hospital with a set of patients and a set of medical doctors. Associate with each patient a log of the various tests and examinations conducted.

21

Experiment No.5

3. A university registrars office maintains data about the following entities: 4. Courses, including number, title, credits, syllabus, and prerequisites; 5. Course offerings, including course number, year, semester, section number, instructor(s), timings, and classroom; (c) students, including student-id, name, and program; 6. Instructors, including identification number, name, department, and title. 7. Further, the enrollment of students in courses and grades awarded to students in each course they are enrolled for must be appropriately modeled. Construct an E-R diagram for the registrars office. Document all assumptions that you make about the mapping constraints.

22

Experiment No.6

Experiment No. 6 Title: Use of SQL for Single Table Retrieval

23

Experiment No.6

Syntax to access the data in the table Employee;


ID 01 02 03 04 05 06 07 08 FIRST_NAM E Jason Alison James Celia Robert Linda David James LAST_NAM E Martin Mathews Smith Rice Black Green Larry Cat START_ DATE 25-JUL-96 21-MAR-76 12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 17-S EP-96 END_DATE 25-JUL-06 21-FEB-86 15-MAR-90 21-APR-99 08-AUG-98 04-JAN-96 12-FEB-98 15-APR-02 SALARY 1234.56 6661.78 6544.78 2344.78 2334.78 4322.78 7897.78 1232.78 CITY Toronto Vancouver Vancouver Vancouver Vancouver New York New York Vancouver DESCRIPTION Programmer Tester Tester Manager Tester Tester Manager Tester

1. Find Out the First_Name Of Employee whose Last Name is Black select First_Name,Start_Date,End_Date,city from employee where Last_Name='Black'; Output FIRST_NAME START_DAT END_DATE CITY ---------- --------- --------- ---------Robert 15-JAN-84 08-AUG-98 Vancouver

2. Find Out the First Name of alphabet start with 'J' Select First_Name,start_Date,Start_Date,End_Date,city from employee where First_Name='James'; Output FIRST_NAME START_DAT START_DAT END_DATE CITY ---------- --------- --------- --------- ---------James James 12-DEC-78 12-DEC-78 15-MAR-90 Vancouver 17-SEP-96 17-SEP-96 15-APR-02 Vancouver

3. Find out the First_Name of the Emplyee who belongs to city Vancouver Select City,Start_Date,End_Date from employee where city='Vancouver';

24

Experiment No.6

Output CITY START_DAT END_DATE ---------- --------- --------Vancouver 21-MAR-76 21-FEB-86 Vancouver 12-DEC-78 15-MAR-90 Vancouver 24-OCT-82 21-APR-99 Vancouver 15-JAN-84 08-AUG-98 Vancouver 17-SEP-96 15-APR-02 4. Find out Tester from the Employee Select Start_Date,End_Date from employee where description='Tester'; Output START_DAT END_DATE --------- --------21-MAR-76 21-FEB-86 12-DEC-78 15-MAR-90 15-JAN-84 08-AUG-98 30-JUL-87 04-JAN-96 17-SEP-96 15-APR-02 5. Find Out the Employee whose salary is 4322.78 select First_Name,Last_Name,End_Date,city from employee where salary>'4000'; Output FIRST_NAME LAST_NAME END_DATE CITY ---------- ---------- --------- ---------Alison James Linda David Mathews Smith Green Larry 21-FEB-86 Vancouver 15-MAR-90 Vancouver 04-JAN-96 New York 12-FEB-98 New York

25

Experiment No.7

Experiment No. 7 Title: Use of SQL for Set Function and Data

26

Experiment No.7

There are situations when there is a need to combine the results from two or more SELECT statements. SQL enables us to handle these requirements by using set operations. The result of each SELECT statement can be treated as a set, and SQL set operations can be applied on those sets to arrive at a final result. Oracle SQL supports the following four set operations: * UNION ALL * UNION * MINUS * INTERSECT SQL statements containing these set operators are referred to as compound queries, and each SELECT statement in a compound query is referred to as a component query. Two SELECTs can be combined into a compound query by a set operation only if they satisfy the following two conditions: 1. The result sets of both the queries must have the same number of columns. 2. The data type of each column in the second result set must match the data type of its corresponding column in the first result set. TIP: The data types do not need to be the same if those in the second result set can be automatically converted by Oracle (using implicit casting) to types compatible with those in the first result set. These conditions are also referred to as union compatibility conditions. The term union compatibility is used even though these conditions apply to other set operations as well. Set operations are often called vertical joins, because the result combines data from two or more SELECTS based on columns instead of rows. The keywords UNION, UNION ALL, MINUS, and INTERSECT are set operators. We can have more than two component queries in a composite query; we will always use one less set operator than the number of component queries.

27

Experiment No.7

The following sections discuss syntax, examples, rules, and restrictions for the four set operations. Set Operators The following list briefly describes the four set operations supported by Oracle SQL: UNION ALL Combines the results of two SELECT statements into one result set. UNION Combines the results of two SELECT statements into one result set, and then eliminates any duplicate rows from that result set. MINUS Takes the result set of one SELECT statement, and removes those rows that are also returned by a second SELECT statement. INTERSECT Returns only those rows that are returned by each of two SELECT statements. Before moving on to the details on these set operators, let's look at the following two queries, which we'll use as component queries in our subsequent examples. The first query retrieves all the customers in region SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5; CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries The second query retrieves all the customers with the sales representative is 'MARTIN'.

28

Experiment No.7

SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN'); CUST_NBR NAME ---------- -----------------------------4 Flowtech Inc. 8 Zantech Inc. If we look at the results returned by these two queries, we will notice that there is one common row (for Flowtech Inc.). The following sections discuss the effects of the various set operations between these two result sets. UNION ALL The UNION ALL operator merges the result sets of two component queries. This operation returns rows retrieved by either of the component queries. The following example illustrates the UNION ALL operation: SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 UNION ALL SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

29

Experiment No.7

CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 4 Flowtech Inc. 8 Zantech Inc. 7 rows selected. As we can see from the result set, there is one customer, which is retrieved by both the SELECTs, and therefore appears twice in the result set. The UNION ALL operator simply merges the output of its component queries, without caring about any duplicates in the final result set. UNION The UNION operator returns all distinct rows retrieved by two component queries. The UNION operation eliminates duplicates while merging rows retrieved by either of the component queries. The following example illustrates the UNION operation: SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 UNION SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN');

30

Experiment No.7

CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 4 Flowtech Inc. 5 Gentech Industries 8 Zantech Inc. 6 rows selected. This query is a modification of the previous query; the keywords UNION ALL have been replaced with UNION. Notice that the result set contains only distinct rows (no duplicates). To eliminate duplicate rows, a UNION operation needs to do some extra tasks as compared to the UNION ALL operation. These extra tasks include sorting and filtering the result set. If we observe carefully, we will notice that the result set of the UNION ALL operation is not sorted, whereas the result set of the UNION operation is sorted. These extra tasks introduce a performance overhead to the UNION operation. A query involving UNION will take extra time compared to the same query with UNION ALL, even if there are no duplicates to remove. Therefore, unless we have a valid need to retrieve only distinct rows, we should use UNION ALL instead of UNION for better performance. INTERSECT INTERSECT returns only the rows retrieved by both component queries. Compare this with UNION, which returns the rows retrieved by any of the component queries. If UNION acts like 'OR, then INTERSECT acts like 'AND'. For example: SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 INTERSECT SELECT C.CUST_NBR, C.NAME
31

Experiment No.7

FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN'); CUST_NBR NAME ---------- -----------------------------4 Flowtech Inc. As we saw earlier, "Flowtech Inc." was the only customer retrieved by both SELECT statements. Therefore, the INTERSECT operator returns just that one row. MINUS MINUS returns all rows from the first SELECT that are not also returned by the second SELECT. For example: SELECT CUST_NBR, NAME FROM CUSTOMER WHERE REGION_ID = 5 MINUS SELECT C.CUST_NBR, C.NAME FROM CUSTOMER C WHERE C.CUST_NBR IN (SELECT O.CUST_NBR FROM CUST_ORDER O, EMPLOYEE E WHERE O.SALES_EMP_ID = E.EMP_ID AND E.LNAME = 'MARTIN'); CUST_NBR NAME ---------- -----------------------------1 Cooper Industries 2 Emblazon Corp. 3 Ditech Corp. 5 Gentech Industries

32

Experiment No.7

Using Set Operations to Compare Two Tables Developers, and even DBAs, occasionally need to compare the contents of two tables to determine whether the tables contain the same data. The need to do this is especially common in test environments, as developers may want to compare a set of data generated by a program under test with a set of "known good" data. Comparison of tables is also useful for automated testing purposes, when we have to compare actual results with a given set of expected results. SQL's set operations provide an interesting solution to this problem of comparing two tables. The following query uses both MINUS and UNION ALL to compare two tables for equality. The query depends on each table having either a primary key or at least one unique index. (SELECT * FROM CUSTOMER_KNOWN_GOOD MINUS SELECT * FROM CUSTOMER_TEST) UNION ALL (SELECT * FROM CUSTOMER_TEST MINUS SELECT * FROM CUSTOMER_KNOWN_GOOD); We can look at it as the union of two compound queries. The parentheses ensure that both MINUS operations take place first before the UNION ALL operation is performed. The result of the first MINUS query will be those rows in CUSTOMER_KNOWN_GOOD that are not also in CUSTOMER_TEST. The result of the second MINUS que ry will be those rows in CUSTOMER_TEST that are not also in CUSTOMER_KNOWN_GOOD. The UNION ALL operator simply combines these two result sets for convenience. If no rows are returned by this query, then we know that both tables have identical rows. Any rows returned by this query represent differences between the CUSTOMER_TEST and CUSTOMER_KNOWN_GOOD tables.

33

Experiment No.8

Experiment No. 8 Title: Use of SQL for Indexing and Group by Clause

34

Experiment No.8

The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns. Aggregate function are the functions which requires one or more than one value as an input as returns only one output. such as SUM, COUNT, MIN, MAX, AVG etc The syntax for the GROUP BY clause is: SELECT column1, column2, ... column_n, aggregate_function (expression) FROM tables WHERE predicates GROUP BY column1, column2, ... column_n; Example using the SUM function SELECT department, SUM(sales) as "Total sales" FROM order_details GROUP BY department; Example using the COUNT function SELECT department, COUNT(*) as "Number of employees" FROM employees WHERE salary > 25000 GROUP BY department; Example using the MIN function SELECT department, MIN(salary) as "Lowest salary" FROM employees GROUP BY department; Example using the MAX function SELECT department, MAX(salary) as "Highest salary" FROM employees GROUP BY department; Example using the AVG function SELECT department, AVG(salary) as "Average of salary" FROM employees GROUP BY department;

35

Experiment No.8

What is an Index? An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. The syntax for creating a index is: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; UNIQUE indicates that the combination of values in the indexed columns must be unique. COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index. The statistics are then used by the optimizer to choose a "plan of execution" when SQL statements are executed. For example: CREATE INDEX supplier_idx ON supplier (supplier_name); In this example, we've created an index on the supplier table called supplier_idx. It consists of only one field - the supplier_name field. We could also create an index with more than one field as in the example below: CREATE INDEX supplier_idx ON supplier (supplier_name, city); We could also choose to collect statistics upon creation of the index as follows: CREATE INDEX supplier_idx ON supplier (supplier_name, city) COMPUTE STATISTICS;

36

Experiment No.8

Create a Function-Based Index In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes. The syntax for creating a function-based index is: CREATE [UNIQUE] INDEX index_name ON table_name (function1, function2, . function_n) [ COMPUTE STATISTICS ]; For example: CREATE INDEX supplier_idx ON supplier (UPPER(supplier_name)); In this example, we've created an index based on the uppercase evaluation of the supplier_name field. However, to be sure that the Oracle optimizer uses this index when executing your SQL statements, be sure that UPPER(supplier_name) does not evaluate to a NULL value. To ensure this, add UPPER(supplier_name) IS NOT NULL to your WHERE clause as follows: SELECT supplier_id, supplier_name, UPPER(supplier_name) FROM supplier WHERE UPPER(supplier_name) IS NOT NULL ORDER BY UPPER(supplier_name); Rename an Index The syntax for renaming an index is: ALTER INDEX index_name RENAME TO new_index_name; For example: ALTER INDEX supplier_idx RENAME TO supplier_index_name; In this example, we're renaming the index called supplier_idx to supplier_index_name.
37

Experiment No.8

Collect Statistics on an Index If one forgot to collect statistics on the index when he has first created it or he want to update the statistics, you can always use the ALTER INDEX command to collect statistics at a later date. The syntax for collecting statistics on an index is: ALTER INDEX index_name REBUILD COMPUTE STATISTICS; For example: ALTER INDEX supplier_idx REBUILD COMPUTE STATISTICS; In this example, we're collecting statistics for the index called supplier_idx. Drop an Index The syntax for dropping an index is: DROP INDEX index_name; For example: DROP INDEX supplier_idx; In this example, we're dropping an index called supplier_idx.

38

Experiment No.9

Experiment No. 9 Title: Use of SQL for Joining and Co-Relation

39

Experiment No.9

A join is used to combine rows from multiple tables. A join is performed whenever two or more tables is listed in the FROM clause of an SQL statement. There are different kinds of joins. Let's take a look at a few examples. Inner Join (simple join) It is the most common type of join. Inner joins return all rows from multiple tables where the join condition is met. For example, SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers, orders WHERE suppliers.supplier_id = orders.supplier_id; This SQL statement would return all rows from the suppliers and orders tables where there is a matching supplier_id value in both the suppliers and orders tables. How inner joins work: We have a table called suppliers with two fields (supplier_id and supplier_ name). It contains the following data: supplier_id supplier_name 10000 10001 10002 10003 IBM Hewlett Packard Microsoft NVIDIA

40

Experiment No.9

We have another table called orders with three fields (order_id, supplier_id, and order_date). It contains the following data: order_id supplier_id order_date 500125 10000 500126 10001 2003/05/12 2003/05/13

If we run the SQL statement below: SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers, orders WHERE suppliers.supplier_id = orders.supplier_id; Our result set would look like this: supplier_id 10000 10001 name IBM order_date 2003/05/12

Hewlett Packard 2003/05/13

The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the supplier_id's 10002 and 10003 do not exist in both tables. Outer Join Another type of join is called an outer join. This type of join returns all rows from one table and only those rows from a secondary table where the joined fields are equal (join condition is met). For example, select suppliers.supplier_id, suppliers.supplier_name, orders.order_date from suppliers, orders where suppliers.supplier_id = orders.supplier_id(+); This SQL statement would return all rows from the suppliers table and only those rows from the orders table where the joined fields are equal.

41

Experiment No.9

The (+) after the orders.supplier_id field indicates that, if a supplier_id value in the suppliers table does not exist in the orders table, all fields in the orders table will display as <null> in the result set. The above SQL statement could also be written as follows: select suppliers.supplier_id, suppliers.supplier_name, orders.order_date from suppliers, orders where orders.supplier_id(+) = suppliers.supplier_id Let's look at some data to explain how outer joins work: We have a table called suppliers with two fields (supplier_id and name). It contains the following data: supplier_id supplier_name 10000 10001 10002 10003 IBM Hewlett Packard Microsoft NVIDIA

We have a second table called orders with three fields (order_id, supplier_id, and order_date). It contains the following data: order_id supplier_id order_date 500125 10000 500126 10001 2003/05/12 2003/05/13

If we run the SQL statement below: select suppliers.supplier_id, suppliers.supplier_name, orders.order_date from suppliers, orders where suppliers.supplier_id = orders.supplier_id(+);

42

Experiment No.9

Our result set would look like this: supplier_id 10000 10001 10002 10003 supplier_name IBM Hewlett Packard Microsoft NVIDIA order_date 2003/05/12 2003/05/13 <null> <null>

The rows for Microsoft and NVIDIA would be included because an outer join was used. However, you will notice that the order_date field for those records contains a <null> value.

43

Experiment No.10

Experiment No. 10 Title: Use of SQL for Nested Queries

44

Experiment No.10

What is a subquery? A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause. WHERE clause Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries. For example: select * from all_tables tabs where tabs.table_name in (select cols.table_name from all_tab_columns cols where cols.column_name = 'SUPPLIER_ID'); Limitations: Oracle allows up to 255 levels of subqueries in the WHERE clause. FROM clause A subquery can also be found in the FROM clause. These are called inline views. For example: select suppliers.name, subquery1.total_amt from suppliers, (select supplier_id, Sum(orders.amount) as total_amt from orders group by supplier_id) subquery1, where subquery1.supplier_id = suppliers.supplier_id; In this example, we've created a subquery in the FROM clause as follows: (select supplier_id, Sum(orders.amount) as total_amt from orders group by supplier_id) subquery1

45

Experiment No.10

This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields. Limitations: Oracle allows an unlimited number of subqueries in the FROM clause. SELECT clause A subquery can also be found in the SELECT clause. For example: select tbls.owner, tbls.table_name, (select count(column_name) as total_columns from all_tab_columns cols where cols.owner = tbls.owner and cols.table_name = tbls.table_name) subquery2 from all_tables tbls; In this example, we've created a subquery in the SELECT clause as follows: (select count(column_name) as total_columns from all_tab_columns cols where cols.owner = tbls.owner and cols.table_name = tbls.table_name) subquery2 The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields. The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such as SUM, COUNT, MIN, or MAX is commonly used in the subquery. Limitations: Oracle allows up to 255 levels of subqueries in the WHERE clause.

46

Experiment No.11

Experiment No. 11 Title: Use of SQL table for Updation

47

Experiment No.11

The UPDATE statement allows us to update a single record or multiple records in a table. The syntax for the UPDATE statement is: UPDATE table SET column = expression WHERE predicates; Example #1 - Simple example UPDATE suppliers SET name = 'HP' WHERE name = 'IBM'; This statement would update all supplier names in the suppliers table from IBM to HP. Example #2 - More complex example User may wish to update records in one table based on values in another table. Since user can't list more than one table in the UPDATE statement, EXISTS clause can be used. For example: UPDATE suppliers SET ( SELECT customers.name WHERE customers.customer_id = suppliers.supplier_id) WHERE EXISTS ( SELECT customers.name FROM customers WHERE customers.customer_id = suppliers.supplier_id); Whenever a supplier_id matched a customer_id value, the supplier_name would be overwritten to the customer name from the customers table. supplier_name = FROM customers

48

Experiment No.11

Practice Exercise #1: Based on the suppliers table populated with the following data, update the city to "Santa Clara" for all records whose supplier_name is "NVIDIA". CREATE TABLE suppliers ( supplier_id supplier_name city number(10) varchar2(50) varchar2(50), not null, not null,

CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id) ); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5001, 'Microsoft', 'New York'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5002, 'IBM', 'Chicago'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5003, 'Red Hat', 'Detroit'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5004, 'NVIDIA', 'New York'); Solution: The following SQL statement would perform this update. UPDATE suppliers SET city = 'Santa Clara' WHERE supplier_name = 'NVIDIA'; The suppliers table would now look like this: SUPPLIER_ID SUPPLIER_NAME 5001 5002 5003 5004 Microsoft IBM Red Hat NVIDIA CITY New York Chicago Detroit Santa Clara

49

Experiment No.11

Practice Exercise #2: Based on the suppliers and customers table populated with the following data, update the city in the suppliers table with the city in the customers table when the supplier_name in the suppliers table matches the customer_name in the customers table. CREATE TABLE suppliers ( supplier_id supplier_name city number(10) varchar2(50) varchar2(50), not null, not null,

CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id) ); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5001, 'Microsoft', 'New York'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5002, 'IBM', 'Chicago'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5003, 'Red Hat', 'Detroit'); INSERT INTO suppliers (supplier_id, supplier_name, city) VALUES (5005, 'NVIDIA', 'LA'); CREATE TABLE customers ( customer_id customer_name city number(10) varchar2(50) varchar2(50), not null, not null,

CONSTRAINT customers_pk PRIMARY KEY (customer_id) ); INSERT INTO customers (customer_id, customer_name, city) VALUES (7001, 'Microsoft', 'San Francisco');
50

Experiment No.11

INSERT INTO customers (customer_id, customer_name, city) VALUES (7002, 'IBM', 'Toronto'); INSERT INTO customers (customer_id, customer_name, city) VALUES (7003, 'Red Hat', 'Newark'); Solution: The following SQL statement would perform this update. UPDATE suppliers SET city = ( SELECT customers.city FROM customers WHERE customers.customer_name = suppliers.supplier_name) WHERE EXISTS ( SELECT customers.city FROM customers WHERE customers.customer_name = suppliers.supplier_name); The suppliers table would now look like this: SUPPLIER_ID SUPPLIER_NAME 5001 5002 5003 5004 Microsoft IBM Red Hat NVIDIA CITY San Francisco Toronto Newark LA

51

Experiment No.12

Experiment No. 12 Title: To Study OSI Reference Model

52

Experiment No.12

The OSI model is as shown in the figure. This model is based on International standard organization of protocols used in various layers. The model is called ISD OSI (open system inter connection) reference model because it deals with other system. It is usually called OSI model. The OSI has 7 layers: 1. 2. 3. 4. The layer should be related where different level of obstruction is Each layer should perform well defined function with an eye The function of each layer should be chosen with an eye towards The layer boundaries should be large enough that distinct function needed. towards defining internationally standard protocol. defining internationally standard protocol. used not to be prone together in same layer but of necessity and small enough that architecture does not become unavoidably layer of model in

53

Experiment No.12

term is discussed starting at bottom layer. OSI model itself is not network architecture. Physical Layer: The physical layer is connected with transmitting raw hits over a communication channel. The design issues have to be with making sure that when one side sends a bit, it is received by other side as 1 bit and not as 0 bit. Typical questions here are how many values should be used to represent Network Layer: A network layer is connected with controlling the operations of subnet. A key design issue is determining how packets are received from source to destination. Receiver can be based on statue tables that are wired into live network and rarely changed. They can also determine at start of each conversion. Eg Terminal session finally they can highly dynamic being determined a new for each packet to connect a network pad. The control of such congestion also belongs to network layer. Since operation of subnet may expect remuneration for their efforts. There is often some accounting functions built into network layer. At least software must count how many packets or character or bits are sent by each costumer to produce billing information. When packet has to travel from 1 network to another target its destination, many questions, and many problems can arise. The addressing used by 2nd network may be different from 1st one. The 2nd one may not accept packet at all because its too large. The protocol may differ so on. In broadcast network receiving problem is simple, so a ne twork layer is often thin as even as existence. Transport Layer: A basic function of transport layer is to accept data from session layer, split into smaller units, if needed be pass there to network layer; and
54

a1 and a0. How many micro seconds a bit lasts

simultaneously in both directions.

Experiment No.12

further mere all these must how initial connection is established and how it is turned down when both sides are finished. And how many pins network issues here largely deal with mechanical, electrical and procedural interfaces and physical transmission medium which lies below physical layer. Data Link Layer: The main test of data link layer is to take new transmitter facility and transform it into a live that appears a free of un actuated transmission error to network layers. This accomplishes this task by having sender break. The input data up to data frame transmit the frames sequentially and process acknowledgement frame sent back by receivers. Since physical layer merely accepts and transmits a stream of bits without any regards to meaning or structure. A line burst on the line can de stroy a frame completely. In this case, the data link layer software on source machine can retransmit the frame introduced the possibility of duplicate frames. A duplicate frame could be sent in acknowledgement frame from receives back to sender when lost. Another issue that arrive data link layer is to keep a fast transmitter from drawing slow receiver in data. Some traffic regulations mechanism must imply to let transmitted to know how much buffer space the receiver has moment. If the line can be used to transmit data in both direction this introduces new complications that the data link layer software must deal with problem is that acknowledgement frames from A and B traffic le vel solution has been revised be done effectively. Under the normal condition the transport layer creates a distinct network connection for transport connection required by session layer. Its transport connections require high trough put however transport layer might create multiple network connections, dividing the data among network connection to improve throughout, on other hand expensive transport layer might multiple several transport connection of to reduce cost.

55

Experiment No.12

The transport layer also determines what type service to provide session layer and ultimately uses of network the most popular type of transport connection in an error tree point to point channel that delivers message or bytes in order in which they uses sent however other possible kinds of isolated message with no guarantee about order of delivery of broadcasting message to multiple destination. Session Layer: The session layer aloe user a different machine to unestablished session between them session allow ordinary data transport layer but it also provides enhanced services useful in some applications. A session might be used to allow a user to log into remote time. A related session services is taken management for some protocols it is essential that both sides do not attempt same operation at sometime. To message these activities session Application layer: This layer contains variety of protocol that is commonly needed. There are hundreds of compatible terminal types in world. Consider left of full screen editor that is supposed to work over a network with many difficult terminal types. On nearly to solve this problem is to define an abstract network virtual that editor or other programmed deal with to handle each terminal type piece of software must be written to map the function of network virtual terminal on real terminal. Another application layer function is transfer differ file system have different file namely convection. Result: The OSI (open system interconnection) reference model is studied in details.

56

Experiment No.13

Experiment No. 13 Title: Study of Indexing and Hashing

57

Experiment No.13

Theory: Several indexing schemes and several hashing schemes hashing schemes have been seen. Files of record can be organized as ordered files using sequential organization .alternately files can be organized way as keep files where records are not ordered in any particular way. Each skin has advantage in certain location. the data base system implement to provide any scheme having final designer .however such an approach require an incremental to write more coding ,adding go to costly of the system uses only a few on thus are from of order indexing or hashing for wider choice implementation or database designer must consider causing issues .if the cost of periodic recognition of the order index or organization acceptable for this relative frequency of e insertion and deletion it id desirable to optimize average access time of expense increasing the word stored access time of what queries are likely to be passed by users .when it comes to make a choice to compare order ,indexing and hashing that is expected and query in the moat critical .the most queries are of the following form . 1. Select A1, A2 ----An from where A=C. INDEXING: An index for a file in the system works in much the same way as a catalogue and a card in the advance catalogue tell us where to find the book. To assist us in searching this catalogue the library keeps the cards in alphabetical order. So we do not have to check every card to find the one we find the one we find in the real world database the indices are not the type which is just described because they may be too large to be handled efficiently. INDEXING IN SQL: Indices are most important for efficient process of translation including both update transaction queries. Indices are also input for efficient information integrity constraints. Most SQL implementation provides the dell commands for certain and removal of indices An index is created by the create index command Create index <index name> or <relation name> [<attribute list>]
58

Experiment No.13

The attribute list is the list of attribute of that form the search key for the index to define index name E-index on the employee with E-name as the switch key. Create unique index E-index an employee. TYPES OF INDEXING: 1. ORDERED INDEICES: Such indices are based in a stored ordering of the value; an index structure is used for getting fast random access to record in a fine. Each index structure is associated with particularly search key. HASH INDICES Such indices are based on the values being distributed uniformly across the range of bucket. The bucket to which a value is assigned is determined by a function called a hash function. HASHING FUNCTION The sequential file organization, we have to access on index structure to locate the required record. It must use binary search and the result is more input operations whereas of the file organizing is using hashing technique, we can avoid accessing on index structures. Hashing also provides a way of constructing indices. KEY VALUE HASH FUNCTION ADDRESS

59

Experiment No.14

Experiment No. 14 Title: Study of Various Network Topologies

60

Experiment No.14

A topology refers to the manner in which the cable is run to individual workstations on the network. The dictionary defines topology as: the configurations formed by the connections between devices on a local area network (LAN) or between two or more LANs There are three basic network topologies (not counting variations thereon): the bus, the star, and the ring. It is important to make a distinction between a topology and architecture. A topology is concerned with the physical arrangement of the network components. In contrast, an architecture addresses the components themselves and how a system is structured (cable access methods, lower level protocols, topology, etc.). An example of architecture is 10baseT Ethernet which typically uses the start topology. Bus topology A bus topology connects each computer (node) to a single segment trunk. A trunk is a communication line, typically coax cable, which is referred to as the bus. The signal travels from one end of the bus to the other. A terminator is required at each end to absorb the signal so it does not reflect back across the bus. In a bus topology, signals are broadcast to all stations. Each computer checks the address on the signal (data frame) as it passes along the bus. If the signals address matches that of the computer, the computer processes the signal. If the address doesnt match, the computer takes no action and the signal travels on down the bus. Only one computer can talk on a network at a time. A media access method called CSMA/CD is used to handle the collisions that occur when two signals are placed on the wire at the same time.

61

Experiment No.14

The bus topology is passive. In other words, the computers on the bus simply listen for a signal; they are not responsible for moving the signal along. A bus topology is normally implemented with coaxial cable. Difference between a regular bus and a local bus

In a regular bus , each computer is attached to the cable segment (called a backbone) by means of a drop cable (a shorter cable connecting the computer to the backbone)

In a local bus , each computer is attached in directly a to the backbone connector. as a local bus. daisy-chain Peer-to-peer

configuration by means of a "T" networks are often configured

Advantages and disadvantages of the bus topology Advantages of bus topology: Easy to implement and extend Well suited for temporary networks that must be set up in a hurry Typically the least cheapest topology to implement Failure of one station does not affect others Disadvantages of bus topology: Difficult to administer/troubleshoot Limited cable length and number of stations A cable break can disable the entire network; no redundancy Maintenance costs may be higher in the long run Performance degrades as additional computers are added

62

Experiment No.14

Star topology All of the stations in a star topology are connected to a central unit called a hub. The hub offers a common

connection for all stations on the network. Each station has its own to direct the cable hub. In connection

most cases, this means more cable is required than for a bus topology. However, this makes adding or moving computers a relatively easy task; simply plug them into a cable outlet on the wall.

If a cable is cut, it only affects the computer that was attached to it. This eliminates the single point of failure problem associated with the bus topology. (Unless, of course, the hub itself goes down.) Star topologies are normally implemented using twisted pair cable, specifically unshielded twisted pair (UTP). The star topology is probably the most common form of network topology currently in use. Advantages and disadvantages of a star topology Advantages of star topology: Easy to add new stations Easy to monitor and troubleshoot Can accommodate different wiring Disadvantages of ring topology: Failure of hub cripples attached stations More cable required

63

Experiment No.14

Ring topology A ring topology consists of a set of stations connected serially by cable. In other words, its a circle or ring of computers. There are no terminated ends to the cable; the signal travels around the circle in a clockwise direction.

Note that while this topology functions logically as ring, it is physically wired as a star. The central connector is not called a hub but a Multistation Access Unit or MAU. (Dont confuse a Token Ring MAU with a Media Adapter Unit which is actually a tr ansceiver.) Under the ring concept, a signal is transferred sequentially via a "token" from one station to the next. When a station wants to transmit, it "grabs" the token, attaches data and an address to it, and then sends it around the ring. The token travels along the ring until it reaches the destination address. The receiving computer acknowledges receipt with a return message to the sender. The sender then releases the token for use by another computer. Each station on the ring has equal access but only one station can talk at a time. In contrast to the passive topology of the bus, the ring employs an active topology. Each station repeats or boosts the signal before passing it on to the next station. Rings are normally implemented using twisted pair or fiber-optic cable.

64

Experiment No.14

Advantages and disadvantages of a ring topology Advantages of ring topology: Growth of system has minimal impact on performance All stations have equal access Disadvantages of ring topology: Most expensive topology Failure of one computer may impact others Complex Ring topology wired as a star A ring topology has the same outward appearance as a star; all the stations are individually connected to a central location. In the star topology the device at the center is called a hub. In a ring topology, the center is called a MAU. While they look the same, a closer examination reveals that the ring actually consists of a continuous circuit. Signals are passed along the circuit and accessed by stations in sequence. In a star topology the signal is split and sent out simultaneously to all stations. The diagram below illustrates the continuous circuit of a ring.

65

Experiment No.14

Counter-rotating ring A counter-rotating ring is a ring topology that consists of two rings transmitting in opposite directions. The intent is to provide fault tolerance in the form of redundancy in the event of a cable failure. If one ring goes, the data can flow across to the other path, thereby preserving the ring.

66

You might also like