Sie sind auf Seite 1von 22

Department of Information Technology

Lab Manual : Class : TE(IT) Experiment No. 1 Title : Introduction to DBMS Theory : Database Management System: A database management system (DBMS) is a collection of programs that enables users to create and maintain the database.The database and software together form a database system. Defining a database involves specifying the data types, structures, and constraints for the data. Constructing the database is the process of storing the data. Manipulating a database includes functions as querying, retrieval, update, and generating reports from database. Technically speaking, it is a software system that uses a standard method of cataloging, retrieving, and running queries on data. The DBMS manages incoming data, organizes it, and provides ways for the data to be modified or extracted by users or other programs. There are many different types of DBMSs, ranging from small systems that run on personal computers to huge systems that run on mainframes. The following are examples of database applications: computerized library systems automated teller machines flight reservation systems computerized parts inventory systems Database Models: Database can be differentiate based on functions and model of the data. A data model describes a container for storing data and the process of storing and retrieving data from that container. Various database models are: Flat file database model Hierarchical database model Network database model Relational database model 1 Subject : Database Management System

From a technical standpoint, DBMSs can differ widely. The terms relational, network, flat, and hierarchical all refer to the way a DBMS organizes information internally. The internal organization can affect how quickly and flexibly you can extract information. Query: Requests for information from a database are made in the form of a query, which is a stylized question. The set of rules for constructing queries is known as a query language. Different DBMSs support different query languages, although there is a semi-standardized query language called SQL (structured query language). Sophisticated languages for managing database systems are called fourth-generation languages, or 4GLs for short. Some DBMS examples include MySQL, PostgreSQL, Microsoft Access, SQL Server, FileMaker, Oracle, RDBMS, dBASE, Clipper, and FoxPro. Since there are so many database management systems available, it is important for there to be a way for them to communicate with each other. For this reason, most database software comes with an Open Database Connectivity (ODBC) driver that allows the database to integrate with other databases. For example, common SQL statements such as SELECT and INSERT are translated from a program's proprietary syntax into a syntax other databases can understand. Merits of DBMS: Controlling Redundancy :- In traditional file processing, every user group maintains its own files. Each group independently keeps files on their db e.g., students. Therefore, much of the data is stored twice or more. Redundancy leads to several problems : 1) 2) duplication of effort storage space wasted when the same data is stored repeatedly

3) files that represent the same data may become inconsistent (since the updates are applied independently by each users group). Restricting Unauthorized Access:- A DBMS should provide a security and authorization subsystem. Some db users will not be authorized to access all information in the db (e.g., financial data).Some users are allowed only to retrieve data. Some users are allowed both to retrieve and to update database. Providing Persistent Storage for Program Objects and Data Structures:- Data structure provided by DBMS must be compatible with the programming languages data structures. E.g., Object oriented DBMS are compatible with programming languages such as C++, SMALLTALK, and the DBMS software automatically performs conversions between programming data structure and file formats. Permitting Inferencing and Actions Using Deduction Rules:- Deductive database systems provide capabilities for defining deduction rules for inferencing new information from the stored database facts. Providing Multiple User Interfaces:- e.g., query languages, programming languages

interfaces, forms, menu-driven interfaces, etc. Representing Complex Relationships Among Data Enforcing Integrity Constraints Providing Backup and Recovery:- must provide facilities for recovering from hardware or software failures.

Users of DBMS: End Users: They interacts with the system either by invoking an application or by writing a query for easy retireval, modification or deletion of data Application Programmer: It writes programs that are used by end users to access the database Database Administrator: The DBA is primarily concerned with creating and maintaining the database ensuring proper functioning of the database and implementing security of the database. Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 2 Title : To study data types and operator in Oracle Subject : Database Management System

