You are on page 1of 38

SQL Commands:

-----------------------

Create: - Create tables and other system objects (DDL)

Syntax:
Create Table <table-name> (<column-name> <data type> (<width>) , … );

Example:-
Creating a table named Employee with fields Employee No, Employee Name, Designation,
Department , Salary and date of Birth.

Create table Employee


(
Empno int,
EmpName varchar(20),
Designation varchar(20),
Department varchar(20),
Salary decimal,
DOB Date
);

To display the table structure:

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='Employee'

OR

sp_columns 'Employee'

Insert (DML):-

Enter the data into the table row by row

Syntax:

Insert into <table-name> (column-name,...) values(<value1>,...);

Note : if values are inserted into all coulmns in the correct order then there is no need to specify
the column names
Insert into <table-name> values(<value1>,...);

Example:

Insert into Employee values (1,'Anil Kumar', 'Clerk','Sales',4500,'12-jun-1981');

Inserting data to selected columns only

Insert into Employee ( EmpNo, EmpName,DOB)values(1,'Ashok Das','13-May-1989');

Creating 5 rows in the table :-

Insert into Employee values (1,'Bob', 'Clerk','Sales',5700,'18-jan-1984');


Insert into Employee values (31,'Joe', 'Clerk','Production',7400,'21-jan-1977');
Insert into Employee (EmpNo, EmpName, Designation, Department) values (4,'Haritha Nair',
'Officer','HR');
Insert into Employee (EmpNo, EmpName, Designation, Department) values (5,'Chandra
Kumar', 'Officer','Sales');
Insert into Employee values (6,'Mahnohar', 'Officer','Accounts',14000,'28-feb-1974');
Insert into Employee values (7,'Satyan', 'Manager','Production',6760,'11-aug-1986');
Insert into Employee values (17,'Anila Jhon', 'Manager','Production',6760,'11-aug-1986');
Insert into Employee values (18,'Ashok', 'Manager','Production',6760,'11-aug-1986');

Select (DQL): -

Select statement is used to perform query operations in your database tables

Syntax:-

Select */column-name1 ,column-name2, .. , .. from <table-name>;

to display all the column values of the table

Select * from <table-name>;

Example :

Select * from Employee;

Displaying selected columns only

select EmpName, Designation,Department from Employee;


Alter (DDL)-

Alter command is used to modify the structure of an existing table which may or may not have
data , the alter command has certain limitations.

Syntax;-.

Alter table <table-name> add/modify column-name datatype(<width>);

Example

Adding a new Column:


Alter table Employee add experience int;

Modifying a Column:
Alter table employee Alter Column empname varchar(25);

Removing an Exiting Column:


Alter table employee drop Column experieance;

Limitations of the Alter Command

1. New columns can be added to the tables


2. Existing columns cannot be renamed
3. Existing column order cannot be changed
4. Column data type can be changed only if there no values existing for all rows for that column.
5. Column width can be increased at any time , but can decrease the width if the column data
width is less than new width for all rows of the table.

Drop (DDL)-
Drop command is used to remove a table from the database.

Syntax:-
Drop table <table-name>;

Example

Drop table Employee;

Virtual Columns: -

Virutal columns defines values which are generated by the system when an sql command is
executed, these values can be selected like any other columns for any table.
example to display the system date in MsSQL.

select GetDate();
select CONVERT(varchar,CURRENT_TIMESTAMP , 106) ;

to dislay the system time in different formats:-


select CONVERT(nvarchar, GETDATE(),14) ;
select CONVERT(nvarchar, GETDATE(), 24) ;
select RIGHT(CONVERT(nvarchar(30), GETDATE(), 22),11);
select RIGHT(CONVERT(nvarchar(30), GETDATE(), 0),6);

to resolve a mathematical expression in the sql environment.


select 10*4;

to display the name and age of all employees in the employee table
select EmpName,Designation,Department , salary, salary*0.1 as HRA, salary*0.25 as DA from
Employee;

Column aliasing - Each column selected from a select query can have a temperory display
name which is known as
column alias , above example 'DA' and 'HRA' are aliased column.

Example:

To select the employee name , department, designation and salary , 10% of salary as HRA ,
25% of salary as DA and sum of HRA,DA and Salary as
netpay from the employee table.

select EmpName as Name , Department,Designation, Salary, Salary*0.1 as HRA , Salary*0.25


as DA, Salary *1.35 as "Net Salary" from Employee;

selecting a details of employees from the table in a text mode, ie wishing a merry christmas.:-

Select 'Hello ' +EmpName+' , wish you a merry chirstmas and happy new year' from Employee;

Example-2

Select EmpName + ' is working as ' + Designation + ' in the ' +Department+ ', Department and
his Salary is '+
LTRIM(STR(Salary)) As 'Details ... ' from Employee;

Where Clause :-
Where clause is used to filter a query fetched by any DML /DQL command of SQL.

syntax with select statment


select */<column-name> ,.. from <table-name> where <condition>

example :-

To display the details of all employees working in the sales department

select * from Employee where Department='Sales';

To display the Employee Name, Designation and Depratment of all Officers


select EmpName, Designation,Department from Employee where Designation='Officer';

To display the Employee Name, Designation and Depratment ,Salary of all Employees with
salary equal or above 5000.
select EmpName, Designation,Department from Employee where Salary >=5000;

To display the Employee Name, Designation and Depratment ,Salary of all Employees born
before 1980.
select EmpName, Designation,Department ,Salary ,DOB from Employee where DOB <
'1-Jan-1980';

To display the Employee Name, Designation and Depratment ,Salary of all Managers born
before 1980.
select EmpName, Designation,Department ,Salary ,DOB from Employee where DOB <
'1-Jan-1980' and Designation='Clerk';

To display the Employee Name, Designation ,Depratment and Salary of all Officers and Clerks.
select EmpName, Designation,Department ,Salary ,DOB from Employee where
Designation='Officer' or Designation='Clerk';

To display the Employee Name, Designation and Depratment ,Salary of all Employee with
salary between 5000 and 8000.
select EmpName, Designation,Department ,Salary ,DOB from Employee where salary>=5000
and salary <=8000;

Same solution using BETWEEN operator(logical):


select EmpName, Designation,Department ,Salary ,DOB from Employee where salary
BETWEEN 5000 and 8000;

Negatate the above query:-


select EmpName, Designation,Department ,Salary ,DOB from Employee where salary NOT
BETWEEN 5000 and 8000;

To display the Employee Name, Designation and Depratment ,Salary of all Employee execpt
clerks and officers.
select EmpName, Designation,Department ,Salary ,DOB from Employee where
Designation<>'Officer' and Designation<>'Clerk';

Same solution using Not Operator(logical):


select EmpName, Designation,Department ,Salary ,DOB from Employee where Not
(Designation='Officer' or Designation='Clerk');

IN clause:
To Display the details of employees working in Sales,HR and Accounts Department

select EmpName, Designation,Department ,Salary ,DOB from Employee where Department IN


('HR' ,'Sales','Accounts');

NOT IN clause

To Display the details of employees not working in Sales,HR and Accounts Department

select EmpName, Designation,Department ,Salary ,DOB from Employee where Department


NOT IN ('HR' ,'Sales','Accounts');

Like clause:

Like clause is used to search text data using widcard characters (pattern searching in oracle)

% - represent all letters of any length;


_ -underscore - represent a single letter.

To display the detials of Employees having names begning with 'A'

select * from Employee where EmpName Like 'A%';

NOT Like

Fetch the rows which does match the cirteria

select * from Employee where EmpName NOT LIKE 'A%';

More pattern searching commands


Dispaly the details of Employees who have 3rd letter in the name as a.
select * from Employee where EmpName like '__a%'

Display the details of all employees with empname ending with 'r'
select * from Employee where EmpName like '%r'

Display the details of all employees with "ni" anywhere in the name.
select * from Employee where EmpName like '%ni%'

Display the details of all employees with exactly 3 letters in their name or less than 3.
select * from Employee where EmpName like '___'

IS operator

Is operator is used to compare a column or expression against a null value.

select * from employee where salary is NULL;


select * from employee where salary IS NOT NULL;

Update statment (DML)


Update statement is used to modify the values of any existing rows

Syntax:
Update <table-name> set <column-name>=<value>, <column-name>=<value> [where
<criteria-statement>]

example:-

Modifying the DOB and Salary of the employee no 4.

Update Employee set salary=4450, dob='29-Aug-1987' where empno=4;

update the salary of all Officers to 10000


update Employee set salary=10000 where Designation ='Officer';

Note :
Update command without a where clause update the details for the entire table.

Increment the salary of all employees by 1000;


update Employee set salary=salary+1000;
Increment the salary of Shyam by 25%
update Employee set salary=salary*1.25 where empname='Shyam';

Delete (DML)
Delete command is used to remove a column from the table, Delete statment without a where
clause removes all rows of a table.

Syn :

Delete <table-name> [where <cirteria>]

Example
Delete the details of Anila

Delete employee where empanme like '%Anila%';

Truncate

Truncate removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such,
Truncate is faster and doesn't use as much undo space as a DELETE.

TRUNCATE TABLE <table-name>;

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.

Creating a new Table from an existing table:-

Syntax :
Select */<column-name>,.. into <table-name> from <table-name>

Examples

1. with all rows


select * into employee1 from employee where department='Sales'

2. with selected rows


Select empno,empname,salary,dob into employee2 from employee;

3. without data (only structure)


select int employee3 select * from Employee where 1=2;
Copy data from one table to another table:-
Data can be copied from one table to another

Syntax :
insert into <target-table> select * from <source-table> [where <criteria>];

example -
create table worker(wrk_id number(5),wrk_name varchar(30));
insert into worker (wrk_id,wrk_name) select empno,empname from employee;

IDENTITY COLUMN

Creates an identity column in a table. This property is used with the CREATE TABLE and
ALTER TABLE Transact-SQL statements.
IDENTITY property for an automatically incrementing identification number.

Syntax
IDENTITY [ ( seed , increment ) ]

example

CREATE TABLE new_employees


(
id_num int IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
)

INSERT new_employees (fname, minit, lname)VALUES ('Karin', 'F', 'Josephs');


INSERT new_employees (fname, minit, lname)VALUES ('Pirkko', 'O', 'Koskitalo');

Functions :-

SQL supports two types of functions that is normal functions and aggergate
functions.

Normal functions are similar the built-in functions in other langauges and packages, these
functions
are catogrised into 1)Numeric 2)String and 3) Date functions
Aggergate functions are applied to multiple rows for a table /query examples are
sum(), avg(),count(),min(),max() etc. these functions fetches only one row from a table.

