You are on page 1of 116

Data Storage

For any business to be successful , fast access to information is critical . Information is extracted from the existing data . Important decisions are taken on the information .To get the right information at the right time ; we store data on a Computer System.This aids in fast and easy access to information. To store and manage data on a computer we need a specialized computer program known as Database Management System(DBMS).A DBMS stores , process and retrieves data .

Database:A

Database is a collection i.e; tables,views,indexes,stored procedure and triggers.The data stored in a database may be related to any process such as Inventory / Payroll System

RDBMS:A collection of related data. Some popular RDBMS are: Oracle Oracle Corporation MS SQL 7.0 Microsoft Corporation Sybase Sybase Inc. Informix Informix Inc. Ingress Ingress Inc. DB/2 A Database which supports at least 6 Rules of 12 Rules of Boyce-Codd called RDBMS otherwise DBMS

Entity Relationship Diagram


Its a technique which is used to represent the logical structure of the database of a system.Its nothing but the diagrammatic representation of database design. What happens in real world ,when you want to construct a house according to your specifications, you would approach to a construction company .The architect would typically interview you to understand your requirements.He draws blue print according to your specifications, and, then construction of the building starts. Similarly , in a Software development environment , a System Analyst will interview the client for all the project specifications , draw the ER Diagram , and get it verified by the client .If the diagram is as per requirements and fulfills all the needs of client ,creation of the database and table will follows.

An ER Diagram is like a blue print for the databases.It consists of following 3 elements: It was introduced by Entities Peter Chen in 1976. Relationships Attributes Sequence is:
Identify Entities->Attributes->Relationship

Entity:
An Entity is an object with distinct set of easily identifiable properties.They are building blocks of a database .An Entity can be any object,item,place, concept or activity about which data can be stored .In a diagramming technique entities are named and represented by a BOX.

STUDENT

COURSE

GRADE

Entity Type: A set of things which share common properties .For eg; STUDENT , COURSE,GRADE.Usually denoted in UpperCase Entity Instance(Example):Is a specific individual , thing/objects.For eg; Deepu,Science .Usually denoted in lower/mixed case.

Attributes:
An Attribute is a properties of the Entity.An attribute instance is a particular property of an individual entity instance.An attribute type is property of an Entity type .For eg; male is an attribute instance while SEX is an attribute type.Attributes are depicted as ellipses,labeled with name of the property.
REG_NO ADDRESS

STUDENT

NAME

SEMESTER

TABLE:Entities are represented as table in a database .A


table is a arrangement of Rows and Columns.Attributes are represented as column heading in a table and actual data about the entity in rows . RollNo
R001 R002 R003 R004 R005

Name
Arti Vivek Preeti Deepu Rani

Address
Dhanbad Kolkata Kolkata Lucknow Delhi

Phone
NULL 5619944 5619944 213456 7639129

Reg_Date
10/02/2002 21/03/1990 05/10/1980 05/05/1989 14/08/1997

RELATIONSHIPS

It is an association among entities .For eg: there is a relationship between you and me (Student and Instructor ).This relationship represents the fact that an Instructor teaches several students.The name of the relationship is Teaches.Relationship depicted by a diamond ,with the name of the relationship type.

INSRUCTOR

TEACHES

STUDENT

Types of Relationships

One to One:
One instance of an Entity can relate to only one instance of related instance.For one Department ,there can be only one Department Head.One Faculty cannot head more than one Department.
RAJ
RAJA SALES COMPUTER FINANCE MARKETING PRODUCTION

SIMRAN
DEEPU RANI

DEPARTMENT

ONE

HEADED BY

ONE

ONE FACULTY MEM

CITY

ONE

SALE

ONE

SALESMAN

One to Many One instance of an Entity can relate more than one instance of related Entity.For eg; One Salesman can sell in many cities.
SALESMAN

ONE

SALE

MANY CITY
Kolkata

RAJ

Mumbay
Dhanbad

SIMRAN

Chennai Ranchi Orissa

RANI

Delhi

Many to Many
More than one instance of an Entity can relate more than one instance of its related Entity.For eg;Many Salesman can sale in many city.
SALESMAN MANY SALE MANY CITY Kolkata

RAJ

Mumbay
Dhanbad

SIMRAN

Chennai Ranchi Orissa

RANI

Delhi

After ER Diagram Entities are mapped to tables and they are related using common Attribute CITY SALESMAN CityCode SCode CName Sname SCode Address Attribute Naming Conventions:
Starts with Characters Can use lower/uppercase Can be upto 256 Characters Embedded space not allowed

Keys
Candidate Key(Surrogate):An attribute or set attribute that uniquely identifies a row.(If a column contain unique values). StudId S001 S002 S003 S004 S005 Name Rajan Deepu Ajeet Deepu Vivek City Lucknow Lucknow Mujaffarpur Delhi Kolkata Fees 56000 40000 67000 12000 25000

To ensure data integrity (Validation) so that the data in the database is valid and correct,Keys play important role .The various types of keys are:

These columns contains unique values , so these are Candidate Keys.

Primary Key
The candidate key which is used to uniquely identify each row is called Primary Key.Here StudId is Primary Key ,choosing Fees as a Primary Key is meaningless as there is no sequence.