Theory : Every business enterprise maintains large volumes of data for its operations. Traditionally data was stored in flat file format. So, information about different objects was maintained separately in different physical files. So, relation between these objects had to be stored in separate physical file. This way a single package consist of lots of files and complete programming to integrate them into a single system. Oracle is an Object Relational Database Management System (ORDBMS). Oracle products are based on a concept known as the Client-Server Technology. Here Server performs all activities related to the database & client performs activities that help user to interact with the application. Commonly used front end tool of oracle is SQL* Plus in client side. Client is requesting information from the server using this tool. SQL * Plus is a Structured Query Language supported by the Oracle. Using this we can store, retrive, edit, enter & run the SQL commands. In order to communicate with the database sql provides following categories of commands. 1] Data Definition Language. 2] Data Manipulation Language. 3] Transaction Control Language. 4] Data Control language. Oracle Internal Datatypes:1] char(n):- Accepts alphanumeric data upto n characters in length. The n indicator is required. The char(n) right pads the data with blanks to ensure that a total of n characters will be stored no matter what. The maximum length is 32767 characters. 2] varchar2(n):- Accepts alphanumeric data upto n characters in length. The n indicator is required. The varchar2(n) will not pad value but will store only as much data as required by the entered value. The maximum length is 32767 characters. 3] long:- Accepts very large blocks of alphanumeric data upto 32760 bytes. 4] number(n,m):- Accepts numeric data only. The value for n is the size specification and the value of m is the precision. Both are optional, but m cannot be used without presence of n. 5] Date :- Accepts date description in the same date format required by the database. The default format is 'D-Mon-YY', where DD is the numeric day of the month, Mon is the first three letters, cpaitalized, of the month and YY is the last two digits of the year. 6] Raw:- Accepts binary data such as multimedia files and accepts length of upto 32767 characters. 7] Long Raw:- Accepts very large blocks of binary data upto 32760 bytes. 8] rowid:- A value that is defined by the oracle system to uniquely identify the physical storage address of a row in the oracle database.

Operators:1] Arithematic Operators:- To perform calculations based on numeric values, Arithematic operators are used. Arithematic operators are: + : Addition - : Substration * : Multiplication / : Division. 2] Comparison Operator:- Comparison Operators are used in conditions to compare one expression with another.The comparison operators are = != < > <= >= between : to check between any two values in : to match any of the values in the list Like : to match a character pattern Null : to check whether it is null 3] Logical Operators:- Logical Operators are used to combine the results of two conditions to produce a single result. The Logical operators are : AND NOT OR. 4] Set Operators:- Set operators combine the results of two queries into a single one. Following are the set operators: Union:- This operator select all distinct rows selected by both queries. Union All:- This operator returns all the rows selected by either query including duplicates. Intersect:- It returns only rows common to both the queries. Minus:- This operator returns all the distinct rows selected only by the first query & not by the second query. Problem: In addition to these Data Types search the other advanced data types such as CLOB, BLOB, NCLOB, BFILE. Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 3 Title : To study the DDL(Data definition Language) command Theory : The Data Definition Language (DDL) is used to create and destroy databases and database objects. These commands will primarily be used by database administrators during the Subject : Database Management System

setup and removal phases of a database project. The DDL used for creating objects can be classified into four commands:1.Create Table 2.Alter Table 3.Truncate Table 4.Drop Table 1] Create Table :- The Syntax for creating a table is as follows:CREATE TABLE <table name>(column definition 1, column definition 2,.); In this, a] We must specify the unique column name. b] And we must specify the proper datatype alongwith the width. Example: CREATE TABLE emp (empid varchar2 (5),empname varchar2(20),empdept number(5), empsal number(10,2)); establishes a table titled "emp" in the current database. In our example, the table contains four attributes: empid, empname, empdept, and empsal 2] Alter Table :- Once you've created a table within a database, you may wish to modify the definition of it. The ALTER command allows you to make changes to the structure of a table without deleting and recreating it. The Syntax for altering a table is as follows:ALTER TABLE <table name>Modify (column definition.); ALTER TABLE <table name> Add (column definition.); ALTER TABLE<table name>Drop(column definition.....); Take a look at the following command: ALTER TABLE emp ADD (designation varchar2(20)); This example adds a new attribute to the emp table -- designation of employee 3] Truncate Table Command:- If data in the table was not of further use and we want to retain the structure of table as it is , this command can be used. Records deleted using this can not be rollback. The Syntax for truncating a table is as follows:TRUNCATE TABLE <Table name> Ex. TRUNCATE TABLE emp; This statement will delete all rows from emp table . 4] Drop Table Command:- The final command of the Data Definition Language, DROP, allows us to remove entire database objects from our DBMS. The Syntax for dropping a table is as follows:DROP TABLE <table name> Ex. if we want to permanently remove the emp table that we created, we'd use the following command: 7