Example

Numeric functions :-

Abs()- returns the absolute value of X. Consider the following example:


select abs(34);

Ceiling() - return the smallest integer value that is not smaller than X.
select ceiling(34.566789) ;

floor() -extracts the integer part of a numeric value


select floor(34.89);

round() -
select round(34.89,0); rounds to integer
select round(56.7891,2);

exp()
SELECT EXP(4) "e to the 4th power" FROM DUAL;

sqrt() -returns square root of the parameter value.


SELECT SQRT(4);

square() -returnsthe square


SELECT SQUARE(4);

power() -return the Nth power of M


select power(3,4);

log() -log to a specific base


SELECT LOG(10)

Cos(), Sin(),Tan(),Cot(), radians(),degrees(),acos(),asin(),atan() -trignometric functions

select sin(90);
select cos(90);
select tan(90);
select cot(90);
select radians(90);
select degrees(3);
select asin(-1);
select acos(-1);
select atan(-1);

pi() -returns the pi value constant.


select pi();

sign() -returns the sign of the number 1 for +ve numbers , -1 for negative numbers
SELECT SIGN(-100)

rand() -returns a random number for 0.1 to 1,Repetitive calls of RAND() with the same seed
value return the same results.
select rand();

Charcter functions:

Char() -return the charcter equivalent of the ASCII value (1-256) passed as parameter to the
function
SELECT char(67);

