Вы находитесь на странице: 1из 155

DBMS

DBMS Concepts

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Data Base Management System


Data: Information is called data. Database: Organized collection of data is called database. A Database is a collection of information that's related to a particular subject or purpose, such as tracking customer orders or maintaining student records.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Data Base Management System


Data Base Management System: A software application which stores data and interact with the data on a daily need base. It is the technology that deals with Database in managing the Data, maintaining the Data and it's applications. It provides convenient environment to store, view, and edit the information.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Advantages of DBMS:
Data can be stored Standards can be enforced Integrity can be maintained Security restrictions can be applied Redundancy (repetition of data) can be reduced
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

DBMS provides the following services:


Data Definition: It provides a method of defining and storing the data population. Data Manipulation: It provides services that let the user enter, modify, remove, and sort data in the database. Data Maintenance: It maintains the population using a record for each item in the population, with fields containing particular information that describes that item.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

DBMS provides the following services


Data Integrity: It provides one or more methods of ensuring that the data is accurate. Data Display: It optionally provides some methods of displaying the data for the user.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

DBMS Models:
A Database Model describes, how the data are presented to the user and programmer for access. The database models can be classified into: FMS (File Management System)

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

DBMS Models:
HDBMS (Hierarchical Database Management System) NDBMS (Network Database Management System) RDBMS (Relational Database Management System

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

FMS (File Management System):


It is the first management system, which is used to store Data in a computerized manner. In FMS, the Data is stored in the form of files. In FMS, the Data is stored in sequential order. In FMS, if any modifications to be done to a record, it is to be deleted first and a new record is to be entered.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

FMS (File Management System):


It is a single user environment. It supports only one to one relation. Data Redundancy is more (Repetition of Data). Data is inconsistent (Inaccurate Data). Security is less.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

HDBMS (Hierarchical Database Management System):


The disadvantages of FMS are still continued in this. Advantages: Security has increased. It is Hierarchical Data Processing. Two types of relationships can be maintained i.e., one to one and one to many.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

NDBMS (Network Database Management System):


A set of computers connected together into a group, for the purpose of information interchange is called a Network. Using NDBMS the Data can be interchanged from computer to computer.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

RDBMS concepts
Dr.E.F.Codd proposed the relational model for database systems in 1970. The term relational derived from the set theory of mathematics. Relational model contains . Collection of Objects or relations. Set of Operators to act on the relations. Data integrity for accuracy and consistency.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

RDBMS (Relational Database Management System):


The simple DBMS supports only one user to access the Data at a time, whereas RDBMS (Relational DBMS) supports multiple users to access the Data simultaneously at a given time. Advantages: Data inconsistency is reduced. Data redundancy is avoided. Data security is maintained. It is a multi-user environment.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

RDBMS (Relational Database Management System):


It is a centralized Database. It is a Relational Database. Supports following types of relationships. One to One One to Many Many to One Many to Many
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

RDBMS terminology
It represents database as a collection of entitities or relations (tables). A row or record is called as a tuple which represents an entity. A column or field is called as an attribute of entity. A list of values of a field (column) is called domain. The number of attributes of a relation is called degree. The number of tuples determines the cardinality of the relation. 5/2/2012 9:50 PM FACULTY : SK ABDUL
YESDANI

RDBMS terminology
Primary Key : An attribute or combination of attributes that uniquely defines each tuple in a relation. Foreign key: An attribute or combination of Attributes in one relation R1 which indicates the relationship of R1 with another relation R2 and must contains values matching at both relations.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

RDBMS Users
RDBMS are multi user supported and many persons involved in the design, use, and maintenance of a large database with hundreds of users. Database Designer: Responsible for identifying the data to be stored in the database and choosing proper structures to represent and store data.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

RDBMS Users
Database Administrator (DBA): Collects the information to store in the database. A database is designed to provide the right information at the right time to right persons. DBA is responsible to authorizing access to the database, monitoring the database , breech of security and poor response time etc,.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

RDBMS Users
System Analysts and Application programmers: System Analists determine requirements of end users, and develop specifications for transactions that meet the requirements. Programmers implements the specifications as programs then test, debug, document and maintain these transactions. Maintain operation of the RDBMS software
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

RDBMS Users
End Users: They invoke an application to interact with the system, or writes a query for easy retrieval, modification, or deletion of data.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

RDBMS Components
Entities and Tables: An entity is any object which is distinctly identified becomes a table in the RDBMS. Ex: the entities in a college are students, faculty, branches etc. Each entity has its own features or characteristics known as attributes become columns in the table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Employee Table Attributes

Emp_no Emp_name
123 124 125 126
5/2/2012 9:50 PM

Emp_dob Emp_desig
Executive Supervisor Manager Accountant
T U P L

Anand Bharat Khan Kiran

12-jan1999 23-Mar2002 01-Jun2000 01-AugFACULTY :2000 SK ABDUL


YESDANI

Data Modeling
Data modeling is a group of conceptual tools that describes data n its relationships. Data modeling contains 3 steps. Conceptual data modeling identifies highest level of relationships in the data. Logical Data Modeling :describes the data and its relationships in detail. Physical Data Modeling: Specifies how the logical model is to be realized.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Entity Relationship model


E-R model belongs to Object based Logical Model. It contains 5 basic components: Entity Relationship Attributes Entity set Relationship set.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Types of Relationships
One to One One to Many Many to One Many to Many

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

E-R model Concepts


Primary Key: An attribute that can uniquely define an entity in an entity set. Strong Entity sets: Entities that have attributes to establish a Primary key. Weak Entity sets: Entities that dont have enough attributes to establish a Primary key.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

E-R Diagrams
Component
Entity

Symbol
Entity

Example
Student

Weak Entity
Relationship

Weak Entity
relationship

assignment
Saves in

Attribute
Key Attribute
5/2/2012 9:50 PM

attribute
attribute
FACULTY : SK ABDUL YESDANI

rollno
Acct_no

Types of attributes
Multi valued attributes Ex: multiple phone nos. Composite attributes Ex: address doorno, street, city,pin etc; Derived Attributes. Ex: age derives from DOB and current date.
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

Constructing E-R Diagrams


Gather all the data needed. Identify all entities. Identify all strong entities. Identify all weak entities. Identify attributes of each entity. Identify Primary Key attribute for each entity.
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

Constructing E-R Diagrams


Identify all multi valued attributes. Identify composite attributes. Identify all Derived attributes. Draw E-R diagrams based upon the identified entities & attributes.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Normalization
Previously databases used to have large number of columns and records. This has some drawbacks as given below. Repetition anomaly: repetition of data in different records effects on performance during retrieval of data. Insertion anomaly: Inserting data in some columns & leaving some columns blank could lead to problems while retrieving data.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Normalization
Deletion anomaly: deleting data from some columns may lead to deletion of all data regarding that person. Updating anomaly: if some thing is updated at one place this should be reflected at all other related places. If it is not updating at all related places that is updating anomaly.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Normalization
To avoid all anomalies from the database a technique called Normalization has introduced by Dr.E.F.Codd. There are 3 Normalizations based on dependencies among attributes of a relation.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

First Normal Form


To achieve First Normal Form: Create separate tables for each group of related data. Table columns must have atomic values. All the key attributes must be identified.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Employee Project details


Empno projId 142 168 263 245 Proj_na me 113,12 Bluesta 4 r,Spect 113 Bluesta r 113 Bluesta r 124 Spect Emp_n Grade ame Amar A Bharat B Kiran C Salary 30000 25000 20000 20000

Madhu C

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

First Normal Form


The Employee project Details table having data about 2 entities. So it has to be split into 2 tables. The projectid attribute is the primary key for project table. The emp_no attribute is the primary key for employee table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

First Normal Form


Proj- Proj_ Id name 113 Blust ar 124 Spect Empno Empna Grade me 142 Amar A
168 263 245
5/2/2012 9:50 PM

salary
30000 25000 20000 20000

bharat kiran

B C

Madhu C

FACULTY : SK ABDUL YESDANI

Second Normal Form


The tables are said to be in 2nd Normal Form: They meet the requirements of the first normal form. No partial dependencies in the tables. Means a non key attributes should not be partially dependant on more than one key attribute. Ex: The project name is dependent only on project Id and empname, grade, salary depends on only on empno. The tables are related through foreign keys.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

nd 2

Normal Form tables splitting


Bluestar Spect

Projid projname
113 124

EmpNo 142 142 168 263 5/2/2012 9:50 PM 245

Projid 113 124 113 245 Mad C 113 FACULTY : SK ABDUL hu YESDANI 124

Emp Emp Grad no name e 142 Ama A r 168 bhar B at 263 kiran C

salar y 3000 0 2500 0 2000 0 2000 0

Third Normal Form


To achieve 3rd Normal Form: Tables should meet the 2nd Normal Form. The tables should not have transitive dependencies in them. If an attribute can be determined by another non-key attribute it is transitive dependency. Again the tables can be splitted from employee table to gradsalary table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

rd 3

Normal Form
Empno 142 168 263 245 Empname Amar bharat kiran Madhu Projid 113 124 113 113 124 Grade A B C C

Grade A B C

Salary 30000 25000 20000

Proj projnam id e 113 Bluestar 124 Spect 5/2/2012 9:50 PM

EmpNo 142 142 168 263 FACULTY : SK ABDUL YESDANI 245

De normalization
By normalizing the database redundancy is reduced and data integrity ensured. But to retrieve the data complex queries may have required. It tends to effect on the performance of the database. So to avoid this a minimal redundancy can accepted and this is called De normalization.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Relational Operators
Operators operate on relations based on the foundation of relational Algebra. Select: used to extract data with a given condition. Project: Used to project certain details of a relational table. Product: It combine relation from 2 different relational tables.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Relational Operators
Union: it retrieve either one or 2 sets of data . Intersect : It will retrieve the data which is combination of 2 sets. Difference: It retrieve data that holds true in one table and not in the other. Join: Its the enhancement to the product operator.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Structure Query Language (SQL)


To interact with the database SQL is a non procedural programing language . It is a ANSI standard language used for operate on any database product. SQL contains large set of operators, functions to operate on database.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

SQL
SQL is used to create and manipulate all database objects. SQL was developed by IBM in the year 1979. The SQL performs the following variety of tasks: Creating, Modifying and Deleting database objects Inserting, Updating and Deleting data Provides for data integrity and consistency Querying data. Controlling access to the database.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

SQL categories
Data Definition language (DDL) Data Manipulation Language (DML) Data Control Language (DCL). Transaction Control language (TCL) Data Retrieval Languae.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

DDL
Commands of DDL. CREATE ALTER DROP RENAME TRUNCATE
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

DML
Commands of DML: INSERT UPDATE DELETE MERGE

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

TCL
Commands of TCL: COMMIT ROLLBACK SAVEPOINT

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

DCL
Commands of DCL: GRANT REVOKE Data Retrieval Language Command: SELECT

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Oracle Data Types


Char(n): Fixed length character data (string), n characters long , max size for n is 255 bytes. Varchar2(size) Variable length character Data . Max size 4000 bytes. Nvarchar 2(size) national / cluture specific variable length character data . Max size 4000 bytes.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Data types
Date represent date & time from 01-Jan4712 B.C to 31-Dec-9999 AD. Time Stamp Precision point time regarding seconds/ milliseconds/ CLOB character based large objects can be stored max size 4 gb. BLOB Binary based large objects can be stored upto a max size of 4 Gb.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Number (p,s) Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127. BINARY_FLOAT 32 bit single precision float data types requires 5 bytes and max value is 1.79 e 308. Binary _Double 64 bit double precision float data types requires 5 bytes and max value is 3.4 e 38.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Data types

Create command
It is used to create an object (table). Syntax: create table <table name>(column name data type constraint, ); Ex: create table student(st-no char(3), st_name varchar2(20), course vrchar2(20), Fees number(5));

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Describe command
It is used to see the structure of the object (table). Syntax: Describe <table name>; Ex: Describe student; Or Desc student; It will show the structure of the table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Insert command
Syntax: 1.Insert into <tablename> (column 1,.) Values( actual values for columns); 2. insert into <tablename> values( actual values for all columns in the order of creation);

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Update command
It is used to update or edit the data in the table. Syntax: Update <table name> set < columnname > = new value, where clause; Ex: update student set course='Java', fees=5500 where rolno='21';
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Delete command
It is used to delete data from the table. Syntax : Delete <table name> where clause; Ex: delete student where rolno='8';

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Operators
Operators are used to perform certain operations on the data or objects. Arithmetic operators. Logical Opertors. Relational operators.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Arithmetic Operators
+ * (multiplication) / (division)

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Logical Operators
AND It is used to combine both must be true. Or It is used to either of any one can be true Not Its used to become false .
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

Relational (comparison) Operators


= (equal) != , < > (not equal) > Greater than < Less than >= greater than or equal <= less than or equal
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

Comparison operators & their meaning


BETWEEN .. AND Between 2 values (inclusive of) Ex: Select * from Emp where sal Between 20000 and 30000; IN(set) match any of a list of values Ex: Select * from Emp where empid IN(101,204,444);
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Operators
LIKE Match a character pattern Ex: Select * from Emp where empname LIKE %Raju; ISNULL Is a null value Select * from Student where fee IS NULL;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

String Functions
Upper(string) converts to uppercase. Ex: Select upper(empname) from emp; It will convert all employee names into uppercase. Lower(string) converts to lowercase. Initcap(string) converts intial letter of every word to uppercase.

Length(string) returns the length of string Substr(string,n,[m]) clips out of m character piece of string starting at position n. If m not given assumes end of the string. Ex: select substr(Abdul Raheem,7) from dual; It will get Raheem from the string.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Aggregate Functions
They are statistical functions to count , average on a set of attribute values to get a single value. Count It will count rows. Ex: select count* from Emp; It will get the number of rows in the Emp table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Ex: select count(distinct desig )from Emp; It will bring out How many different job designations are in the table Emp. Max it will bring out maximum value from a column. Min it will bring out minimum value from a column. Ex: select min(sal), max (sal) from Emp; It will bring out max & min salaries from Emp 5/2/2012 9:50 PM FACULTY : SK ABDUL
YESDANI

Sum computes the sum of values in a column which are number data types. Ex: select sum(sal) from Emp where desig=engineer; It will get sum of the salaries paid to all engineers.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Number Functions
They will accept numeric input & return numeric values. Round(colm/ exprsion, n) rounds the given value to n decimal places. If n omitted there will be no decimal places. Trunc(colm/expresion, n) Truncate the given value to n decimal places, if n is omitted then n defaults to zero
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Mod(m,n) returns the reminder of m divided by n. Abs(n) returns the absolute value of n. Sqrt(n) returns square root of n. Pow(m,n) m will be raised to power of n Floor(n) adjust nearest small whole num. Ceil(n) adjust to nearest large whole num
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Oracle date format


Oracle stores dates in an internal numeric format representing century, year, month, day, hours, minutes and seconds. Default display and input format for dates is DD-MMM-RR and stores between 1-jan-4712BC and 31-dec-9999AD. SYSDATE function returns current database server date & time. Select sysdate from dual;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Arithmetic with dates


We can calculate dates by using arithmetic operators like +, -. Date + number date adds a no.of days to a date. Date number date subtracts a no.of days from a date. Date date returns no.of days subtracted from one date to another date.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Date + number / 24 date adds a number of DAYS ( hours to DAY) a date. Ex: select ename , (sysdate hiredate)/7 as weeks_ago_ joined from emp where deptid=90;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Date functions
They operate on Oracle dates. All date functions returns a value of DATE data type except MONTHS_BETWEEN, which returns a numeric value. MONTHS_BETWEEN(date1, date2) find number of months between 2 dates. The non integer part of the result represents a portion of the month.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Date functions
ADD_MONTHS(date, n) adds n calender months to a date. NEXT_DAY(date, char) finds the date of the next specified day of the week (char) following date. The value of char may be a number representing a day or a character string. LAST_DAY(date) finds the date of the last day of the month from the date.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

ROUND(date,[fmt]) returns the date rounded to the unit specified by the formal model fmt. If the fmt is omitted , date is rounded to the nearest day. TRUNC(date,[fmt]) returns with the time portion of the day truncated to the unit specified by the format model fmt. If no fmt the date is truncated to nearest day.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

TO_CHAR(date) it will convert the date into string format. Ex: select TO_CHAR(sysdate, dd-Monyyyy) from dual; Ex: select To_Char(sysdate, dd-Mon-RR) from dual;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Creating relationships between relations (Tables)


To create relationship between 2 tables we have to use primary key and foreign key constraints. For example there are 2 tables Course , Students. Student joins a particular course , so there is a relationship between a student and course.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Primary Key
We can directly mention primary key constraint to a table while creating the table. Syntax: create table <tablename>(column1,,<constraint > [constraint name ] <constraint type> (column name to which constraint applied));
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Primary key
Ex:create table dept1(dno char(4), dname varchar2(30), constraint dno_pk primary key(dno)); OR

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Primary key
Syntax2:Create table <table name> (<column1 > <datatype> <constraint> [constraint name] <constraint type>, column2,..); Ex:create table dept ( dept_id char(3) constraint dept_pk primary key, dept_name varchar2(20))
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Primary key
After creating the table without a primary key column we need to add a primary key constraint to the table. Ex: create table course(course_id char(3), coursename varchar2(30), fee number(5)); Alter table course add constraint course_pk primary key(course_id); It will add the primary key constraint to the course table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Foreign key
Foreign key is used to create relationship between 2 relations . Syntax: create table <tablename>(column1, ,colum n, <references> <referenced tablename>(<colum name from referenced table>));

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Foreign key
Ex:create table students (st_no char(3)primary key, st_name varchar2(30),j_date date, course_id char(3) references course(course_id));

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Alter Command
Its used to alter a table structure. We can add a new column, constraint to an existing table. We can modify the column data types , size of the column data type etc. We can drop columns, drop constraints of a table.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Alter
Adding a new colum to an existing table structure. Syntax: alter table <tablename> add (new column name data type); Ex: alter table dept add( location varchar2(30));

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Alter
Dropping a column Sysntax: Alter table <table name> drop column <column name> ; Example: alter table dept drop column location;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Alter
Modifying the data type or size of columns in the table . Syntax: alter table <table name> modify <column name> <new data type (size)> ; Ex: alter table dept1 modify dname char(20); It will changes the dname column data type to char(20).
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Alter
Adding constraints to the table with alter. Syntax: Alter table <table name> add constraint <constraint name > <constraint type> (<column name>); Ex: alter table dept add constraint did_pk primary key (deptid);
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

alter
Dropping the constraint of a table / column. Syntax: Alter table <table name> drop constraint <constraint name>; Ex: alter table dept drop constraint did_pk;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Alter
Adding a check constraint to a column. Check constraint is used to limit values between a range / or to do some validation. Ex: Alter table dept add constraint chk check(deptid between 101 and 909);

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Queries
A query is an operation that retrieves data from one or more tables or views. In this reference, a top-level SELECT statement is called a query, and a query nested within another SQL statement is called a sub query. Ex: select empid, empname, salry, desig from employee where empid =109;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Advanced Queries (joins)


Combining (join) tuples stored in different tables to display more meaningful and complete information. Comparisons in the where clause are used to combine rows from the tables listed in the from clause. Ex: Select ename, job,deptname from emp,dept where did= dno and job=Doctor
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

joins
To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. Oracle continues this process until all tables are joined into the result. The optimizer determines the order in which Oracle joins tables based on the join conditions, indexes on the tables, and, any available statistics for the tables.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Types of joins
Equijoin: An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent values for the specified columns.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Equijoin example
SELECT last_name, job_id, departments.department_id, department_name FROM employees, departments WHERE employees.department_id = departments.department_id;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Self Joins
Self join is used to create a query on a single table . The following query uses a self join to return the name of each employee along with the name of the employee's manager. A WHERE clause is added to shorten the output.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

SELECT e1.last_name||' works for '|| e2.last_name Employees and Their Managers FROM employees e1, employees e2 WHERE e1.manager_id = e2.employee_id AND e1.last_name LIKE 'R%';

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Sub Queries
subquery answers multiple-part questions. For example, to determine who works in Taylor's department, you can first use a subquery to determine the department in which Taylor works. You can then answer the original question with the parent SELECT statement.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

A subquery in the FROM clause of a SELECT statement is also called an inline view. A subquery in the WHERE clause of a SELECT statement is also called a nested subquery. A subquery can contain another subquery.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Use sub queries for the following purposes:


To define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement . To define the set of rows to be included in a view or materialized view in a CREATE VIEW or CREATE MATERIALIZED VIEW statement
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

To define one or more values to be assigned to existing rows in an UPDATE statement. To provide values for conditions in a WHERE clause, HAVING clause, or START WITH clause of SELECT, UPDATE, and DELETE statements.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Example of sub queries


Select ename,salry from emp where projno in(Select projectid from project where prj_startdate >30-jan-11) and deptno=20; It will bring out employees who are working on projects started after 30th Jan,11 and in deptno 20.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Select * from emp where deptno in( Select deptno from dept where Loc=Hyderabad); It will list all employees who are working in department(s) located in Hyderabad.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Scalar sub queries


A sub query that returns exactly one column value from one row is called as a scalar sub query. They can be used in all clauses of SELECT except GROUP BY Ex: Select empid,name from employee ex ORDER BY (select deptname from dept dt where ex.did= dt.did);
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Grouping
With GROUP BY clause we can group rows witch have certain properties & then applying an aggregate function on one column for each group separately. This clause appears after the where clause and must refer to columns of tables listed in the from clause
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Example
select dno,avg(salry) from employees group by dno; It will extract average salary of all depts. Select dno, count(eno) from employees where dno in(111,114) group by dno; It will return no.of employees working in dnos 111 & 114.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Select dno, sum(salry) from employees where salry >0 group by dno; It will calculate total salry for each department.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Views
View is a logical subsets or combination of data by creating views of tables. A view can be logical table based on a table or another view. It contains no data of its own but its like a window by which data from tables can be viewed of changed. The tables on which a view is based are called base tables.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

The view is stored as a select statement in the data dictionary. View s are useful to restrict data access and to make complex queries. To provide data independence. To present different views of the same data.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Types of views
Simple views Complex views

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Featyres simple view No.of tables One Functions No Groupsof data No DML operations through view Yes

complex view one / more Yes Yes


Not always

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Creating views
Syntax: CREATE [OR REPLACE] [FORCE] [NOFORCE] VIEW viewname AS subquery [WITH CHECK OPTION [CONSTRAINT]] [ WITH READ ONLY [CONSTRAINT]];

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

OR REPLACE Recreate already existing view. FORCE creates the view regardless of whether base table exists or not. NOFORCE creates the view if the base table exists , its default. WITH CHECK OPTION specifies only rows accessible to the view can be inserted /updated
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

WITH READ ONLY ensures that no DML operations can be performed on the view. Example : Create view empview80 as select empid, name, salry from employee where deptid =80;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

create view sal_view as select ename, salary, did from employee where did in('a01','c01'); Extracting the data from view: Syntax: Select < columnames > from view name; select * from sal_view
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Modifying a view
Syntax : Create or replace view < viewname> as select < columnames> from <tablename > <where clause> Ex: create or replace view sal_view as select eid,ename, salary, did from employee where did='d01;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

View with check option


Ex: create view viewspl as select * from employee where did ='a01' with check option constraint viewspl_chk

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

With read only


Ex: create or replace view viewspl as select * from employee where did in('a01','c01') with read only insert into viewspl values('333','Kumar',24000,'a01'); It wont allow any DML statement because of its read only option.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Top N Analysis
Syntax:

Example: select rownum as rank, ename, salary from (select ename, salary from employee order by salary asc) where rownum <=6
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

PL/SQL (Programming language / Structure Query language)


PL/SQL is for programmers, system analysts, project managers and others who interested in database applications. U should have through knowledge in SQL before beginning the PL/SQL. PL/SQL is a block-structured language. Basic units of PL/SQL are procedures, functions and anonymous blocks.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Continued
These logical blocks can contain any number of nested sub blocks. Generally each block corresponds to a problem or sub problem to be solved. So, PL/SQL supports divide & conquer approach to problem solving called stepwise refinement.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

PL/SQL block- structure


[DECLARE -- declarations] BEGIN ---statements [EXCEPTION --- handlers] END;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Advantages of PL/SQL
PL/SQL is completely portable, high performance transaction processing language . Supports for SQL. Supports Object-Oriented Programming. Better Performance &Tight Security. Tight integration with Oracle.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Continued.
We can use all SQL commands and functions, operators and pseudo columns. So, we can manipulate data flexibly and safely. It supports all SQL data types and it reduces the need to convert data passed between front end application and data base.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

PL/SQL character set


A specific set of character set available in PL/SQL for programming. A-Z and a-z (Upper & lower case letters). 0 to 9 digits for numbers. Symbols: ()+-*/<>=!;:,@%,#$&_ |{} ? [] tabs, spaces and carriage returns. Its non case sensitive , except with strings and character literals.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Data types in PL/SQL


Char(size) fixed length character data Varchar2(size) variable length chardata. Number(P,S) fixed or floating point nos. DATE fixed length date times. Boolean true or false

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Delimiters or operators of PL/SQL


A delimiter is a simple or compound symbol which has a spl meaning to PL/SQL For Example We can use delimiters for arithmetic operations. We can use all arithmetic operators, relational operators to form expressions. Ex: If x>y THEN high := x; End If;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Important Operators
+ , -, *, / ** Exponentiation operator. % attribute indicator. : host variable indicator. ; statement terminator. := Assignment operator => association operator
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

Continued..
|| Concatenate operator < > , != , ^ = relational (Not equal to) = relational (Equal to) > , <, >=, <=, -- single line comment /* ..*/ multi line comments
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

PL/SQL Control structures


Selection control - conditional control Iteration control Sequential control

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

IF and CASE statements


IF statement executes a block of statements conditionally. 3 forms of ifs. IF-THEN IF THEN- ELSE IF- THEN- ELSEIF. CASE is to evaluate a single condition and choose from multiple options.
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

IF-THEN
IF condition THEN Block of statements END IF; Example: IF sales > quota THEN compute_bonus(empid); UPDATE payroll SET pay = pay+bonus where empno = empid; END IF;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

IF-THEN-ELSE
IF condition THEN Blok of statements1; ELSE Block of statements 2; END IF;

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Continue
Example: IF trans_type =CR THEN UPDATE accounts SET balance = balance+ credit where account _no = act_id; ELSE UPDATE accounts SET balance = balancedebit where account _no = act_id; END IF;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

IF-THEN-ELSEIF
BEGIN IF condtion1 THEN block of statements; ELSEIF conditionn2 THEN block of statements; ELSE block of statements; END IF; END;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Continued
BEGIN IF sales >60000 THEN bonus := 1800; ELSEIF sales >40000 THEN bonus := 1000; ELSE bonus := 500; END IF; Insert into payroll values(empid,bonus,.); END;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

CASE
Example: CASE grade WHEN A THEN Salary := 40000; WHEN B THEN Salary := 30000; WHEN C THEN Salary := 25000; WHEN D THEN Salary := 20000; END CASE;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Iterative Controls: Loop & Exit


Loop statements let you execute a sequence of statements multiple times. 3 Forms of loop statements. LOOP, WHILE LOOP FOR - LOOP
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Loop
LOOP IF credit_rating <3 THEN Exit; -- Exits loop immediately END IF; END LOOP; --Control resume here
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

EXIT WHEN in a LOOP


LOOP FETCH c1 into .. EXIT WHEN c1% NOTFOUND; -- Exits END LOOP; CLOSE c1;
FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

WHILE - LOOP
1.WHILE condition LOOP sequence of statements END LOOP; Example: WHILE total <=25000 LOOP SELECT sal INTO salary from emp whree..; total := total+salary; END LOOP;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

FOR - LOOP
FOR counter IN [REVERSE] lower bound . Upperbound LOOP sequence of statements; END LOOP; Ex: FOR i IN REVERSE 1..3 LOOP -assigns values 3,2,1 to I total := total +200; -- executes 3 times END LOOP;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

COLLECTIONS
A collection is an ordered group of elements of same type. Its a general concept that contains lists, arrays and other data types. Each element has a unique subscript that determines its position in the collection.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Continue..
To create collections, U define a collection type, then declare variables of that type. U can define table and VARRAY types in the declarative part of any PL/SQL block, subprogram, or package

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Collection EXample
DECLARE TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER; emp_tab EmpTabTyp; BEGIN select * INTO emp_tab(6754) from emp where empno=6754; END;
5/2/2012 9:50 PM FACULTY : SK ABDUL YESDANI

Declaring PL/SQL Collection variables


Once U define a collection type, U can declare variables of that type. U use the new type name in the declaration, the same as with predefined types such as NUMBER and INTEGER.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

PROCEDURES
Use the CREATE PROCEDURE statement to create a standalone stored procedure or a call specification. A procedure is a group of PL/SQL statements that you can call by name.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

A call specification (sometimes called call spec) declares a Java method or a thirdgeneration language (3GL) routine so that it can be called from SQL and PL/SQL. The call spec tells Oracle Database which Java method to invoke when a call is made.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

It also tells the database what type conversions to make for the arguments and return value. Stored procedures offer advantages in the areas of development, integrity, security, performance, and memory allocation.

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

5/2/2012 9:50 PM

FACULTY : SK ABDUL YESDANI

Вам также может понравиться