DROP TABLE emp Remember that the DROP command removes entire data structures from your database View the tables structure:- If the user wants to view the structure of table, the following command helps to achieve the same. The syntax is DESC <table name> Ex. DESC emp This shows the structure of the table along with column headings, data types, primary key and constraints. Problem: Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 4 Title : To study the Data Manipulation Language(DML) command Theory : 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. The DML commands are as follows:Subject : Database Management System

1] Insert 2] Select 3] Update 4] Delete 1] INSERT:- The INSERT command in SQL is used to add records to an existing table. Syntax is as follows:INSERT INTO <table name> values (a list of data values); Ex. 1INSERT INTO emp values(a1,Scott,10,8000); 2INSERT INTO emp values(&empid,&empname,&empdept,&empsal); 3INSERT INTO emp (empid,empsal) values (a2,5000); Note that there are four values specified for the record. In first two, these correspond to the table attributes in the order they were defined: empid,empname,empdept and empsal. But in last one, they must match with the sequence given in the query after table name. 2] Select:- The SELECT command is the most commonly used command in SQL. It allows database users to retrieve the specific information they desire from an operational database. This is generally referred as the querying the table. Syntax is as follows:SELECT column-name1, column-name2, .... from table_name; Ex. SELECT * FROM emp; This retrieves all rows from emp table. To retrieve list of the names of all employees in the company SELECT empname FROM emp; Finally, the WHERE clause can be used to limit the records that are retrieved to those that meet specified criteria. The following command retrieves all of the data contained within emp for records that have salary greater than 5000: SELECT * from emp where salary > 50000; 3 Update:- The UPDATE command can be used to modify information contained within a table, either in bulk or individually in table. Syantax is as follows:UPDATE <table-name> set field=value,..where condition; Ex. UPDATE emp SET salary = salary + 5000 WHERE empid = 12345; This adds 5000 to the current salary of employee with id 12345. 4] Delete:- After inserting rows in a table we can also delete them if required. The delete command consists of a from clause followed by an optional where clause. The Syntax for the delete command is:DELETE FROM <table_name> where condition; 9

Ex. DELETE FROM emp WHERE empid = 12345; This will delete details of employee id 12345 from the table. Problem: 1] Search how the select command can be used to create a new table which has same structure as that of existing table. 2] Retrieve the names of the employees whose job is SALSEMAN from the dept. no. 30 Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 5 Title : To study the TCL(Transaction Control Language) and DCL(Data control language) Theory : 1] Transaction Control Language(TCL) :- A Transaction is a logical unit of work. All the changes made to the database can be referred to as a transaction. Transaction can be made permanent to a database only if they are committed .A transaction begins with an executable Subject : Database Management System