NChar() -return the charcter equivalent of the ASCII and supplymentry characters value
(1-65535) passed as parameter to the function
SELECT nchar(1167);

ASCII () -returns the ascii value of the charcter passed as parameter


SELECT ASCII ('a') ;

Space(n) -returns a string formed by n number of white spaces


Select 'Hello' + space(15) + 'Boy'

CharIndex(n,m) -returns the first occurence of the character N within the string M.
Select CHARINDEX('llo','Hello')

PatIndex(n,m) -returns the first occurence of the pattern N within the string M.
Select CHARINDEX('%llo%','Hello')

Str(n,m) -Coverts the given expression N to a string data type with width M (optional)
select STR(345,3)

Stuff(exp1,n,m,expr2) - Inserts a string expr2 in expr1 from nth position in expr1


by overwriting m characters of expr1.

select STUFF('He is a Good Boy',9,4,'Bad');


select Stuff('She is a girl' ,10,0,'clever ');

Replace(expr1,expr2,expr3) -Relpaces expr2 with expr3 in the string expr1.


select REPLACE('He is a Good Boy','Good','Bad')

Replicate(expr1,n) - returns string with expr1 one concated n times


select REPLICATE('-',50);
select empname,replicate('*',floor(salary/100)) as 'salary' from employee;

Upper() -Returns the string passed as parameter in upper case.


select upper('roger michel HUMPERY binnY');
select upper(EmpName) as EmpName, upper(Department) as Department, Upper(Designation)
as Designation from Employee;

convert all employee names ,department and designation to uppercase in employee table.
update employee set empname=upper(empname), designation=upper(designation),
department =upper(department);

Lower() -Returns the string passed as parameter in lower case.


select lower('roger michel HUMPERY binnY');
select lower(EmpName) as EmpName, lower(Department) as Department, lower(Designation)
as Designation from Employee;

convert all employee names ,department and designation to lower case in employee table.
update employee set empname=lower(empname), designation=lower(designation), department
=lower(department);

Ltrim() -Truncates the leading white spaces in a string


select ltrim(' Ashok Hari');

Rtrim() -Truncates the trailing white spaces in a string


select Rtrim('Ashok Hari ');

to remove both leading and trailing white space from a character value.
select * from employee where ltrim(rtrim(empname))='Sunil Kumar';

Left(expr1,n) - return the first n characters of expr1.


select left('Narayana',4);

Right(expr1,n) - return the last n characters of expr1.


select right('Narayana',4);

Substr() -Returns the sub string of the first parameter string ,starting postion as value defined
and second parameter and the no of characters as value of third parameter

select substr(<string-value>,N,M) from <schema>


extracts M characters starting from Mth position

example
select substr('HariNarayanadas',5,6);

To display empname, first 3 characters of deptarment and designation


select empname, substring(department,1,3) as Dept , substr(designation,1,3) as design ,salary
from employee;

len() -returns the no of letters in the string passed as the parameter


select empname,len(empname) from Employee;

combining a functions :Dennis


to display the last 4 chars of the empname.
select empname, substr(empname,len(empname)-3 ,4) from employee;

Replace() -repalace the output string with the pattern provided as the 3rd parameter as pattern
provided as the 2nd parameter in the string.

syn
select Replace (<string-value>, <pattern-value1>,<pattern-value2>) from <schema>
replaces pattern-value1 with pattern-value2 in the string value.

example
select Replace ('Mangalore City','City','Central') from dual;

update employee set Department = replace(Department, 'sales','Sales and Marketing');

Reverse(expr1) -Reverse the string expr


select REVERSE('Doctor')

Date Functions:-

Getdate() -Returns the current system date;


Select getdate();

Year() -returns the current year;


select Year(getdate());

Month() -returns the current month;


select Month(getdate());

Day() -returns the current day;


select Day(getdate());

DateDiff(interval,d1,d2) -returns the date as <interval> between d1 and d2

To display the age of all employees as per the system date.


select empno, empname,DATEDIFF(year,dob,getdate()) as 'Age' from Employee;

To find out how many days for chirstmas.


select DATEDIFF(days,getdate(),'25-Dec-2015');

DateAdd(interval,m,d1) -returns the date as "m" "intervals" from date d1.


select DATEADD(MM,6,GETDATE())

To find the date 100 days before the current date.


select DATEADD(DD,-100,GETDATE())

To find the date 2 weeks from the current date.


select DATEADD(Week,2,GETDATE())

To find the date 100 HOURS from the current date.


select DATEADD(hh,100,GETDATE())

To find the date 100 Minutes from the current date.


select DATEADD(minute,100,GETDATE())