Alternate Key
The candidate key which is not chosen as Primary Key is called Alternate Key.Here, Fees is a Alternate Key.

Composite Key
When the key that uniquely identifies the rows of table made up of more than one attribute .

CustId C122

ProdId P002

Qty 12

SaleDate 14/08/76

C134
C122

P002
P005

13
12

14/08/76
10/02/75

None of the columns contains unique values . However , if we combine CustId and ProdId we get unique value.So CustId+ProdId is Composite Primary Key.

Foreign Key
When primary key of one table is also available as an attribute in another table,it is called Foreign Key. It is used to relate tables. Referential Integrity:Ensuring that all the values in Foreign key match with the Primary Key. PRODUCTS ProdId(PK) Description Qoh Price
CUSTOMER CustId ProdId(FK) Qty OrderValue

SQL
It is the language used to access data within Oracle databases. Developed by IBM in mid 1970s. Oracle Corporation introduced the first the commercially available implementation of SQL. Abbreviation of Structured Query Language, pronounced as see quell is made of three sub-languages such as:

Data Definition language (DDL):


Consists of commands to create the objects like CREATE,ALTER,DROP such as tables,views , indexes etc.

Data Manipulation Language(DML):


Used for query , Insertion,Deletion and Updation of information stored in the databases.

Data Control Language(DCL):


Used for controlling data and access to the databases Example:Commit , Rollback

SQL *Plus

SQL *Plus is a software product from Oracle Corporation that allows users to interactively use the SQL commands , produce formatted reports and support written command-procedures to access Oracle databases.Through SQL * Plus user can: Enter,edit,store,retrieve and run SQL commands Format ,perform calculations on , store , and print query results in the form of reports. List column definition of any table. Access and copy data between SQL databases. Send messages to and accept responses from an end user.

Starting SQL *Plus


Programs

Oracle-OraHome81

Application Development SQL Plus

Data Type:Type of data that is stored in a column.


These are: 1)Char(size):Fixed-length character data ,size character long.Maximum size is 2000. 2)Varchar2(size):Variable length character string having maximum of size bytes(upto 4000) 3)Number(size): Stores fixed and floating point nos. 4)Date: Stores date and time. 5)Long: Can store up to 2 GB of characters. 6)Raw: Used to store graphics & sound etc.