SQL statement & ends explicitly with either rollback or commit statement & implicitly i.e. automatically, when a DDL statement is used. Let us see how commit & rollback controls transaction with the database. A] Commit :- This command is used to end a transaction. Only with the help of commit command transaction changes can be made permanent to the database. The syntax is as follows:COMMIT; B] Rollback :- A rollback command is used to undo the work done in the current transaction. We can either rollback the entire transaction so that all changes made by SQL statements are undone. The syntax is given as follows:ROLLBACK; 2] Data Control Language(DCL) :- Data control language provides users with privilege commands. The owner of the database object, say tables, has the sole authority over them. The owner can allow other database users to access to the objects as per the direction. Granting privileges (inser,select) to other allows them to perform operations within their (privileges)purview. For ex. If a user is granted a select privilege he/she can only view the data but can not perform any other DML operations on the owners object . A] Grant Privilege :When one user wants to share his objects(ex.Tables) with other users,the appropriate privileges can be granted on that object. Privileges can be granted to other users using the grant command.Syntax is as follows:GRANT <privileges> on <object_name> to <user_name> ; Privileges can be to select, update, delete,insert. Ex. SQL>conn scott/tiger; SQL>Grant select on emp to teit_A; SQL>conn teit_A/te_A; SQL>select * from scott.emp; Here,current user say scott is giving privileges to view the emp table to the teit_A user. Grant command can also have the grant option .If the owner is giving privileges with grant option to the grantee,then grantee can grant the privileges to other user on the same table. i.e if the above command includes with grant option then user teit_A can again give privilege on emp table to some other user say teit_B in following manner. SQL>Conn scott/tiger; SQL>Grant select on emp to teit_A with grant option; SQL>Conn teit_A/te_A; SQL>select * from scott.emp; SQL>Grant select on scott.emp to teit_B ; SQL>Conn teit_B/te_B; SQL>select * from scott.emp; In above ex. Grantee has to refer table name along with its owner name i.e. scott.emp B] Revoke Privilege :To withdraw the privileges that has been granted to a user ,we use the revoke command. The syntax is as follows :-

11

REVOKE <privileges> on <object_name> from <user_name>; In the above ex. If scott is removing privileges on emp from teit_A then automatically teit_B will also lost the access to emp.i.e. SQL>Conn Scott/tiger; SQL>Revoke select on emp from teit_A; Problem: In the above ex. Different users have been created. Using which sql command new user can be created ? Can every user create new user? If not, who is having that privileges? Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 6 Title : Study the SQL * plus functions Theory : 1] Single Row functions :- A single row function or scalar fun.returns only one value for every row queried in the table. Single Row functions are broadly classified as:A] Date functions B] Numeric functions C] Character functions D]Conversions functions. Subject : Database Management System

A] Date functions:1] Add_Months Syntax:- Add_months (d,n) Where d is date & n represents no. of months. 2] Last_Day Syntax:- Last_Day(d) 3] Months_between Syntax:- Months_between(d1,d2) 4] Next_Day Syntax:-Next_Day(d,day) Where d represents date & day implies any week day. B] Numeric functions:Numeric functions accept numeric input & returns numeric output. Ex. Functions Ceil(n) Floor(n) Power(m,n) Input Select ceil(42.78) from dual; Select Floor(100.2) from dual; Select Power (4,2) from dual; Output 45 100 16

C] Character Functions:1]Lower(char); 2]Upper(char); D] Conversion Functions:1] To_char(d,fmt):Where d is date & fmt is the format . This function converts date to a value of varchar2 in a form specified by date format fmt. 2]To_Date(char,fmt):Where char is character & fmt is format. This function converts varchar2 to a date. Fmt specifies form of character. 2] Group Functions or Aggregate Functions:A group function returns the result based on the group of rows . These are as follows:A] Avg Function:This Function return the average of values of the column specified in the argument of column. Syntax:-Avg(Col_name); B] Min Functions :The function will give the least of all values of the column present in argument. Syntax:-Min(Col_name); 13

C] Max Function :To perform an operation which gives the maximum of a set of values it is used. Syntax:-Max(Col_name); D] Sum Function:Sum Function can be used to obtain the sum of range of values of record set . Syntax:-Sum(Col_name); Grouping Rows with Group By Clause To this point, we've used aggregate functions to summarize all the values in a column or just those values that matched a WHERE search condition. You can use the GROUP BY clause to divide a table into logical groups (categories) and calculate aggregate statistics for each group. The GROUP BY clause's important characteristics are: 1The GROUP BY clause comes after the WHERE clause and before the ORDER BY clause. 2No columns from the input table can appear in an aggregate query's SELECT clause unless they're also included in the GROUP BY clause. A column can have different values in different rows, so there's no way to decide which of these values to include in the result if you're generating a single new row from the table as a whole. A GROUP BY clause, which groups rows, often is used with a HAVING clause, which filters groups. Problem: 1] Retrieve how many no. of employees are working as a salesman in each department. 2] Retrieve those deptno. For which sum of salary of that dept. employees is greater than 10000. 3] retrieve those dept. for which more than one emp are as a analyst. 4] select count of employees in each dept. for which count is greater than 3. Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 7 Title : Study of Joins Theory : Join statements allow you to combine data in multiple tables to quickly and efficiently process large quantities of data. These statements are where the true power of a database resides. There are basically 3 types of Joins:1]Simple Join 2]Self Join 3]Outer Join 1] Simple Join :- It is further classified into two types:Subject : Database Management System