DateName(interval,d1) -returns the date name in words for date "d1" as per the "interval" .

To display the current weekday name:


select DateName(WeekDay,GETDATE())

To display the current month name:


select DateName(Month,GETDATE())

To display the current month name:


select DateName(Month,GETDATE())

DatePart(interval,d1) -returns the date part for date "d1" as per the "interval" .

To display the current year :


select DatePart(year,GETDATE())
To display the current month:
select DatePart(Month,GETDATE())

To display the current day of the month:


select DatePart(Day,GETDATE())

To display the current day of the current week (1 is sunday, 2 is monday,..):


select DatePart(DW,GETDATE())

To display the current week of the current year


select DatePart(Week,GETDATE())

To display the current day of the current year


select DatePart(DayofYear,GETDATE())

To display the current Hour


select DatePart(HH,GETDATE())

To display the current minute


select DatePart(MM,GETDATE())

To display the current Second


select DatePart(SS,GETDATE())

isDate(d1) -returns 1 if the given expression d1 is a valid date otherwise 0


select ISDATE('2015/01/01 12:00:00')
select ISDATE('Ramu')
select ISDATE(200)

Aggregate Functions:-
Aggregate functions are used to extract the aggergate values from a group of data in a table,
SQL supports
the following aggergate.

sum(),avg(), min(), max(), count()

Note:-
Only sngle column can be selected , aggergate functions will fetch only a single row from a
table.

example:-
To find the sum of the salary of all employees in the employee table.
select sum(salary) as "total salary" from employee;
select sum(salary) as "total salary" , avg(salary) as "average salary" from employee;

To find the total number of officers in the company

select 'Officer' as "Job", count(*) as "Employees" from employee where


upper(designation)='OFFICER';

Display the highest and lowest salary in the Employee table.


select max(salary) as "Highest" , min(salary) as "Lowset" from employee;

Group By -

Group by clausing is used to display the aggergated columns grouped for a specific
column-value.

example:-

To find the department wise count of employees from the employee table.
select department, count(*) as "Total Employees" from employee group by department

To find the designation wise count of employees from the employee table.
select designation, count(*) as "Total Employees" from employee group by designation

Multiple grouping

To find the departmentwise and designation wise count of employees from the employee table.
select department, designation, count(*) as "Total Employees" from employee group by
department, designation

Order by -
Order by clause is used to sort the query with respect to any column, the column must be
selected in the
select query ,if order by used in conjuction with group by clause order by must follow group by.

examples
select * from employee order by empname;

Display the employee details sorted on department then by deisgnation (within each
deepartment)
select * from employee order by department,designation;
DESC

used in conjuction with order by clause, to sort in the descending order , system will sort
columns on
ascending order by default.

example
select * from employee order by empname desc;

sorts department in ascending order and designation in descending order.


select * from employee order by department, designation desc;

Having clause:-
Having clause is used by queries using aggergate functions , i.e if you want to compare
an aggergate function you must use having instead of where clause

example
to display departmentwise total salary for total salary above 10000.
select department, sum(salary) from employee group by department having sum(salary)
>10000

usage WHERE and HAVING together in a query statement.

Always where clause must be provided before group by --having clause.

select department,sum(salary) from employee where department <> 'Accounts' group by


department having sum(salary) <20000;

Using all aggergate functions in one query.

select department, count(salary), sum(salary), avg(salary) , max(salary) , min(salary) from


employee group by
department;

Sub Queries :-

Sub Queries as used in the WHERE clause of another query statment or an


insert/update/delete
statement to identified more complex information from the tables/queries.

example

To get the details of all employees with salary lower than that of wilson's , wilson's salary is
unknown.

select empname,department,designation ,salary from employee where


salary <= (select salary from employee where empname='Wilson');

To display the details of employee drawing the highest and lowest salaries.

select empname,department,designation ,salary from employee where


salary =(select max(salary) from employee);

To display the department and total salary where total salary is highest.

select department,sum(salary) from employee group by


department having sum(salary) =(select max(salary) from employee group by department);

DISTINCT keyword
DISTINCT keyword is used to identify the unique rows from a query , i.e supress the duplicate
values.

example-
display all departments from the employee table

select DISTINCT department from employee;


select DISTINCT department,designation from employee;

INTERSECT,UNION keywords

examples

select * from Employee where department in('hr','accounts')


INTERSECT
select * from Employee where department in('accounts','production')

Displays the details all employees working in the departments mentioned in the query, but
will supress duplicate data.

select * from Employee where department in('hr','accounts')


UNION
select * from Employee where department in('accounts','production')

select Initcap(empname),salary from employee


UNION
select 'total salary', sum(salary) from employee;

Displays the name & salary of all employees with total salary and summary of salary
as last row.

Note : Intersect,UNION and minus will sort the consolidated queries with respect to the first
column.
so the summary may not display in the last row unless you give the salary as first column.

SQL JOINS
=========
SQL Joins are queries which fetches relational data from two or more independent sql tables
using one or more common common key fields, in oracle the joins are
classied into three namely

1.equi-joins /inner-joins

2. outer joins
left outer joins
right outer joins
full other joins
3. self-joins

equi joins:-

Display the data if the data is exists in both tables , it is also known as simple inner joins.

create a table personal which stores an extension of the data of the employees
such as spouse, qualification and bank account number

create table personal


(
empno number(5),
spouse varchar(20),
qual varchar(20),
accNo number(5)
);

insert into personal values (32,'Manjunath','BsC Maths', 11319);