Creating Table
Table is a Row and Column arrangement of data. Tables are owned by the user who creates them Name of table must be unique Column names in a table must be unique Column names can be duplicated across the tables Table name must begin with a letter A-Z or a-z It may contain letters, numbers and special characters It may upto 30 characters long. Must not be SQL reserved word Names are not case-sensitive Syntax:
Create table <table name>( Column-name <datatype(size)>,

Create table ItemMast ( ITNO number(4), Name varchar2(20), QOH number(5), Class char(1), ROD date, Rate number(8,2) ); To see the structure of a table: Desc[ribe] <table-name>

Inserting Values into a Table

Insert command is used to insert rows in a table Values can be inserted for all columns or for selected columns At a time single can be inserted Syntax: Insert into <table-name> (cols list) values(..);

Inserting through Parameter Substitution


Parameter substitution provides an easier way to enter data into a table .The & symbol is used as the substitution operator.When a substitution operator is used ,SQL *Plus prompts for the value of the variable , accepts it and then substitutes it in place of the variable. insert into ItemMast values (&ITNO, '&Name', &Qoh,&class','&ROD','&Rate') Enter value for itno: 2 Enter value for name: Cinthol Int. Enter value for qoh: 15 Enter value for class: B

Enter value for rod: 19-May-2002 Enter value for rate: 15.76
old 1: insert into ItemMast values (&ITNO, '&Name, &Qoh, '&class','&ROD','&Rate') New 1: insert into ItemMast values(2,'Cinthol Int.', 15 , 'B', '19-May-2002','15.76')

1 row created.

Alternatively we can use like:


insert into ItemMast values(&1,'&2',&3,'&4','&5',&6) Enter value for 1: 4 Enter value for 2: XXX Enter value for 3: 100 Enter value for 4: D Enter value for 5: 02-Feb-2002 Enter value for 6: 100
Statement: insert into ItemMast values (&1, '&2', &3, &4', &5',&6) Read As : insert into ItemMast values(4,'XXX',100,'D','02-Feb 2002',100)

1 row created.

Retrieve Information from Table


Select statement instruct the database to retrieve information from a table. Syntax: Select <column list> from <table-name> [where <condition>] Select * from ItemMast;

To see list of tables created by the user: Select * from TAB;

Tables can be altered in one of the three ways:


By adding a column to an existing table By changing a columns definition By droping column Adding column to a table: Alter table <table name> add(<col-name> <datatype>); alter table Employee add(Salary Number);
Any No. of columns can be added in single alter command.

Alter Table

Changing Column Definition:


Alter table Employee modify(Salary Number(5) NOT NULL);

Dropping Column of a table : To drop a column use : Syntex: Alter table <tab-name> drop column <col-name>; eg. Alter table Employee drop column EmpAddress;

Creating table with Rows from Another Table Create table MyTable As Select * from ItemMast; Creating with different Column Headings: Create table myTable(Name,Salary) As Select ename, sal from Employee;

Creating Temporary Table


Temporary tables are only for current session , after session only structure of table left in the database. Create global temporary table MyTable ( EmpId char(4), EmpName varchar2(10) );

Updating Column(s) of a Table

UPDATE command is used to update the columns in the table. Values of a single column or group of columns . Updation can be carried out for all the rows in the table or selected rows. Syntax: Update <Table-Name> SET <column-name> = <value> [where <condition>] Update emp set comm=500; Update emp set sal=sal+(sal*0.1); Update emp set sal=sal+500 where EmpId=E005;

Deleting Rows from Table

DELETE command is used to delete rows from a table. The entire row is deleted from the table. Specific column cannot be deleted from table Syntax: Delete from <Table-Name> [where <condition>] Delete from emp; Delete from emp where job=Clerk;

Deleting Structure of a Table


To delete structure of table DROP command is used. Syntax:

DROP TABLE <Table-Name>; Drop table emp;

Data Integrity

Enforcing data integrity ensures the quality of the data in the database. For example, if an employee is entered with an employee_id value of 123, the database should not allow another employee to have an ID with the same value. If you have an employee_rating column intended to have values ranging from 1 to 5, the database should not accept a value of 6. If the table has a dept_id column that stores the department number for the employee, the database should allow only values that are valid for the department numbers in the company. Two important steps in planning tables are to identify valid values for a column and to decide how to enforce the integrity of the data in the column. Data integrity falls into four categories:

Entity integrity

Domain integrity
Referential integrity User-defined integrity There are several ways of enforcing each type of integrity.
Entity: Domain PRIMARY KEY constraint UNIQUE constraint DEFAULT definition FOREIGN KEY constraint CHECK constraint NOT NULL FOREIGN KEY constraint CHECK constraint All column- and table-level constraints in CREATE TABLE Stored Procedures Triggers

Referential User-defined

Entity Integrity:Entity integrity defines a row as a unique entity for a particular table. Entity integrity enforces the integrity of the identifier column(s) or the primary key of a table (through indexes, UNIQUE constraints or PRIMARY KEY constraints). Domain Integrity:Domain integrity is the validity of entries for a given column. You can enforce domain integrity by restricting the type (through data types), the format (through CHECK constraints ), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL definitions).

Referential Integrity:Referential integrity preserves the defined relationships between tables when records are entered or deleted. It is based on relationships between foreign keys and primary keys or between foreign keys and unique keys. Referential integrity ensures that key values are consistent across tables. Such consistency requires that there be no references to nonexistent values and that if a key value changes, all references to it change consistently throughout the database.When you enforce referential integrity, SQL Server prevents users from: Adding records to a related table if there is no associated record in the primary table. Changing values in a primary table that result in orphaned records in a related table.

Applying Constraints
They are part of table definition that are used to limit the values entered into its columns NOT NULL:Prevents column from accepting NULL values UNIQUE:Ensures uniqueness of the values in a column Primary Key:Same as Unique , but only one column allowed per table Check:Controls the value of a column(s) being inserted Default:Assigns a default value for the column(s),at the time of insertion when no value is given for that column References:Used to relate two tables,maintains Referential Integrity

The constraints are declared at the time of creating creating a table with CREATE Table command. Constraint can be added to a table after its creation . All the the details of constraints are stored in Data Dictionary. Each constraint is assigned a name.It is easier if we give user defined names so that it is easily referenced ,otherwise the name is automatically generated of the form : SYS_Cn Where n is unique number The keyword CONSTRAINT allows us to name a new constraint .All constraint names must be unique.

NOT NULL:
This constraint is placed immediately after the datatype of a column .Any attempts to put NULL values in that column will be rejected .Columns without NOT NULL constraint allow NULL values.
Create table ItemMast ( ITNO number(4) NOT NULL , Name varchar2(20), QOH number(5) );

UNIQUE:
This constraint ensures that the values entered into the column are UNIQUE..
Create table ItemMast( ITNO number(4) UNIQUE , Name varchar2(20), QOH number(5));

Columns with Unique constraint allows NULL ,but if we want to restrict the same , use NOT NULL along with UNIQUE constraint
Create table ItemMast( ITNO number(4) NOT NULL UNIQUE , Name varchar2(20), QOH number(5));

We can also define a group of columns as UNIQUE table constraint.Declaring a group of column as UNIQUE , differs from declaring the individual columns as unique
Create table ItemMast(
ITNO number(4) NOT NULL, Name varchar2(20) NOT NULL, QOH number(5), UNIQUE(ITNO,Name));

Applying constraint Name:


Create table ItemMast( ITNO number(4) NOT NULL constraint MYCons UNIQUE , Name varchar2(20), QOH number(5));

PRIMARY KEY:

This key also ensures unique values , but it differs from UNIQUE as
it does not allow NULL Only one Primary Key can be declared in a table. It can also apply to multiple columns , forcing a unique combination of values. Create table ItemMast(
ITNO number(4) Primary Key, Name varchar2(20) NOT NULL, QOH number(5));

Create table ItemMast(


ITNO number(4), Name varchar2(20), QOH number(5),

CHECK:

This allows the user to define a condition ,that a value entered into the table ,has to satisfy,before it can be accepted.The CHECK Constraint consists of the keyword CHECK followed by parenthesized conditions.Any attempt to update or insert column values that will make the condition false , will give an error.
Create table ItemMast(
ITNO number(4) Primary Key, Name varchar2(20) NOT NULL, QOH number(5) CHECK (QOH >10));

Create table ItemMast(


ITNO number(4), Name varchar2(20) Check (Name in (Lux,Cinthol,Denim)),

Create table ItemMast (


ITNO number(4) Primary Key, Name varchar2(20) NOT NULL, QOH number(5) , Check ((Name=Lux and QOH >=10) OR (Name=Cinthol and QOH >=20))

DEFAULT:
This is used insert a value in the column when user is not entering any value for that column.

Create table ItemMast (


ITNO number(4) Primary Key, Name varchar2(20) Default Lux, QOH number(5) , Check ((Name=Lux and QOH >=10) OR (Name=Cinthol and QOH >=20))

);

REFERENCES:
A foreign key is a combination of columns with values with values based on the primary key values from another table.A foreign key constraint, also known as Referential Integrity Constraint , specifies that the values of the foreign key correspond to actual values of the primary key in another table .
Create table ItemTran( ITNO number(4) references ITEMMAST(ITNO), TranType char(1) check (trantype in(I,R)), TranDate date, Qty number(5)); Create table ItemTran( ITNO number(4), TranType char(1) check (trantype in(I,R)), TranDate date, Qty number(5), Foreign key(ITNO) references ITEMMAST(ITNO));

ON DELETE CASCADE OPTION:


Using this option whenever a parent row is deleted then all the corresponding child rows are deleted from the detail table.This option is always used with FOREIGN KEY.

Create table ItemTran( ITNO number(4) references ITEMMAST(ITNO) ON DELETE CASCADE, TranType char(1) check (trantype in(I,R)), TranDate date, Qty number(5));

Querying Database Tables


The Select statement instructs the database to retrieve information from table. Syntax: Select <column list> from <table-name> [Where Condition> [Group By Column Name(s)>] [Having <condition>] [Order by <expression>] Examples: Select * from emp; Select EmpName,Salary from Emp;

Conditional Retrieval of Rows: The Where clause is used along with the SELECT statement to specify the condition ,based on which the rows will be extracted from the table with SELECT The where clause is case-sensitive Operators are used to specify conditions: Relational Operators:
=,>,>=,<,<=,<>,!=

Logical Operators:
AND, OR ,NOT

Special Operators:
IN,BETWEEN,LIKE

Examples: Select * from emp where deptno=20; Select ename,sal from emp where sal>20; Select empno,ename from emp where job= MANAGER Select ename from emp where job=CLERK and deptno=20; Select ename from emp where job=CLERK or job=ANALYST; Select * from emp where hiredate <= 30-SEP-81; Select ename from emp where job <> MANAGER Select ename from emp where enpno in(7369,7521,7839); Select * from emp where deptno NOT IN (10,20,30); Select enam,sal from emp where sal between 1000 and 2000 Select ename from emp where hiredate not between 30JUN-81 and 31-DEC-81;

DISTINCT Clause : DISTINCT clause is used with select to suppress duplicate values if any in a column. SELECT DISTINCT job from emp;

NULL values: NULL values are not 0 or a blank. It represents an unknown or inapplicable value. It cannot be compared using the relational and /or logical operators. The special operator IS is used with the keyword NULL to locate NULL values Select ename from emp where deptno IS NULL; Select ename from emp where deptno IS NOT NULL; Select * from emp where sal > 2000 and comm is NULL;

Matching a pattern with a column


The LIKE operator is used. It can only used with CHAR and VARCHAR2 % represents a sequence of zero or more characters _ stands for single character Examples: Select ename from emp where ename like S% Select ename from emp where ename like %S Select ename from emp where ename like _____ Select ename from emp where ename like _I%

User friendly Column Headings


We can change the names of columns at the time of select statement Syntax: Select <actual col-name> <user-def name> from <table-name> Select id EMPID from Employee Select id as EMPID from Employee Select ename, sal,sal*0.1 PF from emp

Ordering Results of a Query


SQL uses the ORDER BY clause to impose an order on the result of a query. ORDER BY clause is used with SELECT statement. Syntax:
Select <col-list> from <table-name> [Where condition] [ORDER BY <columns>][ASC|DESC]

The order by clause orders(sorts) the query output according to the values in one or more selected columns.By default it orders in Ascending order. ORDER BY must always be the last clause in the SELECT statement.

Order BY contd
List the empno,ename, sal in ascending order of salary
Select empno, ename, sal from emp order by sal;

List the Employee Name , salary,Job and Dept No. is ascending order of Department and then on descending order of salary:
Select deptno, job, ename, sal from emp order by DeptNo, Sal DESC;

Ordering output by Column Number


In place of column names,we can use numbers to indicate the fields being used to order the output.These numbers will refer, not to the order of the columns in the table, but to their orders in the output. Example:
Select empno, ename, sal from emp order by 3;

Aggregate Functions
Aggregate functions are used to produce summarized results. They operate on set of rows. They return results based on groups . By default all rows in a table are treated as one group . The aggregate functions produce a single value for an entire group or table.

COUNT: It determines the number of rows/ noNULL column values.If * is passed , then the total number of rows is returned. List the no. of employees working with the company: SELECT COUNT(*) FROM emp; List no. of jobs available in the emp t able: SELECT COUNT(DISTINCT job) from emp;

SUM:The sum function returns the sum of values for the select list of columns. Select Sum(sal) from emp; MAX:This returns the maximum value of the selected list of item. Select MAX(sal) from emp where job=Salesman; MIN:This returns the minimum value of the selected list of item. Select MIN(sal) from emp where job=Salesman; AVG:Returns the average of column values. Select AVG(sal) from emp;

Grouping the Result of a Query


The Group By clause is used to divide the rows in a table into smaller groups. The Group By clause is used with SELECT clause SQL groups the result after it retrieves the rows from the table. Conditional retrieval of rows from grouped result is possible with the HAVING clause Syntax: Select <col-list> from <table> [where condition] GROUP BY <col> [HAVING <condition>]

List the department numbers and the number of employees in each department Select deptno,count(*) from emp GROUP BY deptno; List the dep no. and the total salary payable in each dept: Select deptno,sum(sal) from emp group by deptno; List the jobs and the number of employees in each job.The result should be in descending order of the number of employees: Select job,count(*) from emp group by job Order by 2 desc; List the total salary maximum & minimum salary and average salary of employees job wise: Select job,sum(sal),avg(sal),max(sal),min(sal) from emp group by job.

List the average salary from each job excluding managers: Select job,AVG(sal) from emp Where job!=MANAGER group by job Groups within groups: Group by clause can be used to provide results for groups within groups. List the average monthly salary for each job type within department Select deptno,job,avg(sal) from emp group by deptno,job;

The HAVING Clause


HAVING clause is used to specify the condition on Group By clause like Where Clause select is used with SELECT. List average salary for all departments employing more than five people: SELECT deptno,AVG(sal) from emp GROUP BY deptno HAVING count(*) >= 5;

JOINS
Joins are used to combine columns from different tables. The connection between tables is established through the where clause. Types of Joins:Equi Joins, Cartesian Joins,Outer Joins, Self Joins.

One of the most important features of SQL is the ability to define relationships between multiple tables and draw the information from them in terms of these relationships , along within a single command.With joins , the information from any number of tables can be accessed. To join two tables, the retrieval criteria will typically specify the condition that a column in the first table (which is defined as foreign key) is equal to a column in the second table (which is primary key referenced by the foreign key)A joins where clause may contain additional conditions.In a join , the table names are listed in the from clause separated by commas.

Syntax
SELECT <select-list> from table1> , <table2> ,., <tableN> Where <table1.col1>= <table2.col2> and <table2.col3>= <tableN.colN>. Additional conditions <select-list>:set of cols and expressions from <table1> through <tableN> <table1> through <tableN>: tables from which column values are retrieved <col1>through <colN>:the columns in <table1> through <tableN> that are related Addition conditions are optional query criteria

EQUI JOINS:
When two tables are joined together using equality of values in one or more columns ,they make an Equi Join.Table prefixes are utilized to prevent ambiguity and the where clause specifies the columns being joined. Example: List the employee numbers,names , department numbers and the department name: SELECT empno,ename,emp.deptno ,dname from emp , dept where emp.deptno=dept.deptno

Table Aliases
It can be very tedious to type the table names repeatedly.Temporary labels(or aliases) can be used in the FROM clause .These temporary names are valid only for the current select statement.Table aliases should also be specified in the select clause.Table aliases should can be up to 30 character in length , but the shorter they are better. The advantage of using table aliases is that it effectively speeds up the query
SELECT e.empno,e.ename,e.deptno ,d.dname from emp e, dept d

Where e.deptno=d.deptno

Cartesian Joins
When no join condition clause is specified in WHERE clause, each row of one table matches every row of the other table.This results in a Cartesian product.
SELECT empno, ename, dname, loc from emp, dept; If the number of rows are 14 and 4 in emp and dept tables respectively ,then the total number of rows produced is 56. Cartesian product is useful in finding out all the possible combination of columns from different tables.

Consider following tables and data present: Tab1:Holds principal amount. Tab2:Holds year and rate of interest .
Tab1 PRICIPAL
1

Tab2 YEAR
10 11 2

RATE
11.5
12

1000
2000 3000

3
4

Finding the possible combinations of calculation of amount, a Cartesian join of Tab1 and Tab2 is required.The formula for calculation of Amount is Pricipal*(1+(rate/100))year Select Principal, Year, Rate, Principal* POWER(1+(rate/100),year) from TAB1,TAB2

Outer Joins
If there are any values in one table that do not have corresponding value(s) in the other , in an equi join that row will not be selected.Such rows can be forcefully selected by using the outer join symbol(+) . The corresponding columns for that row will have NULLs. Example:Display the list of employees working in each department .Display the department information even if no employee belongs to that department:
SELECT empno, ename, emp.deptno, dname, loc from emp, dept where emp.deptno(+) = dept.deptno;

Rules to place(+) operator

The outer join symbol(+) can not be on both the sides It is possible between only two tables

Self Join:
To join a table to itself means that each row of the table is combined with itself and with every other row of the table.The self join can be viewed as a join of two copies of the same table .The table is not actually copied , but SQL performs the command as though it were. The syntax of the command for joining table to itself as almost same as that for joining two different tables.To distinguish the column names from one another , aliases for the actual table name are used , since both the tables have the same name . Example:To list out the names of the manger with the employee record one will have to join EMP with itself Select Worker.ename,Manager.ename "Manager" from emp Worker , emp Manager where Worker.mgr=Manager.empno;

List all employees who joined the company before their manager Select e.ename,e.hiredate,m.ename manager , m.hiredate From emp e, emp m WHERE e.mgr=m.empno and e.hiredate< m.hiredate

SET Operators :SET Operators are used to combine


information of similar type from one or more than one table. Datatype of corresponding columns must be the same The types of SET Operators are:
UNION:Rows of the first query plus rows of the second query, less duplicate rows INTERSECT:Common rows from all the queries MINUS :Rows unique to the first query

SET operator combine two or more queries into one result. Suppose we want following three details from dept table
List of all the different designations in department 20 and 30 List the jobs common to department 20 and 30 List the jobs unique to department 20 To get these combination of information the SET operators

UNION:
The union clause merges the outputs of two or more queries into single set of rows and columns. Syntax: Select <stmt1> UNION Select <stmt2> [Order BY clause]
Display the different designations in department 20 and 30

Select job from emp where deptno=20 UNION Select job from emp where deptno=30

Points to kept in mind:


The two select statement may not contain an ORDER BY clause,however the final result of the entire UNION operator can be ordered The no. of columns retrieved by the first select must be equal to no. of cols. retrieved by the second statement. The data types of cols retrieved by the select statement must be same Select empno,ename from emp where deptno=20 UNION Select empno,ename from emp where deptno=30 Order by 1

INTERSECT
The INTERSECT operator returns the rows that are common between two sets of rows. Syntax: Select <stmt1> INTERSECT Select <stmt2> [Order BY clause]
Display the jobs common to department 20 and 30

Select job from emp where deptno=20 INTERSECT Select job from emp where deptno=30

MINUS:
The MINUS returns the rows unique to first query. Syntax: Select <stmt1> MINUS Select <stmt2> [Order BY clause]
Display the jobs unique to department 20
Select job from emp where deptno=20 MINUS Select job from emp where deptno=10 MINUS Select job from emp where deptno=30

NESTED QUERIES
If we want List Employees belonging to department of MILLER:
We have to use two query statements,first of all we have to do determine the department number of MILLER like: SELECT deptno from emp where ename=MILLER; Then we will use the the deptno to find out the other Employees something like: SELECT ename from emp where deptno=10; We can combine the above two query statements into single something like: SELECT ename from emp where deptno=(SELECT deptno from emp where ename=MILLER);
THIS IS NESTED QUERY i.e; Query inside another QUERY

SQL has an ability to nest queries within one another.A subquery is a SELECT statement that is nested within another SELECT statement and which returns intermediate results .SQL first evaluates the inner query (subquery) within the WHERE clause .The inner query generates values that are tested in the predict of the outer query ,determining when it will be true.The return value of inner query is then substituted in the condition of the outer query.

Advantages:
Subqueries allows a developers to build powerful commands out the simple one. The nested queries is very useful when you need to select rows from a table with a condition that depends on the data in the table itself.

List the names of the employee drawing the highest salary: Select ename from emp where sal=(select max(sal) from emp); List all employee details whose salary is greater than average salary of employees whose hiredate is before 01APR-1981: Select * from emp where sal > (select avg(sal) from emp where hiredate <01APR-1981);

DISTINCT clause: It use to force the query to return single value. Select * from dept where deptno=(select distinct deptno from emp where mgr=7698); Subqueries that return more than one row: List of employees, who earn lowest salary in each department: SELECT ename,sal,deptno from emp where sal IN(SELECT MIN(sal) from emp group by deptno);

Points to be kept in MIND


The inner query must enclosed in parenthesis The inner query must be on the right hand side of the condition. The subquery may not have an order by clause . The ORDER BY clause appears at the end of the main SELECT statement. Subqueries are always executed from the most deeply nested to the least deeply nested.

Correlated SubQuery: A correlated subquery is a


nested subquery which is executed for each candidate row considered by the main query and which on execution uses a value from the column of the outer query. In a correlated subquery , the column value used in inner sub query refers to the column value present in the outer query forming a correlated query .The subquery is executed repeatedly , one for each row of the main (outer) query table.
Employees earn salary greater than the average salary for their dept: SELECT empno,ename,sal,deptno from emp e where sal >(select AVG(sal) from emp where deptno=e.deptno);

Correlated subquery is used to answer multi-part questions whose answer depends on the value of each row of the parent query.The inner select is normally executed once for each candidate row.

Special Operators in Subqueries EXISTS: Used to check the existence of values Produces Boolean result ANY,SOME and ALL: Used along with relational operators Similar to IN ,but only used in subqueries The SOME and ANY can be used interchangeably

EXISTS:
List all employees who have at least one person reporting to them: SELECT empno,ename,job,deptno from emp e where EXISTS (select empno from emp where emp.mgr=e.empno); List the employee detail if any and only if more than 2 employees are present in department number 10: Select * from emp where deptno= 10 and EXISTS ( select count(*) from emp where deptno=10 GROUP BY deptno HAVING COUNT(*) > 2); List all employees details who do not manage any one: SELECT ename,job from emp e WHERE NOT EXISTS (Select mgr from emp where mgr=e.empno);

ANY Operator:It

compares the lowest

value from the set List the employee names whose salary is greater than the lowest salary of an employee belonging to department number 20: SELECT ename from emp where sal > ANY(select sal from emp where deptno=20); List the employee details of those employee whose salary is greater than any of the managers: SELECT empno,ename,sal from emp where sal > ANY(select sal from emp where JOB=manager);

ALL Operator: In

case of ALL operator the predicate is true if every value selected by the subquery satisfies the condition in the predicate of the outer query. Example: List the employee names whose salary is greater than the highest salary of all employee belonging to department number 20: Select ename from emp where sal > ALL (select sal from emp where deptno=20);

FUNCTIONS They are used to manipulate data items.


Advantages: Perform complex calculations on data Can modify individual data items Can very easily manipulate output for group of rows. Can alter date format for display Types: Single Row Function(Column Function) Group Function

DUAL TABLE
DUAL table is a table with only one row and column in it.It is owned by SYS and can be accessed by all users.It contains one column, DUMMY and one row with value X.The DUAL table is useful to return a value only once-for instance , the value of a constant , psuedo_column or expression that is not derived from a table with user data. Desc DUAL;

Column Functions:As they work on columns. They are: Arithmetic Functions: ABS(n):Returns absolute value of the column or values passed SELECT ABS(-65) from dual; CEIL(n):Finds the smallest integer greater than or equal to n. Select CEIL(89.9) from dual; FLOOR(n):Finds the largest integer less than or equal to n. Select FlOOR(89.9),CEIL(89.9) from DUAL;

MOD(m,n):Returns the remainder of m divided by n ; or m if n=0 SELECT MOD(200,30) from dual; POWER(m,n):Returns m raised to power n Select power(2,2) from DUAL; SIGN(n): Returns 1 if n is negative, it returns 1 if n is positive and it returns 0 if n is 0. Select sign(-1) from dual; SQRT(n):Returns square root of n. Select sqrt(81) from dual; trunc(m,[n]):This truncates the m or column to n decimal places .If n is omitted then it is truncated to no decimal places.If n is negative then numbers left of decimal places are truncated to 0; Select trunc(90.723,1), trunc(90.723,-1), trunc(90.723)

ROUND(m,[n]):This rounds the m or column to n decimal places .If n is omitted then it is rounded to no decimal places.If n is negative then numbers left of decimal places are rounded to 0; Select round(90.723,1), round(90.723,-1), round(90.723) from dual; EXP(n):This returns e raised to the nth power. Select exp(4) from DUAL;

Character Functions
Working with characters
CHR(x):Returns the character given to character number Select chr(65) from DUAL; ASCII(x):Returns the ASCII value of given character Select ASCII(A) from DUAL; CONCAT(str1,str2):Returns str1 concatenated with str2. Select concat(Anu,Rag) from DUAL; INITCAP(string):Capitalize the first character of each word in the string. Select initcap(anurag) from dual; LOWER(string):Converts string to lower case. SELECt lower(ANU) from DUAL;

UPPER(string):Converts string to upper case. Select upper(anu) from DUAL; LPAD(char1,n[,char2]):This fills(pads) the column value from left , to a total width of n characters positions.The leading spaces are filled with char2.If string is omitted value is padded with spaces. Select lpad(dname,15,$),lpad(dname,15, ) , dname from dept; RPAD(char1,n[,char2]):This fills(pads) the column value to the right , to a total width of n characters positions.The trailing spaces are filled with char2.If string is omitted value is padded with spaces. Select rpad(dname,15,$),rpad(dname,15, ) , dname from dept;

LTRIM(string,char/s):Removes all blank spaces from the left .If char/s is specified it removes from the left leading occurrences of char. Select dname,LTRIM(dname),LTRIM(dname,R) from DEPT; RTRIM(string,char/s):Removes trailing occurrence(s) of all blank spaces .If char/s is specified it removes from the right trailing occurrences of char. Select dname,RTRIM(dname),RTRIM(dname,S) from DEPT; REPLACE(string,search_str[,replace_str]):This returns string with every occurrence of search_str replaced with replace_str.If replace_str is not specified, all occurrences of search_str are removed. Select replace(This and That,Th,B) from dual; Select replace('This and That','Th') from dual;

SUBSTR(string,m[,n]):Returns substring, n characters long from the string specified, starting at position number m .If n is not specified the string is extracted from position m to end. Select dname , SUBSTR(dname,2,4) , SUBSTR(dname,4) from dept; TRANSLATE(string,from_str,to_str):This returns string with all occurrences of each character in from_str replaced by corresponding character in to_str. select translate(abcdefghij,abcdef,123456) from dual; select translate('abcdefghij','abcdefghij','123456') from dual;

INSTR(string,char):Returns position of first occurrence of char in string. Select dname,instr(dname,e) from dept; LENGTH(string):Returns length of string. Select length(Anu) from dual;

They are used to manipulate date.All date function returns a value of DATE data type except MONTHS_BETWEEN which returns a numeric value. SYSDATE:It is a psuedo-column that returns the current date and time of type DATE.The SYSDATE can be used just as any other column name. SELECT SYSDATE from DUAL; ADD_MONTHS(d,n):Adds or subtracts to or from a date.Returns date as result Select hiredate , add_months(hiredate,4) , add_months(hiredate,-4) from emp;

Date Functions

Click Me for Date Format


Select to_char(14-AUG-96,RM) from DUAL; SELECT TO_CHAR(TO_DATE('12-APR-71 13:21:00 , 'DD-MON-YY HH24:MI:SS'),'HH:MI') FROM DUAL

ROUND(d[,format]):Rounds date d to the unit specified by format.If format is not specified, it defaults to DD,which rounds d to the nearest day. Select round(to_date(14-AUG-76),MM) from Dual; TRUNC(d[,format]):This function returns the date d truncated to the unit specified by format.If format is not specified, it defaults to DD,which truncates to the nearest day. Select trunc(to_date(14-AUG-76),MM) from Dual; MONTHS_BETWEEN(d1,d2):Returns number of months between two dates,d1 and d2.If d1 is later than d2,the result is positive,if d1 is earlier than d2 ,the result is negative.The output will be a number. Select months_between(02-FEB-02,02-AUG-02), months_between(02-AUG-02,02-FEB-02) from dual;

LAST_DAY(d):Returns the date of the last day of the month specified.The result will be a date. SELECT sysdate,last_day(sysdate) from dual; NEXT_DAY(date,day):Returns the date of next specified day of the week after the date. SELECT sysdate,next_day(sysdate) from dual; TO_CHAR(d,f):this function converts the date d to character format f. SELECT sysdate,TO_CHAR(sysdate,DAY) from dual

GENERAL FUNCTIONs
GREATEST(expr1[,expr]):This returns the greatest expression of its arguments. Select greatest(10,7,-1) from dual; LEAST(expr1[,expr]): This returns the least value in the list of expressions. Select least(10,7,-1) from dual; NVL(col,value):The columns with NULL values are ignored in all of the group functions such as SUM,AVG etc.Also in arithmetic expression ,if the column contains NULL ,will not provide any useful information.The NVL function helps in substituting a value in place of a NULL.The data type of the value to substituted must match with col data type Select ename,sal,comm,sal+comm GROSS ,sal+NVL(comm,0) New Gross from emp;

TRANSLATE(char,find,new):This function returns char with each find changed to new.All occurrences of find are replaced with corresponding character in new.If corresponding new character is not supplied,then find char is removed. Select dname,translate(dname,e,l) from dept; DECODE(C,V1,S1,V2,S2,,D):This function does a ifthen-else.A default value can also be specified with DECODE function,which is substituted,in case nothing matches from the set.C which is either column or expression is compared to each V and substitutes S if C equals the search value.If no match is found , the DECODE function returns the D which is default value.If default value is omitted ,NULL is returned for unmatched values. Select ename , job , DECODE(job,CLERK,EXEC, MANAGER,RM,job) from emp;

UID:this returns an integer that uniquely identifies the current database user.It takes no arguments. SELECT UID from dual; User:this returns a VARCHAR2 value containing the name of the current Oracle user.USER takes no arguments. SELECT USER from dual;

SEQUENCES A sequence is database


object used to generate unique integers for use as primary keys.

Syntax:
Create SEQUENCE <seq-name> INCREMENT by <n>] Start with <m>] MAXVALUE N|NOMAXVALE] MINVALUE N|NOMINVALUE] Where: <seq-name> name of sequence <n> increment specified by user Start with number with which the sequence will begin MINVALUE lower bound

CREATE SEQUENCE empnumber INCREMENT BY 1 START WITH 1;

Generating Sequence Numbers:


A pseudo column NEXTVAL is used:
Select empnumber.NEXTVAL from dual;

Use in table: create table checking (id number(5),name varchar2(10));


insert into checking values( empnumber.NEXTVAL , 'Anu');

select * from checking; Output: ID NAME --------- ---------1 Anu

insert into checking empnumber.NEXTVAL , Dipti'); select * from checking; Output: ID NAME --------- ---------2 Dipti

values(

Checking Current Value :


The pseudo column CURRVAL is used for this purpose.It tells the last value. Select empnumber.CURRVAL from dual;

To see list of SEQUENCES created by user:


Select * from USER_SEQUENCES;

Altering SEQUENCES:
Alter SEQUENCE <seq-name> INCREMENT by <n>] MAXVALUE N | NOMAXVALE] MINVALUE N | NOMINVALUE] ALTER SEQUENCE empnumber INCREMENT BY 2; NOTE:This alter sequence command will not affect the sequence number created earlier.Only future sequence numbers are affected by the ALTER SEQUENCE statement.START WITH value cannot be changed using ALTER .The sequence must be dropped and recreated in order to restart a sequence at different number. Removing SEQUENCES: Drop sequence <seq name> Drop sequence empnumber;

You might also like