15

A] Equi-Join :- It is based on equalities. It combines the rows that have the equivalent values for specified column. It retrives rows from both tables provided that they have the same deptno as specified in the where condition. Ex. Sql> Select ename,dname,loc from emp e, dept d where e.deptno=d.deptno; It retrives rows from both tables provided that they have the same deptno as specified in the where condition. Since where clause uses comparison operator equal (=) operator it is called equi-join. B] Non Equi-Join :- It specifies the relationship between columns belonging to different tables by making use of relational operators (<,>,>=,<=,<>) other than =. Ex. Sql> Select ename, sal,grade from emp ,salgrade where sal between losal and hisal; 2] Self Join :- A self-join is a normal SQL join that joins a table to itself and retrieves rows from a table by comparing values in one or more columns in the same table. Ex. Sql> Select e.* from emp e,emp y where e.sal>y.sal and y.ename=upper(Johnes); It retrieves those employees whose salary is greater than employee johns. 3]Outer Join :Ex. Sql> Select ename,dname loc from emp e, dept d where e.deptno(+)=d.deptno; It returns all rows returned by simple join as well as all those rows from one table that do not match any row from other other table. Unlike other joins, the order in which you specify the tables in outer joins is important, so the two join operands are called the left table and the right table. Outer joins come in three flavors: Left outer join:- The result of a left outer join includes all the rows from the left table specified in the LEFT OUTER JOIN clause, not just the rows in which the joined columns match. If a row in the left table has no matching rows in the right table, the associated row in the result contains nulls for all SELECT-clause columns coming from the right table. Right outer join :- A right outer join is the reverse of a left outer join. All rows from the right table are returned. Nulls are returned for the left table if a right table row has no matching row in the left table. Full outer join :- A full outer join, which is a combination of left and right outer joins, returns all rows in both the left and right tables. If a row has no match in the other table, the SELECTclause columns from the other table contain nulls. If a match occurs between the tables, the entire row in the result contains data values from both tables Problem: 1] Retrieve the deptname & sum of salary of that department. 2] Display names of employees working in sales dept. 3] Retrieve employee name & manager name of that employee using self join. 4] Select only those employees who do not have any person working under them using

self join Conclusion :

Department of Information Technology


Lab Manual: Class : TE(IT) Experiment No. 8 Title : Study of different types of subqueries Theory : A]Simple subqueries A simple subquery, or noncorrelated subquery, is a subquery that can be evaluated independently of its outer query and is processed only once for the entire statement. It is divided into two types:1] Single Row Subquery:Here,Subquery can return only one row. Ex. Retrieve those employees whose salary is greater than employee johns. Sql> Select * from emp where sal>(select sal from emp where ename=JOHNES); 2] Multiple Row Subquery:Here Subquery can return more than one row. In such b case we can include operators Subject : Database Management System

17