insert into personal values (44,'Ramdas','BE Electronics', 13014);
insert into personal values (76,'Kris Achari','BE CS', 11114);
using the inner join to display the data in employee & personal tables;

select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee inner join personal on employee.empno=personal.empno;

Outer Joins

1. Left outer joins

Displays all the data of the first table but only the matching data of the second table

example:

select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee left outer join personal on
employee.empno=personal.empno;

2. Right outer join

Works excatly opposite of left outer joins i.e Displays all the data of the second table but only
the matching data of the first table

select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee right join personal on employee.empno=personal.empno;

3.Full outer join

Full outer joins is a unioin of both left and right outer joins , i.e Displays all the data of both
tables.

select employee.empno,empname,department,designation,salary,dob,doj,
spouse,qual,accno from employee full join personal on employee.empno=personal.empno;

4. Self -Joins

self joins are used to join the single table to itself in some cases like

assue a table employee with the following data

empno empname mgrNo


1 Ajeesh 6
2 Tanseer 6
3 Akhil 7
4 Dhanya 7
5 Bhavya 3
6 Prasad 7
7 Sujith

create table empdata


(
emp_no number(5),
emp_name varchar(25),
mgr_no number(5)
);

insert into empdata values (1,'Ajeesh',6);


insert into empdata values (2,'Tanseer',6);
insert into empdata values (3,'Akhil',7);
insert into empdata values (4,'Dhanya',7);
insert into empdata values (5,'Bhavya',3);
insert into empdata values (6,'Prasad',7);
insert into empdata (emp_no,emp_name) values (7,'Sujith');

select a.emp_no, a.emp_name,b.emp_name from empdata a left join empdata b on


a.mgr_no=b.emp_no;

INDEXES :-

An index is database object assoicated with a table or a cluster, that helps to increase the data
access speed . By creating an index on one or more columns of a table, you can fetch the data
from randomly distributed rows.Indexes are one of many means of reducing disk I/O .If a table
has no indexes, then the database must perform a full table scan to find a value. A index stores
the column value with a pointer to the location of the correspoding row in the physical storage ,
which a select query is executed with the respective column in the where clause the system
looks the index table identifies the row pointer for the physical location and fetech the row
details . the function is similar to a normal index page given at the begining of any big reference
book which helps a reader to move to the required topic by identifying the page number from the
index page.

Syntax :

Create Index <Index-Name> on <table-name>(<column-name>,..);

example:-

Create index emp_index on employee(empno);


Modifying a Index :-
Alter Index <index-name> [Keyword] [Properties]
Alter index emp_index rename to emp1_index;

Deleting an Index

Syn:
Drop index <index-name>

Example:
Drop index emp1_index;

Unique Indexes - Unique index on a table allows only unique values to be entered for each row
of the table for the mentioned column.

example
create UNIQUE INDEX emp_idx on employee(empno);
once a unique index is created you cannot duplicate the key colum value in the table ,unique
index cannot be created if duplicate values for the keycolumns,already exists in the table.

Clusters:-
-----------
A cluster is a database object that contains data from one or more tables, all of which have one
or more columns in common.
Oracle Database stores together all the rows from all the tables that share the same cluster key.

Creating a cluster

Syntax:
Create Cluster <clustername> (<column-name>(<data-type>) [sort])

example:
Create Cluster inventory (itemcode number(5));

to view the cluster information


select * from user_clusters;

Indexing a cluster:
Create Index idx_iventory on CLUSTER inventory;

Adding tables to a cluster:-


Create table item_master
(
itemcode number(5),
itemname varchar(20),
company varchar(20),
catagory varchar(20),
opn_stck number(5)
)
Cluster inventory (itemcode);

Create table invoice


(
invNo number(4),
itemcode number(5),
quantity number(3),
rate number(10,2)
)
Cluster inventory(itemcode);

Data Constraints:-
=============
The constraint are rules that restrict the values for one or more columns in a table. The Oracle
Server uses constraints to prevent invalid data entry into tables.

1. Primary Key Constraint


2. Check Constraint
3. Not null Constraint
4. Unique Constraint
5. Foreign Key Constraint

Note : the first 4 constraints are also know as entity constraints (column-level) and the 5th one is
known as
referencial constraint

Primary Key Constraint:

The primary key is a single field or combination of fields that uniquely defines a record. The not
null constraint is part of the primary key. A table can have only one primary key.

example:-

Create table empdata


(
empno number(7) primary key,
empname varchar(20),
salary number(10,2)
);

Note : now for the above table duplicates or blank values for the column empno will not be
allowed. A primary key can be added for the column of any existing table provided the existing
data in the table does not have a
duplicate values for empno.

Removing the primary key constraint from the table


Alter table empdata drop primary key.

Setting an exsting column as primary key


alter table empdata modify empno number(7) primary key;
Note: existing values for a column must be unique and not null.

Add primary key column to an exsiting table


alter table empdata add empid number(7) primary key;
Note:There can be only one primary key for one table.

Check constraint: The check constraint allows you to specify a condition on each row in a table.

create table product_master


(
prod_no number(5) Primary Key,
prod_name varchar(20),
price number(7,2) Constraint chk_price check (price between 1000 and 2500)
);

removing a check constraint :


Alter table product_master drop Constraint chk_price;

Not Null Constraint:

The not null constraint means the column contains no null values. The columns without the NOT
NULL constraint can contain null values by default.

create table product_master


(
prod_no number(5) Primary Key,
prod_name varchar(20) constraint p1 not null,
price number(7,2) Constraint chk_price check (price between 1000 and 25000)
);

Unique Constraint:
The unique constrain means no row value repeat again. The unique constraint is a part of the
primary key.

