SQL Notes
SQL Notes
Index
1.Introduction to SQL
Structured Query Language
Standard Query Language
1
Common for all RDBMS
Pronounced as ‘sequel’
TABLE/RELATION:-
Max of 30 characters.
A-Z, a – z, 0 – 9.
Case insensitive. EMP or emp
Has to begin with alphabet
Only 3 Special characters: $, #, _ Allowed in oracle
(Avoid their use).
2
SQL reserve words not used.
1. VARCHAR2 (size)
Variable-length character data
Minimum size is 1; maximum size is 4000.
Specifying the size is compulsory.
2. CHAR (size)
Fixed-length character data
(Default and minimum size is 1; maximum size is 2000)
3. NUMBER (p,s)
Number having precision p and scale s (The precision is the total
Number of digits, and the scale is the number of digits to the right of the decimal point.
NUMBER(5):-99999
NUMBER (5,3)
e.g. 73.312
Number(2,2)—There can be 2 digits after the decimal ,and the precision is 2 so there
can be no digit before the decimal point. (0.99)OR(0.9) 0.9 33
(If precision is less than scale, then oracle creates the table,but it is of no use as we
cannot store any value).
4. DATE
5. LONG
Variable-length character data up to 2 gigabytes.
Can have only one long column per table.
(Advanced data types later)
Questions:-
1. What is difference between Varchar2 and char?
2. What is the difference between varchar and varchar2?
DDL Commands:
Create:-
3
1. CREATE TABLE EMP /*can type in lowercase*/
(Empno number (4),
Ename varchar2 (20),
Sal number (7,2),
City varchar2 (15),
Comm number (7, 2)
)
Alter Command:-
DML Commands:
1) UPDATE EMP
SET Sal = 10000
4
WHERE ENAME=’Amit’;
2) UPDATE EMP
SET Sal = 10000;
/*change sal=10000 at all records*/
3. UPDATE EMP
SET Sal = 27000,COMM = 1500
Where ENAME = ‘vijay’
2) Delete emp; // deletes all rows but table remains there for future additions
COMMIT will save changes made by DML command till the last commit
stmnt.Whenever u commits its end of Transaction.
Rollback will undo the changes ,made the DML statement till the last
commited stmnt.
Eg:-
1.Insert into…….
2.Insert into…..
Commit.
3.Insert into ….
4.Insert into …
Rollback;
Insert into ….
Insert into …
Commit;
5
SQL> Select * from EMP
Where sal > 5000;
1. Emp table from the server hard disk comes to server Ram.
3. Only those rows that satisfy the condition are sent from server to the client m/c.
Logical Operator:
Operator Meaning
AND Returns TRUE if both
conditions are true
OR Returns TRUE if either
condition is true
NOT Returns TRUE if the following
Condition is false
AND Operator:-
Select * from EMP where city=’Mumbai’ and sal >3000;
OR Operator:-
NOT Operator:-
Relational Operator:
>, < , >= , <= , = , != or <>
9. SQL> Select * from EMP where sal > 5000 and sal<8000;
6
Select Ename “EMPLOYEE NAME”, Sal, Sal*0.4 HRA, Sal*0.15 DA from Emp;
Column Alias :
Double quotes is optional. If blank space or dot in the alias then double quotes is
compulsory. But it is preferred to use double quotes.
Eg: SQL> Select Ename “EMP NAME”, Sal “SALARY”, Sal * 0.1 “H R A” From Emp;
Arithmetic Operator :
15. SQL> Select Ename, Sal, Sal*0.1 “H R A”, Sal*0.15 “D.A”, Sal + Sal * 0.1 + Sal *
0.15 “TOTAL”
From EMP;
Duplicate Rows:-
7
WILD CARDS:
SQL> select *
From EMP
Where ename like ‘A__’;
1. SQL> Select *
From EMP
Where sal between 2000 and 3000;
2. SQL> Select *
From EMP
Where sal not between 2000 and 3000;
3. SQL> Select *
From EMP
Where empno in (2, 3);
8
/*empno=2 or empno=3*/
4. SQL> Select *
From EMP
Where empno not in (2, 3);
Note:-
Explain that IN ( ...) is actually translated by Oracle server to a set of OR conditions: a
=value1 OR a = value2 OR a = value3.
Logical operator(contnd)
Sorting:
Order by clause
9
SQL> select *
From EMP
Order by sal asc
Keywords:
ASC, DESC
Ov7 can combine upto 16 columns in order by clause
Ov8 onwards there is no limit.
• Character functions: Accept character input and can return both character or number
values.
10
• Date functions:- Operate on values of the DATE data type (All date functions return a
value of DATE data type except the MONTHS_BETWEEN function, which returns a
number.)
• Conversion functions:-Convert a value from one data type to another data type.
• General functions:-
– NVL
– NVL2
– COALSECE
– CASE
– DECODE
1. Character functions.
UPPER:
LOWER:
INITCAP:
11
Character functions:
CONCAT ---- joins two strings
LPAD ---- left padded
RPAD ---- right padded
LTRIM ---- trim left
RTRIM --- Trim Right
TRIM ---- all TRIM
SUBSTR ---- extracting string from required position of string
REPLACE ---- replace char from specified characters
TRANSLATE---- goes for a 1 character at a time
INSTR ---- returns starting position of string (numeric value)
LENGTH ---- returns no of characters
ASCII ---- returns ASCII value of 1 st character
CHR ---- opposite to ASCII .gives character of ASCII value
Concatenation operator: ||
12
SELECT CONCAT (FNAME, lname) from EMP;
LPAD:
10. SQL> select fname, lpad (fname,25) from EMP;
RPAD:
12. SQL> select fname, rpad (fname,25) from EMP;
13
where fname ='Raj';
REPLACE
INSTR:-
14
From Emp;
LENGTH
ASCII
2.NUMBER FUNCTIONS:
15
Mod: returns the remainder. Also works with floating numbers.
Power: (a)^ b.
ROUND:
(when –ve sign it works before the decimal, as -1 so it checks the first digit to the left of
decimal, if that digit is >=5 then make it 0 and increment the second digit to the left by
1,else if <5 then make it 0 and do not increment the second digit)
TRUNCATE:
SIGN:
16
0 for zero
MOD:
SQRT:
POWER:
ABS:
3.DATE FUNCTIONS
Months_between:-
17
o/p returns no.of Months between the two dates,the decimal part is the day .
CONVERSION FUNCTIONS:-
1.Implicit Conversion
create table test1
(col1 number,
col2 varchar2 (10));
2.Explicit Conversion
18
Various facilities for date:
DD/MM/YYYY // 4 bytes of the year
27/02/2001
DD/MM/YYY // 3 bytes
27/02/001
DD/MONTH/YY // spell out the whole month string of 9 chars
27/FEBRUARY/01
DD-Month-YY
27-February-01
DD-month-YY
27-february-01
DD-MON-YY
27-FEB-01
19
o/p 27/02/02 01:42:23 /*it displays server time & not the machine time*/
GENERAL FUNCTIONS:
Conditional Expressions:-
1. SQL>
20
Select deptno, decode (deptno,10,'ten',20,'twenty') from emp
Select fname,sal,job,
decode(job,'Programmer',sal*.10,'Analyst',sal*.15,'Manager',sal*.20,200) Bonus from
emp;
CASE Statement:-
It is available only from oracle9i
It is more flexible than decode.
case statement.
The following statement is possible only with Case,and not with decode:-
3. Select fname ,Sal, case when sal > 1 and sal < 5000 then'low salary '
when sal between 5000 and 15000 then 'medium salary '
when sal between 15001 and 25000 then 'high salary'
Else 'very high salary' end Typesal from emp;
So Decode works with (=) operator and case works with (=,>,<,or,and….)
So Case is more flexible.
21
NVL function : Null value
Select empno, sal, comm, sal+nvl (comm,0) "Total Sal” from emp_sal
Use of NVL:
Eg: NVL(job,’manger’)
NVL(city,’mumbai’)
NVL2 Function:-
If the first exp is not null, it will return the second expr else it willl return the third exp.
COALESCE Function:-
Coalesce(Exp1,Exp2,Exp3,Exp4,exp5,…………………………….Expn)
This function returns the first not null exp from the list.
Update emp
set lname =null
where fname like 'raj';
22
4.Multiple Row Functions:-
Group Functions/ Aggregate Functions
Rollback;
23
// count no. of sal where sal ! = NULL
GROUP BY CLAUSE:
1 ABC 5000 10
4 AAA 8000 10
6 QGG 7000 10
3 PQR 6000 20
2 AVC 6700 20
5 QAA 9000 30
Important rules:
Select deptno,JOB ,sum(sal) from emp GROUP BY DEPTNO,JOB ;
// ERROR SINCE sum (sal) returns single value while deptno returns
multiple value.
So, whatever cols are there in select should be there in group by
clause.But Vice-versa not true.
24
Select deptno,sum(sal) from emp group by deptno; //CORRECT
Select deptno, sum (sal) from emp WHERE sal>7000 group by deptno;
// where clause is used to retrieve the rows
o/p deptno sum(SAL)
1 8000
2 17000
Execution as follows:-
Note: if u give where clause after group by it gives error bcoz u r trying to
retrieve the rows from the disk of server after the grouping is done.
HAVING CLAUSE :
25
Multiple grouping:
Roll;
5.SQL Joins
SQL Joins are used to join the tables and to retrieve records based on a join condition
1. Equijoin/Natural join.
The Tables are joined using an (=) sign.
26
Insert into dept values(20,’Exp’,2);
Insert into dept values(30,’Mktg’,3);
Eg: TABLE dept .Common field between dept & emp is deptno.
Case 1:-
Select dname, fname from emp,dept
Where dept.deptno=emp.deptno;
Case 2:-
Table on the RHS: driving table (in this case it is dept) should be the table with lesser
no. of rows.
For every row of the driving table, a pass is carried out through the driven table.
27
--------------------------------------------------------------------------------
2. Select dname,fname, sal from EMP, dept
Where dept.deptno=emp.deptno AND
Dept.deptno=10;
If we write just deptno in select then there will be ambiguity of which deptno to
call. Therefore we‘ve to specify it.
2. Non-equijoin:-
A non-equijoin is a join condition that does not uses the Equality operator.
Professor table and subject table (Assume one subject is taken by only one prof).
If u want to see, which subjects are not taken by that professor
u will use non equijoin.
3. OUTER JOIN:-
28
Inner join+left outer join +right outer join =full outer join.
Here the join shows all rows of dept table, even if the the dept has no employees.
(Right outer join)
Here the query shows all rows of emp table,even which are not assigned to any
dept.(Left outer join)
Select fname,dname
From EMP, dept
O/p for every row of driving table it gives every row of driven table.
Eg: if EMP table has 5 rows and dept has 3 rows then according to above example we
‘ve o/p as 15 rows.
SELF JOIN:-
SELF join: open multiple copies of same table. Give them alias and then join the
table to itself is self join.
Alias is compulsory.
29
Create table emp_manager_tbl
(Empno number(5),
ename varchar2 (20),
Job varchar2(20),
Sal number(5),
Deptno number(5),
Mgrid number);
Worker manager
Vivek raj
Raj ram
Ram Ram
Emp ---worker A
1 vivek 101
101 Raj 777
777 ram 777
Emp ---Manager B
1 vivek 101
101 Raj 777
777 ram 777
After query execution temporary tables are cleared from the RAM.
30
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON(table1.column_name = table2.column_name)] |
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)];
Cross join:-
SELECT fname,dname
FROM emp
CROSS JOIN dept Cross Join Locations;
Natural join
Select fname,sal,job,dname
From emp natural join dept
Where sal >20000
Select fname,dname,locname from emp natural join dept natural join locations;
1. Natural joins use all columns with matching names and data types to join the tables.
The USING clause can be used to specify only those columns that should be
used for an equijoin.
2. For this clause the column name has to be same, but datatype can be different.
3. The columns referenced in the USING clause should not have a qualifier (table
name or alias) anywhere in the SQL
Select a.fname,a.sal,a.job,b.dname
from emp a join dept b
using (deptno);
31
Select a.fname,a.sal,a.job,b.dname
from emp a join dept b
using (deptno) where sal >20000
The ON clause can also be used as follows to join columns that have different
names:
Note:-
select * from emp a join dept b
on a.deptno =b.deptno
and a.locid =b.locid
or
select * from emp a join dept b
on a.deptno =b.deptno and sal >20000
OUTER Joins:-
Select e.fname,e.sal,e.job,d.dname
from emp e
left outer join dept d
32
On (e.deptno=d.deptno)
Select e.fname,e.sal,e.job,d.dname
from emp e
right outer join dept d
on (e.deptno=d.deptno)
Select e.fname,e.sal,e.job,d.dname
from emp e
full outer join dept d
On (e.deptno=d.deptno)
6.SUB-QUERIES:
1. Single row sub-queries
Here we want employees with min (sal). Min (sal) is a group function, so we require
group function but this changes the meaning. Therefore we require subquery.
First child query executes it returns value 3000 in this case then parent query
executes.
33
Sub-queries upto 255 levels in OV7. OV8 onwards there is no limit.
Delete employees, who are working in the same dept as that of raj.
Find all employees doing same job as that of Mandar,and earning salary greater than
‘Mehul’
IN
ANY
ALL
34
Find the employees who earn the same salary as the minimum salary for each
department
The below example displays employees who are not Analyst and whose salary is less
than that of any Analyst.
<ANY means less than the maximum. >ANY means more than the minimum. =ANY is
equivalent to IN Operator.
<ALL means less than the minimum. And >ALL means more than the maximum.
ALL works like logical AND.
7.Manipulating Data
35
1.No of cols and datatype has to be same.
UPDATE EMP
SET JOB= ‘sales_reps’ WHERE DEPTNO=10;
roll;
update emp
set job='SalesRep'
where job='Officer';
Update emp
Set sal= (select sal from emp
Where fname like ’raj’)
Where empno=5;
Update emp
Set sal=(select sal from emp
Where fname like ’raj’),
Job=(select job from emp
Where fname like ’raj’)
Where empno=5;
UPDATE copy_emp
SET deptno= (SELECT deptno
36
FROM emp
WHERE empno = 1)
WHERE job = (SELECT job
FROM emp
WHERE empno = 2);
Deleting Rows:--
The decision whether to update or insert into the target table is based on a condition in
the ON clause.
37
Transaction:-
A transaction begins when the first DML statement is encountered and ends when one
of the
following occurs:
Controlling Transactions:-savepoint
(Using savepoints)
Insert ……….
Update………
Savepoint abc;
Delete ………..
Savepoint pqr;
Update……..
Rollback to pqr;
Savepoints are not schema objects and cannot be referenced in the data dictionary.
If you create a second savepoint with the same name as an earlier savepoint, the earlier
savepoint is deleted.
Savepoints are automatically cleared when a commit or full rollback is issued.
You cannot commit to a savepoint.
Autocommit: -
The AUTOCOMMIT command can be toggled on or
Off. If set to on, each individual DML statement is committed as soon as it is executed.
You cannot roll
back the changes.
Set autocommit on
Insert into test1 values (2,2);
Set autocommit off;
38
• Data changes are made permanent in the database.
Locking:-
In an Oracle database, locks:
The users can also lock data manually, which is called explicit locking.
(Done with the help of CURSORS).
Implicit Locking
– Exclusive lock.
– Share lock.
• A share lock is automatically obtained at the table level during DML operations.
several transactions can acquire share locks on the same resource.(will restrict other
users from drop table or alter table).
39
• An exclusive lock is acquired automatically for each row modified by a DML
statement.
Exclusive locks prevent the row from being changed by other transactions until the
transaction is committed or rolled back. This lock ensures that no other user can modify
the same row at the same time and overwrite changes not yet committed by another
user.
Tables can be created at any time, even while users are using the database.
40
(col1 number,
col2 date default sysdate);
Update empp
set job=default;
• User Tables:
System tables
• Data Dictionary:
– Is a collection of 350 system tables created and maintained by
the Oracle Server
– Contain database information.
User_tables
select table_name from user_tables;
Desc user_tables
User_indexes
User_constraints
User_objects
User_views
User_sequences
User_synonymns
41
From user_objects;
42
• Modify an existing column
• Define a default value for the new column
• Drop a column
Adding a Column
Modifying a Column:
You can modify a column definition by using the ALTER TABLE statement with the
MODIFY clause.
Column modification can include changes to a column’s data type, size, and default
value.
Guidelines
• You can decrease the width of a column only if the column contains only null values or
if the table has no rows.
• You can change the data type only if the column contains null values or if the table
has no rows.
• You can convert a CHAR column to the VARCHAR2 data type or convert a
VARCHAR2 column to the CHAR data type only if the column contains null values or if
you do not change the size.
Dropping a Column
43
Alter table empdept10
drop column fname;
After a column has been marked as unused, you have no access to that column. A
SELECT * query will not retrieve data from unused columns.
In addition, the names and types of columns marked unused will not be displayed during
a DESCRIBE, and you can add to the table a new column with the same name as an
unused column
Dropping a Table
Truncating a Table
DELETE statement.
44
1. It’s a DDL Command.
2. Its faster as it does not generates the rollback information.
3. It does not fires the delete triggers.
4. We cannot have a where clause in truncate statement.
5. Releases the storage space used by that table
9.SET OPERATORS:-
The SET operators combine the results of two or more queries into one query.
Queries containing SET operators are called compound queries.
1. UNION Operator: -
45
insert into emp2 values(4,'D');
insert into emp2 values(5,'E');
Column name here is picked up from 1st query alias for column name can be
given in 1st query.
MINUS OPERATOR displays records that are present in 1st table and not present in the
2nd.
46
Minus
Select ……………...
Union
Select……………….
Union all
Select………………...
Intersect
Select…………………
Hierarchy of execution is from top to bottom. Hierarchy can be changed by putting
brackets.
7.
10.Pseudocolumns
47
Rownum: it is just a counter. Its initialized in the server RAM,not stored in the
database.
11.Constraints
The Oracle Server uses constraints to prevent invalid data entry into tables.
The constraints defined on backend are valid for all front ends.
Constraint types:
NOT NULL Specifies that the column cannot contain a null value
PRIMARY KEY :-Uniquely identifies each row of the table. It cannot contain null values.
48
CHECK:- specifies a condition on a column or set of columns that must be true
The NOT NULL constraint can be specified only at the column level, not at the table
level.
A UNIQUE key integrity constraint requires that every value in a column or set of
columns (key) be unique—that is, no two rows of a table can have duplicate values in a
specified column or set of columns.
The column (or set of columns) included in the definition of the UNIQUE key constraint is
called the unique key.
If the UNIQUE constraint comprises more than one column, then that group of columns
is called a composite unique key.
49
constraint emp_email_uk unique(email));
1. A table can have only one primary key constraint but can have several unique
constraints.
2. Primary key will not allow null values
Egs like passport no,emailed are unique keys
50
It is used to build a Parent-Child relationship.
Foreign key constraints can be defined at the column or table constraint level.
A composite foreign key is created by using the table-level definition.
The example on the slide defines a foreign key constraint on the department_id column
of the employees table, using table-level syntax.
The name of the constraint is emp_deptid_fk.
The foreign key can also be defined at the column level, provided the constraint is based
on a single Column.
• FOREIGN KEY is used to define the column in the child table at the table constraint
level.
• ON DELETE CASCADE indicates that when the row in the parent table is deleted, the
dependent rows in the child table will also be deleted.
• ON DELETE SET NULL:-converts foreign key values to null when the parent value is
removed.
RESTRICT RULE:-
The default behavior is called the restrict rule, which will not allow to delete or update the
parent record when the child records are existing.
51
references employees(employee_id,email) );
Self –Referencing:-
52
Alter table employees
Add constraint email_unq unique (email)
Dropping a Constraint
Disabling Constraints
Enabling Constraints
If you enable a constraint, that constraint applies to all the data in the table.
All the data in the table must fit the constraint.
Viewing Constraints:-
C----CHECK Constraints
C----NOT NULL Constraint.
53
Search _condition will help us to identify.
12.SQL * plus
1. Setting the environment
2. Reporting tool
Note:-
For SQL commands “;” is compulsory
SQL * PLUS “;” is optional
54
New: __________
will not be shown.
3. SQL> SET VERIFY ON : It shows the substitution text. By default it is ON.
20 Analyst
----------------------
----------------------
11. SQL> Break on deptno skip page
SQL> /
12. SQL> Break on deptno DUP skip page /*Dup-------display duplicates*/
SQL> /
13. SQL> Break on deptno on job
SQL> /
14. SQL> Break on deptno skip page on job skip 2
SQL> /
Whenever dept changes skip page & whenever job changes skip 2 lines.
15. SQL> break
Shows break settings.
55
17. SQL> SET PAGESIZE 5
SQL> /
Sets 5 Lines / Page.
LINESIZE:
Default value 80 . Maximum value 32000.
SQL> /
24. SQL> compute avg min max sum of sal on deptno
SQL> /
Everything is calculated . And grand total is displayed.
56
33. SQL> column sal heading ‘salary’ format 99,9999.99
o/p salary
1,300.00
34. SQL> column sal off // original format
35. SQL> column sal on // salary in place again
36. SQL> clear column // original setting comes again
37. SQL> column Fname heading ‘employee_name’
SQL> /
38. SQL> column fname heading ‘emp/name’ format a35
lSQL
clear column
Set lin 70
O/P EXCELLENT
MUMBAI
42. SQL> BTITLE CENTER ‘PAGE ’ SQL.USER
System variables:
SQL.PNO Page no.
SQL.USER user name
SQL.RELEASE version of oracle
SQL.SQLCODE stores error no. of the last error that took place.
If the sql stat is successful then it returns a value 0.
13.Sequences
57
A sequence:
• Automatically generates unique numbers
• Is a sharable object.
Only for the first time the seq starts from 4,then it starts from 1.
(Can be used in a scenario when some data entry has happened already)
nomaxvalue:-10 p27
58
Note:-Start with cannot be less than min value.
Note:-If not specified a value for start with,it will take the same value as
min value.
Confirming Sequences
The CURRVAL pseudocolumn is used to refer to a sequence number that the current
user has just generated.
(empno number,
ename varchar2(20),
sal number,
deptno number);
4. SQL> Rollback;
59
If we login again , then it continues from empno 3 bcoz stored object in database
is 2.
Minvalue 1
Maxvalue 1000
Increment by 2
Cycle;
Minvalue 1
Maxvalue 1000
Increment by -1;
Note: Decrementing seq. is used in airline res. System to show no of tickets balance.
Rollback and commit have no effect on value of sequence.
Minvalue 1
Maxvalue 10
Increment by 1
Cycle
NOcache;
Minvalue 2;
60
Change the increment value, maximum value,
Minimum value, cycle option, or cache option.
Drop sequence abc;
Create sequence abc;
14.VIEWS
A view does not contain any data, the base table has data.
Advantages of Views:-
Views restrict access to the data because the view can display selective columns from
the table.
It is data encapsulation.
Types of views:
61
• A complex view is one that:
Derives data from many tables.(view based on joins)
Contains group functions (avg,sum,max,min) of data
Contains expressions .e.g. sal*12 annual_salary
Distinct clause
Rownum keyword.
Creating a View:
Desc emp_sal10;
NOTE:-
Select * from v1
Order by sal desc;
The outer ORDER BY clause takes the precedence and displays sal in desc order.
The select statement of the view is kept in a column named TEXT which is of the type
LONG.
Modifying a View
62
Create or replace view emp_sal10
(Employee_no, empname, salary, deptno)
as select empno, fname || ’ ’ || lname,
sal, deptno
from emp
where deptno = 10;
(This will in turn fire the sql statement of the above view,so view will not give any
performance benefit ,but it makes queries simpler)
Create view v1
As select empno,fname,sal from emp;
Update v1
Set sal=7777
Where empno=2;
Roll;
63
DML Operations are not possible for view based on joins
( instead of triggers)
The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs
performed through the view cannot create rows which the view cannot select.
Update empvu20
Set deptno = 10
Where empno = 3;
• You can ensure that no DML operations occur by adding the WITH READ ONLY option
to your view definition.
64
Create or replace view empvu10
(employee_number, employee_name, job_title)
as select empno, lname, job
from emp
where deptno = 10
with read only;
Delete empvu10
where employee_number = 2;
Inline Views
Query:-
Select a.lname, a.sal, a.deptno, b.maxsal
from emp a, (select deptno, max(sal) maxsal
from emp
group by deptno) b
where a.deptno = b.deptno
and a.sal < b.maxsal;
In the following example, the inline view b returns the details of all department numbers
and the maximum salary for each department from the EMPLOYEES table.
The WHERE a.department_id = b.department_id
AND a.salary < b.maxsal clause of the main query displays employee names, salaries,
department numbers, and maximum salaries for all the employees who earn less than
the maximum salary in their department.
Practice :-
Name amt type Date
Vijay 2000 c 1/1/2005
Vijay 1500 d 1/1/2005
Raj 25000 c 1/1/2005
Vijay 300 d 1/1/2005
Raj 1400 c 2/1/2005
Raj 2000 d 2/1/2005
select sum(decode(type,cr,amt,0))
creditamt, sum(decode(type,db,amt,0))debitamt,name,date
from tablename
65
group by name,date.
Primary key should always be indexed(column that uniquely identifies the row).
Conditions when an index is not invoked even though u’ve created it:
66
Select * from emp where ename like ‘aaa’;
!=
(i.e. created a composite index on (empno,email) and in where clause we have only
email column.)
Index :-ename
Command
Unique index:-
created.
Composite Index:-
67
When a index is defined on two or more cols it is called as composite index.
Whenever u drop the table, all indexes for that table are automatically dropped
by oracle.
user_ind_columns
where table_name=’EMP’
order by index_name;
System Privileges
CREATE USER: Grantee can create other Oracle users (a privilege required
for a DBA role).
BACKUP ANY TABLE: Grantee can back up a table in any schema with the
68
export utility.
SELECT ANY TABLE :Grantee can query tables, views, or snapshots in any
Schema.
Creating Users
Roles
A role is a named group of related privileges that can be granted to the user.
A user can have access to several roles, and several users can be assigned the same
role. Roles are typically created for a database application.
Only a dba,or a user having create role priv can create a role.
Logon to system/excellent:-
69
GRANT create table, create view
TO manager;
Grant succeeded.
Object Privileges
Logon:-scott/tiger
GRANT insert,update,delete,select
ON emp
TO jack, john;
Grant succeeded.
70
A privilege that is granted with the WITH GRANT OPTION clause can be passed on to
other users and roles by the grantee.
Grant succeeded.
Scott—dept
GRANT select
ON scott.dept
TO PUBLIC;
17.Synonyms:-
It is handle to an object.
Logon to system/manager:---
SYSTEM/excellent
Conn jack/lion
71
Jack can access data of scott table.
He has to fire:-
Public synonym:-
72
/This query shows all emp hired before 2090 as yy works with the current century*/
1.If the current year is in the second half of the century(50-99),and a two-digit year
between ‘00’ and ‘49’ is entered,then this be stored as a ‘next century’ year.
2.If the current year is in the second half of the century(50-99),and a two-digit year
between ‘50’ and ‘99’ is entered,then this be stored as a ‘current century’ year.
3. If the current year is in the first half of the century(0-49),and a two-digit year between
‘00’ and ‘49’ is entered,then this be stored as a ‘current century’ year.
4.If the current year is in the first half of the century(0-49),and a two-digit year between
‘50’ and ‘99’ is entered,then this be stored as a ‘prev century’ year.
Timestamp:-
Timestamp[(fractional_seconds_precision)]
Note:-
The fractional_seconds_precision optionally specifies the number of digits in the
Fractional part of the second datetime field and can be a number in the range 0 to 9. The
default is 6.
Example: -
73
TIMESTAMP WITH TIME ZONE Data Type
• Timestamp with time zone is a variant of timestamp that includes a time zone
displacement in its value.
• The time zone displacement is the difference, in Hours and minutes, between local
time and utc. UTC stands for Coordinated Universal Time—formerly Greenwich Mean
Time.
Timestamp[(fractional_seconds_precision)]
With time zone
Timestamp[(fractional_seconds_precision)]
with local time zone
=============================================================
74
19.Advanced Sub-Queries
Multiple-Column Subqueries
Each row of the main query is compared to values from a multiple-rows and multiple-
columns in the subquery.
Column Comparisons
Column comparisons in a multiple-column subquery
can be:
• Pair wise comparisons
• Nonpairwise comparisons
75
WHERE empno IN (3,13))
AND empno NOT IN (3,13);
Correlated Subqueries
The Oracle Server performs a correlated subquery when the subquery refers to a
column from a table referred to in the parent query.
A correlated subquery is evaluated once for each row processed by the parent
statement.
Display details of those employees who have switched jobs at least twice.
76
start_date date,
end_date date);
SELECT e.empno,fname,job
FROM emp e
WHERE 2 <= (SELECT COUNT (*)
FROM job_history
WHERE empno = e.empno);
Execution is as follows:-
Correlated DELETE
Use a correlated subquery to delete rows in one table
based on rows from another table.
Correlated UPDATE
• ADD a extra column deptname in the emp table.
• Populate the table by using a correlated
update.
UPDATE emp e
SET dname =
(SELECT dname
FROM dept d
WHERE e.deptno= d.deptno);
77
20.Rollup and Cube Operators
Rollup is an extension to the group by clause.
• Total salaries for every job ID within a department for those departments whose
department ID is less than 40 are displayed by the GROUP BY clause
– Total salary for all departments whose department ID is less than 40, irrespective of
the job IDs
Cube Operator
Additionally, the CUBE operator displays the total salary for every job irrespective of
the department.
78
79