like any, all, in, not in . Ex. Retrieve those employees whose salary is greater than salary of any employee within deptno. 10 Sql> Select * from emp where sal > any(select sal from emp where deptno=10); B] Multiple Subqueries:Oracle places no limit on no. of subqueries included in where clause.It allows nesting of query within subquery. Ex. Select those employees whose job is equal to any employee of accountancy dept. Sql>Select * from emp where job in(select job from emp where deptno=(select deptno from dept where dname=Accountancy)); C]Correlated subqueries A correlated subquery can't be evaluated independently of its outer query; it's an inner query that depends on data from the outer query. A correlated subquery is used if a statement needs to process a table in the inner query for each row in the outer query. Ex. Retrieve those employees whose salary is greater than average salary of employees of the same dept. Sql>Select ename,sal,deptno from emp e where sal>(select avg(sal) from emp where deptno=e.deptno); Execution always starts with the outer query. The outer query selects each individual row of outer_table as a candidate row. For each candidate row, the DBMS executes the correlated inner query once and flags the inner_table rows that satisfy the inner WHERE condition for the value outer_column_value. The DBMS tests the outer WHERE condition against the flagged inner_table rows and displays the flagged rows that satisfy this condition. This process continues until all the candidate rows have been processed Note:- For all queries refer the emp ,dept, salgrade table Problem: Select details of employees which are located in NEWYORK Using subquery. Source Code and Output: Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 9 Title : Study of referential integrity constraints Theory : Primary Key: The primary key of a relational table uniquely identifies each record in the table. It can either be a normal attribute that is guaranteed to be unique (such as Social Security Number in a table with no more than one record per person) or it can be generated by the DBMS (such as a Rowid, in Oracle). Primary keys may consist of a single attribute or multiple attributes in combination.Every database table should have one or more columns designated as the primary key. The value this key holds should be unique for each record in the database. Once you decide upon a primary key and set it up in the database, the database management system will enforce the uniqueness of the key. If you try to insert a record into a table with a primary key that duplicates an existing record, the insert will fail. Syntax for specifying primary key is: Subject : Database Management System

19

CREATE TABLE tablename(columnname datatype [Constraint constraintname] primary key, columnname datatype) Here, constraint clause in the primary key is optional. Each table can have only one primary key. Foreign Keys The other type of key is the foreign key. These keys are used to create relationships between tables. Natural relationships exist between tables in most database structures. A foreign key is a column or set of columns in a table whose value relates to or reference values in same other table. A foreign key ensures that rows in one table have corresponding rows in another table. A foreign key establish a direct relationship to a primary key or candidate key in the referenced table. So foreign key values are restricted to present key value. If you insert or update a row into foreign key table, DBMS checks if the value in foreign key column matches primary key value. Deleting a row from parent table removes all matching entries in the foreign key table depending on primary key column.

Syntax: CREATE TABLE tablename (columnname datatype [Constraint constraintname] reference parenttable(primarykey-column)) Note that there is no uniqueness constraint for a foreign key. Problem: Create two tables with following structures: 1. publisher(pub_id, pub_name) and define pub_id as primary key 2. titles(title_id, name, price, pub_id). Define pub_id as foreign key and title_id as primary key. Conclusion :

Department of Information Technology


Lab Manual : Class : TE(IT) Experiment No. 10 Title : Study of Views Theory : A view is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. When writing queries, the query can get longer and longer. In addition, sometimes you find that a single query uses the same rules in two different parts of the query. In programming languages you would move the duplicated code into some sort of library of subroutines. In SQL, the idea of a subroutine is called a VIEW. A VIEW can be created in the DBMS, and each view represents a particular SQL query. Once the view is created, the query it represents is hidden from the user, and instead the view appears to be just another table. The contents of the VIEW always remains identical to the result of running the query which the view represents. For example, if we frequently issue the following query SELECT empid FROM emp; I might well want to make this a view . To create a view use the create view command as seen in this example CREATE VIEW view_emp AS SELECT empid FROM emp; This command creates a new view called VIEW_EMP. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this: SELECT * FROM view_emp WHERE empid BETWEEN 500 AND 1000; And Oracle will transform the query into this: SELECT * FROM (select empid from emp) WHERE empid BETWEEN 500 AND 1000; Subject : Database Management System

21

Benefits of Oracle Views Oracle views offer some compelling benefits. These include: * Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called its less likely to require parsing. This is because the basic underlying SQL that is called is always the same. * Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to. DROP View Once you are finished with your VIEW, you can delete it. The command to do this is DROP VIEW viewname Ex. DROP VIEW view_emp;

Conclusion :

Das könnte Ihnen auch gefallen