Note : combination of unique and not null constraints produces the same affect of a primary
key, but system
internally creates index for a primary key which will not happen in case of an UNIQUE NOT
NULL constraint
and primary key can be applied only for one column of the table.

example:

Alter table product_master modify prod_name constraint prod_unq unique;

Table level constraints:

All the above defined cnstraints are column level constraints, a table level constraint is defined
for setting
the integrity rules on the data linking one or more columns of the tables.

examples of table level constraints are following:

Composite Key :
Compostie Key is same as primary key but involves two or more columns of the table as follows

create table emp_dept


(
emp_name varchar(20),
dept varchar(20),
salary number(7,2),
doj date,
Primary key ( emp_name,dept)
);

In the above case system allows duplicate values for empname as well as dept , but not for the
combination.
i.e one employee cannot exists in multiple department.

Check constraint as table level constraint


create table emp_pers
(
emp_name varchar(20),
dept varchar(20),
dob date,
doj date,
constraint c1 Check (dob < doj)
);

Foreign Key Constraint:

The foreign key constraint and references constraint is a same. A foreign key constraint means
that values in one table must also appear in another table. The referenced table is called the
parent table while the table with the foreign key is called the child table. The column refered in
the parent table by the foreign key column must be primary key of the parent table.

example:
create table product_purchase
(
pur_no number(5),
pur_date date,
pur_qty number(5),
pur_rate number(7,2)
prod_no number(5) Constraint fk_prodno references product_master(prod_no);
);

Note: only table name need to be mentioned in the reference clause if column names in both
tables
are identical

Child table of 2 parents.

create table customer


(
cust_id number(5) primary key,
cust_name varchar(20)
)

create table Product


(
prod_id number(5) primary key,
prod_desc varchar(20),
prod_price number(8,2)
)

create table Purchase


(
pur_id number(5) primary key,
cust_id number(5) references customer,
prod_id number(5) references product,
qty number(5),
rate number(8,2)
);

Note:- now you cannot delete both customer and product tables from the database unless you
delete
the purchase table, similary you cannot delete the table rows from customer or product if the
respective
prod_no or cust_no is used in the purchase table.

On Delete Cascade:

Usally system will not allow to delete a row from the master table if the primary key column
value is
used in the child table, you must remove on the dependent rows from the child table before
removing
the row from the master table. in case if you set ON DELETE CASCADE rule for the foreign key
constraint
and if any row from parent table is deleted all dependent rows the the child table will be
automatically deleted

Note :-
Naming a constraint is not mandatory in oracle, if name is not specified system will generate
an internal
name for the constraint which can be identified by running the query

select * from user_constraints;

Constraint name must be known remove a constraint from a table.

VIEWS
======
A view is a predefined, named query stored in the database. Once created, views can be
queried in much the same way that tables can be queried.
Views contain rows and columns like tables do. Views are also known as virtual tables.
Syntax:
Create or replace [FORCE] view <view-name> As <query-statement> [WITH READ ONLY
][With Check Option]

Restrictions:-

1. The subquery cannot select the CURRVAL or NEXTVAL pseudocolumns.


2. If the subquery selects the ROWID, ROWNUM, or LEVEL pseudocolumns, then those
columns must have aliases in the view subquery.
3. If the subquery uses an asterisk (*) to select all columns of a table, and you later add new
columns to the table,
then the view will not contain those columns until you re-create the view by issuing a
CREATE OR REPLACE VIEW statement.
For you to insert into the table using the view, the view must contain all NOT NULL columns of
all tables in the join, unless you have specified DEFAULT values for the NOT NULL columns.

Updateable Views:-
1. An updatable view is one you can use to insert, update, or delete base table rows.
2. A DISTINCT operator, An aggregate function, A collection expression in a SELECT list, A
subquery in a SELECT list, A subquery designated WITH READ ONLY
3. for a join view to be updatable, then all of the following conditions must be true:
a.The DML statement must affect only one table underlying the join.
b.For an INSERT/Update statement, the view must not be created WITH CHECK
OPTION, and all columns into which values are inserted must come from a primary key table.

Examples

Create or replace view empv1as select * from employee where dept='accounts';

to display the views created by the current user:


select * from user_views;

select * from empv1 ;


will display the details of all employees working in the accounts department

note:-
The above created view is updatable , you can update any row in the view as follows

update empv1 set salary=salary+100 where upper(department)='ACCOUNTS';


will increment the salary of all employees working in the accounts department by 100

update empv1 set salary=salary+100 where upper(department)='HR';


will not update any row even though the data exists in the table because the view only hold the
rows belonging to ACCOUNTS department

Insert into empv1 values (212,'Willyx', 'Clerk','Sales',5700,'18-jan-1984','20-feb-06');


The comand will insert a row in the employee table using the empv1 ,but the inserted row will
not be visible in empv1 as department is not ACCOUNTS

Read Only views :-

Create or replace view empv2 as select * from employee where department='Production' WITH
READ ONLY;

Insert into empv2 values (212,'Willyx', 'Clerk','Sales',5700,'18-jan-1984','20-feb-06');


The above command will fail as the view is read only

With Check Option

it will allow an insert or update in the table only if the new row matches the criteria given on view
creation.

Create or replace view empv3 as select * from employee where department='production' WITH
CHECK OPTION;
For the above view you can insert /update the details of employees for production department in
the employee table;

Insert into empv3 values (212,'Willyx', 'Clerk','Sales',5700,'18-jan-1984','20-feb-06');


will fail

Insert into empv3 values (211,'Nelson', 'Manager','production',5700,'18-jan-1984','20-feb-06');


will suceed as the department is production

FORCE View

Normal views can be created only for existing tables, FORCE VIEW allows users to create view
on a table even if the table is
non existant but the query can be performed using the view only after the table creation.

create FORCE view studview as select * from students;

Sub Views -you can create views from existing views as


create view empv2A as select empno, name, department,salary from empv2 where salary
between 5000 and 6000;

Note:
Dropping the table or a parent view from the database will not delete the views dependent on
those tables/parent views.

Deleting a view

Drop View <view-name>


Drop view studview;

Read Only views by default

Views having columns as expressions :-

create or replace view empsv1 as select


empname , salary ,
salary*0.1 as HRA,salary*0.25 as DA,
salary*1.35 as Gross
from employee;

Note :
the Employee Name and Salary can be updated or inserted in the view , HRA,DA and Gross
are read-only.

Delete command applied on a view without a where clause will delete the table data. In such
case to avoid such deletions
create the view WITH CHECK OPTION. but check options will allow to insert new rows into the
view.

Views with aggergate columns

create or replace view empsv2 as select


department, sum(salary) as salary
from employee group by department order by department;

Views with joins from multiple tables;

create table worker(id number(5), wname varchar(20),dept varchar(20));


insert into worker values(1,'Suresh','Sales');

create table pay(id number(5), basic number(10,2),hra number(10,2),da number(10,2));


insert into pay values(1,3450,345,1000);

create or repalce view wrk_pay as


select worker.id,worker.wname,worker.dept, pay.basic,pay.hra,pay.da from
worker inner join pay on worker.id=pay.id;

TCL commands of Oracle (COMMIT,ROLLBACK,SAVEPOINT)

Commit - Updates all the modified transactions to the physical storage system. If autocommit
feature is set for the application commits automatically

rollback - Cancels all the recent chages made the the logical data structure , a rollback can be
performed before a commit.

savepoint -multiple savepoints can be set by the developer within a single session for a
collection of statements executed. rollback to
a save point will undo all actions performed by the user in the database for 1 hour.

example:-

uncheck the autocommit option in the editor and try to insert a few rows as follows

insert into employee values(100,'Suma','Faculty','CS',4000,'1-jan-1972','1-mar-1998');


insert into employee values(101,'Sudessh','Faculty','CS',4500,'1-jan-1967','1-mar-1996');
insert into employee values(100,'Vinod','Manager','Sales',4200,'1-jan-1973','1-mar-1998');

select * from employee; (all the above rows will be availble in the table)

rollback;
select * from employee; (all the above rows will not be availble in the table,insert action is
cancelled)

insert into employee values(100,'Suma','Faculty','CS',4000,'1-jan-1972','1-mar-1998');


insert into employee values(101,'Sudessh','Faculty','CS',4500,'1-jan-1967','1-mar-1996');
commit;
insert into employee values(100,'Vinod','Manager','Sales',4200,'1-jan-1973','1-mar-1998');
rollback;
select * from employee; (first 2 rows of the above rows will be availble in the table, but last row
will be cancelled,
transcations are rollbacked only to the last commit point)

SAVEPOINT:-
insert into employee values(103,'Padma','clerk','accounts',4000,'1-jan-1972','1-mar-1998');
savepoint s1;
insert into employee values(104,'Rakesh','officer','sales',4500,'1-jan-1967','1-mar-1996');
insert into employee values(105,'Deepak','manager','production',4000,'1-jan-1972','1-mar-1998');
savepoint s2;
insert into employee values(106,'Anotony','Faculty','CS',4500,'1-jan-1967','1-mar-1996');
insert into employee values(107,'Thanzeer','Faculty','CS',4000,'1-jan-1972','1-mar-1998');
savepoint s3;
insert into employee values(108,'Sudessh','Faculty','CS',4500,'1-jan-1967','1-mar-1996');

rollback to s3;
select * from employee (only the last row insertion is cancelled, i.e transaction till savpoint s3)

rollback to s1;
select * from employee (till the first row insertion is cancelled, i.e transaction till savpoint s1)

NB-Normal rollback cancels all transactions.

GRANT and REVOKE Commands

DCL commands are used to enforce database security in a multiple user database environment.
Two types of DCL commands are GRANT and REVOKE.
Only Database Administrator's or owner's of the database object can provide/remove privileges
on a database object.

GRANT - is a command used to provide access or privileges on the database objects to the
users.

Syntax

GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT


OPTION];

privilege_name is the access right or privilege granted to the user. Some of the access rights
are ALL, EXECUTE, and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
PUBLIC is used to grant access rights to all users. ROLES are a set of privileges grouped
together.
WITH GRANT OPTION - allows a user to grant access rights to other users.
Example:

GRANT SELECT ON employee TO sudhir;

This command grants a SELECT permission on employee table to Sudhir.

WITH GRANT OPTION - if this option is suffixed with the command then the user receving the
permission can GRANT SELECT privilege on employee table to another user, Later, if you
REVOKE the SELECT privilege on employee from receving user, still other user will have
SELECT privilege on employee table.

REVOKE -The REVOKE command removes user access rights or privileges to the database
objects.
Syntax
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}

REVOKE SELECT ON employee FROM sudhir;

This command will REVOKE a SELECT privilege on employee table from sudhir and will not be
able to SELECT data from that table anymore.
However,

1) if the user has received SELECT privileges on that table from more than one users, he/she
can SELECT from that table until everyone who granted the permission revokes it.

2) You cannot REVOKE privileges if they were not initially granted by you.

Privileges and Roles:

Privileges: Privileges defines the access rights provided to a user on a database object. There
are two types of privileges.

1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or
DELETE data from database objects to which the privileges apply.

Few CREATE system privileges are listed below:

Roles:

Roles are a collection of privileges or access rights. When there are many users in a database it
becomes difficult to grant or revoke privileges to users.
Therefore, if you define roles, you can grant or revoke privileges to users, thereby automatically
granting or revoking privileges. You can either create Roles or use the system roles pre-defined
by oracle.

Some of the privileges granted to the system roles are as given below:

System Role Privileges Granted to the Role

CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE SEQUENCE,


CREATE SESSION etc.
RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE
TRIGGER etc. The primary usage of the RESOURCE role is to restrict access to database
objects.
DBA ALL SYSTEM PRIVILEGES

Creating Roles:

Syntax :

CREATE ROLE role_name;

Example: To create a role called "developer" with password as "pwd",the code will be as
follows

CREATE ROLE developer

It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a
privilege directly to every user.
If a role is identified by a password, then, when you GRANT or REVOKE privileges to the role,
you definitely have to identify it with the password.

We can GRANT or REVOKE privilege to a role as below.

For example: To grant CREATE TABLE privilege to a user by creating a testing role:

First, create a testing Role

CREATE ROLE testing

Second, grant a SELECT,INSERT,UPDATE privilege to the ROLE testing. You can add more
privileges to the ROLE.

GRANT SELECT,INSERT,UPDATE on Employee TO testing;


Third, grant the role to a user.

GRANT testing TO sudhir;

To Delete a Role:

Syntax
DROP ROLE role_name;

For example: To drop a role called developer, you can write:


DROP ROLE testing;

SQL Table locks:


Locks are applied to the tables in an environment where multple users are working on one table.
when a user is on the process
of update of 1 row , the row cannot be accessed by another user for update.

In Oracle locks are of two types


1. Implicit locking - where the system locks the tables internally
2. Explicit locking - where the user locks the tables for update any FOR UPDATE clause is
suffixed to the query statement for locking the row.

example

user sudhir selects the employee table


select * from sujith.employee where empno=3 FOR UPDATE ;

users sujith tries update the same row as follows


update employee set empname='Muthu' where empno=3;

The above will have to wait to be performed till sudhir executes a commit/rollback on his
session.

SYNONYM (DBA Users only)

A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects and used while granting access
to an object from another schema and to avoid users worry about knowing which schema owns
the object.

Syntax
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];

1) PUBLIC means that the synonym is a public synonym and is accessible to all users.
2) User must first have the appropriate privileges to the object to use the synonym.

Example:
CREATE PUBLIC SYNONYM worker FOR employee;

Removing a synomym:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

example
DROP PUBLIC SYNONYM emp_table;

Note : FORCE option will force Oracle to drop the synonym even if it has dependencies

Snapshots:
Oracle uses snapshots, sometimes referred to as materialized views, to meet the requirements
of delivering data to non-master sites in a replicated environment and caching
"expensive" queries from a data warehouse.

Snapshot types:

Primary Key -
Primary key snapshots are considered the normal (default) type of snapshot. Primary key
snapshots are updateable if the snapshot has been created with "FOR UPDATE" was specified
when defining the snapshot. Changes are propagated according to the row changes as
identified by the primary key value of the row (vs. the ROWID). The SQL command for creating
an updateable, primary key snapshot might look like:

CREATE SNAPSHOT emp_snap FOR UPDATE AS


SELECT * FROM employee;

Partitioned Tables:-

Now a days enterprises run databases of hundred of Gigabytes in size. From Oracle Ver. 8.0
Oracle has provided the feature of
table partitioning i.e. you can partition a table according to some criteria .

For example you have a SALES table containing millions of records, but all the records belong
to four years only i.e. 1991, 1992, 1993
and 1994. And most of the time you are concerned about only one year i.e. you give queries
like the following

select sum(amt) from sales where year=1991;

select product,sum(amt) from sales where year=1992 Group by product;

Now whenever you give queries like this Oracle will search the whole table. If you partition this
table according to year, then the performance is improve since oracle will scan only a
single partition instead of whole table.

Range Partitioning:-

To create a partition table give the following statement

create table sales (year number(4), product varchar(10), amt number(10))


partition by range (year)
(
partition p1 values less than (1991) ,
partition p2 values less than (1992) ,
partition p3 values less than (1993) ,
partition p4 values less than (1994) ,
partition p5 values less than (MAXVALUE));

select from the partiton table :-

display the sales of 'Soap' in 1991


select * from sales partiton p1 where product='Soap'

Hash partitioning:-
Hash partitioning provides a method of evenly distributing data across a specified number of
partitions. Rows are mapped into partitions based on a hash value of the partitioning key
CREATE TABLE products (partno NUMBER, description VARCHAR2 (60))
PARTITION BY HASH (partno)
PARTITIONS 4
STORE IN (tab1, tab2, tab3, tab4);

List Partitioning:-

Use list partitioning when you require explicit control over how rows map to partitions. You can
specify a list of discrete values for the partitioning column in the description for each partition.
Create table customers (custcode number(5), Name varchar(20), Addr varchar2(10,2), City
varchar2(20), Bal number(10,2))
Partition by list (city),
Partition north_India values (‘DELHI’,’CHANDIGARH’),
Partition east_India values (‘KOLKOTA’,’PATNA’),
Partition south_India values (‘HYDERABAD’,’BANGALORE’, ’CHENNAI’),
Partition west India values (‘BOMBAY’,’GOA’);

You might also like