SQL Material - Raj Sekhar Anna
SQL Material - Raj Sekhar Anna
SQL Material - Raj Sekhar Anna
Database:
Ex :
Oracle is a RDBMS ,it one of the mostly trusted and widely used RDBMS currently.
Versions= > 8i
12c
Oracle database contains logical and physical structure. Logical structure as table spaces ,
schema objects . Physical structure as data files, redo log files and control files.
In oracle all the information is stored in forms of tables. A table consists of rows and columns.
Oracle datatype:
In oracle it is mandatory to specify the datatype for columns.
Char :
Char is a fixed data length, when we specify some length under char function it occupies the
memory irrespective entered data .
VARCHAR:
When we use varchar the memory allocation is dynamic , wastage of memory is not there.
VARCHAR2:
This wil not occupies spacefor null values. memory allocation is dynamic. Memory wasted is not
there.
NUMBER:
Ex : 236.15
DATE:
Syn :
columnname date
Note:
TIMESTAMP:
LONG:
RAW:
LONG RAW:
Max size is 2 GB
we can use only once In entire table. Repetition is not possible in one table.
BLOB(Binary lob):
Bfile:
SQL STATEMENTS
Sql statements are categorized into 5 different languages.
1.CREATE:
2.ALTER:
Alter is used to add a column, modify a column, rename a column, drop (or) delete a
column.
I.ADD:
Syn:
EX:
II.MODIFY:
Syn:
EX:
III.DROP:
Syn:
Ex:
IV.RENAME:
Syn:
alter table table_name rename column old column name to new column name;
Ex:
3. DROP:
When we use drop command both structure and data of the table get delete.
Syn:
Ex:
4. RENAME:
Syn:
Ex:
5. Truncate :
When we use truncate only data of a table get delete, the structure should remain.
Syn:
Ex:
I. INSERT :
Syn:
Ex:
Note:
Syn:
Ex:
REFERENCE METHOD:
In this method we can enter or insert multiple rows of data at a time. We provide values
through prompt.
Syn:
Ex:
SQL>eno: 01
SQL>empname: prakash
Note:
Note:
When we are specifying character data type we must specify the value in single quots.
II. UPDATE:
Update is used to update the existed data of the table based on where condition.
Ex:
Note:
Ex:
III. DELETE:
Delete is used to delete the content of a table and delete records of the table.
Ex:
Delete from emp where ename = hanuma; => to delete particular record.
SELECT:
We can mention specific columns or hold data in select clause and we can filter data by using where,
group by, having etc clauses
Ex:
COMMIT:
We have to use commit command to make the DML operations permanent save.
Syn : commit;
ROLL BACK:
Ex:
save point A;
Ex:
save point B;
Ex:
Based on above example if I give roll back to A then the rows which we inserted for ’02,03’ will be
roll back.
At this point we can commit the row instead for 01 by using commit.
The rows which we inserted for 03 will be roll backed at this point we can commit the rows
inserted for 01 and 02 by using commit.
DCL statements are the one of the sql statement types which enforce database security.
GRANT :
A DBA or user can grant access permission to other users on database using grant option.
ON [object]
Ex:
When a user is newly created in the data base DBA should grant below privileges to user in order
to connect to the database.
Ex:
When user or owner of a table wants to give select permission to another user the following
can be used.
Syn:
Privileges are the permission name, which is granted to the user, it may select, insert, update,
delete, execute.
REVOKE:
The revoke command is used to take back the existing privilege from a user.
It only DBA or a user with admin option can revoke system privilege.
ON [object]
DUAL TABLE:
We can use dual table in select clause for performing any operations such as
OPERATORS IN SQL
1 ARITHMETIC OPERATORS: ( +,-,*,/ )
Ex:
Logical operators are used to filter the data based on conditions such as ‘and, or, not’.
AND :
OR :
NOT :
= à equal to
!= à not equal to
Ex:
4) SPECIAL OPERATORS: ( IS, IN, LIKE ( %, - ), NOT LIKE, ANY/SOME, ALL, BETWEEN, NOT BETWEEN
IS :
Ex:
Note :
Ex :
Ex :
Select * from emp where sal not between 4000 and 6000;
Ex:
ANY/SOME:
Ex:
5 SET OPERATORS:
The result of each select statement can be treated of set and sql operators can be applied on those
sets.
1)union
2)unionall
3)intersect
4)minus
FUNCTIONs IN ORACLE
Functions are used to meet the business requirement. There are two types of functions
It works or executes from each of value. The following are the single row functions.
a) Number Functions
b) String Functions
c) Date Functions
d) Conversion Functions
e) General Functions.
a)NUMBER FUNCTIONS:
i)Power:
power(m,n)
itreturns the m raised to the n’th power .It multiply the m specified in n number of times.
ii)sqrt :
iii)mod(M,N):-
o/p……..>1,10
iv)ABS (M):
v)trunc:-
If n2 is omitted, then n1 truncated to ‘0’ places. n2 can be negative to truncate (make zero) n2 digits
left of the decimal points.
Output: 125
Trunc (125.815,0)
O/P : 125
Trunc (125.815,1)
O/P : 125.8
Trunc (125.815,2)
O/P : 125.81
Trunc (-125.815,2)
O/P: -125.81
Trunc (125.815,-1)
O/P : 120
Trunc (125.815,-2)
O/P : 100
vi) Round :
The round function returns a number rounded to a certain number of decimal places.
If parameter is omitted the function will round number to ‘0’ decimal places.
Ex:
O/P : 15.999,16,15.56,15.49
vii) Sign :
Ex:
O/P : -1,1,0
viii) Ceil :
O/P : 15
iX) Floor:
It returns the largest integer less than or equals to m, The adjustment should done to the lowest
nearest value.
O/P : 14
X) ASCII :
This function returns the number code for the specified number.
O/P: 116
O/P: 84
Xi) CHR :
O/P: ‘t’
O/P: ‘T’
O/P: 9
O/P: 1
b. String functions:
i. Length:
ii. Reverse:
O/P:
iii. Upper:
Iv: Lower:
V. Initcap:
It converts the given string initial letter to upper letter and remaining characters to lower letter.
Vi. Concat:
Vii. Substr :
Substr function returns specified characters from character value starting from position m to n
characters.
If m is positive oracle counts the beginning of string to find the first character.
If m is negative oracle counts back words from the end of the string
If n is omitted the oracle counts returns all characters from Mth to end of the string
If n is < 1 or ‘0’ null is returned
O/P: error
O/P: echn
O/P: echnologies
O/P: es
O/P: gi
O/P: null
O/P: null
Viii. Instr:
It searches for expression beginning with mth character for nth occurrence and returns the numeric
position of substring.
N always be positive.
Examples:
O/P: 2
Select instr (‘orporatororders’ ‘or’,4) from dual;
O/P: 5
O/P: 10
O/P: 17 [It started searching from back word direction and found or at 17 th position]
O/P: 5 [It started searching from 1st character for the 2nd occurrence of or string find at 5th position]
iX. Trim:
If we don’t specify leading /trailing/both, the trim function will remove characters from both front
and end of string
Syntax:
O/P: 22
O/P: 2200
O/P: 0022
O/P: 22
X. Ltrim:
It removes the specified characters from left side of the specified string
Ex:
Ltrim (‘0001230’,’0’)
O/P: 1230
Ltrim (‘6372tech1234’,’0123456789’)
O/P: tech1234
In the above example every number combination from 0-9 has been listed in the string parameter.
By doing this it doesnot only for order that appears the string, all leading number will be removed.
Xi. Rtrim:
Ltrim (‘0012300’,’0’)
O/P: 00123
Ltrim (‘6372tech1234’,’0123456789’)
O/P: 6372tech
Xii. Lpad:
The Lpad function pads (adds) the specified characters to the left side of the string.
Padà this is the characters that will be characters padded to the left side of the string.
If we don’t specify any characters to be pad by default it will pad the spaces.
O/P: ‘ tech’
Lpad (‘tech’,8,’0’);
O/P: 0000tech
Xiii. Rpad:
The Rpad function pads (adds) the specified characters to right of the specified string
O/P: tech
O/P: ‘tech0000’
Xiv. Translate:
The function replaces a sequence of characters a string with another set of characters.
O/P: ‘4tech456
O/P: 333tith
XV. Replace:
This function replaces a sequence of characters in a string with another set of characters
If we don’t specify replacement string , the replace function simply remove all occurrences of string
and give us the result output
O/P: 333tech2
Replace (‘123tech324’,’123’,’456’)
O/P: 456tech324
O/P: Tech
C) Date functions:
i. Sysdate:
We can use date functions by adding and subtracting values from a date function.
O/P: 28-oct-19
O/P: 27_oct-19
The current date function returns the current date in the time zone of current sql session as set
by the alter session command
O/P: 28-oct-19
Note: we have to alter the session and time zone to use current_date
iii. Add_months:
O/P: 28-jan-20
O/P:
iV. Months-between:
O/P: 1
Select months-between (sysdate, hiredate) from dual;
O/P: 410.958
V. Next_day:
O/P: 29-oct-19
O/P: 31-oct-19
Vi. Last_day:
O/P: 31-oct-19
D) Conversion functions:
i. To_char:
O/P: 1210.7
O/P: -1210.7
O/P: 1210.73
O/P: 1210.73
O/P: 000021
To_char with dates:
O/P: 2010/03/10
O/P: july9,2003
Note:
In the above examples fm means format_mask parameter. It means the zeros and blanks are
suppressed
Parameter/Format Explanation
mm month (01-12)
dd day of month(1-31)
mi minutes (0-59)
ss (0-59)
year to write the complete year name
ii. to_date:
O/P: 15-may-15
iii. To_number:
O/P: 120.80
General functions:
User:
O/P: system
Uid:
O/P: 5
NVL:
The above command replaces the null values of sal column with values of 10000
NVL2:
It allows you to substitute a value when a null is encountered as well as not null values is
encountered
The above command replaces null values sal column with 20000 and non-null value with 10000
Null if:
If expr1 and expr2 are equal it returns null, It expr1 and expr2 not equal it returns expr1
O/P: null
O/P: 20
Coalesce:
The coalesce function returns the first non-null expression in the list. If all expressions evaluate to
null then the coalesce function will return null.
If empname1 and empname2 is null, if empname3 is not null it will display empname3;
Case:
In the simple case expression oracle database searches the first when_then pair which is equal to
comparison_expr and returns return_expr
The maximum number of argument in a case expression is 255. All expression including optional else
expression and initial case expression. Each when and then pairs counts as two arguments
Example:
From emp;
Martin medium
Denis low
.
Else statement
End
End;
Differences:
The simple case performance a simple equality check of expression against each of the when options
The searched case evaluates the conditions independently under each of the when options, more
complex conditions can be implemented with search case
Decode:
It has the functionality of if-then statement using decode function we can substitute value with
another value
Here default value used to replace the other values with default value, If we don’t specify the default
value it will replaces the rest of values as null
Ex:
select decode (S-area, ‘bellandur’, ‘karnataka’, ‘rct’, ‘a.p’, ‘chennai’, ‘t.n’ , ‘rest of india’);
The above function replaces s-area column where Bellandur with Karnataka, Rct with A.P , Chennai
with T.N and other values with rest of India
Aggregate functions:
These functions can appear in select list and having clauses only
The functions operate on set of rows to give one result per each group
It returns the average value of the column, It ignores the null values
Ex:
ii.Sum:
Ex:
iii.Max:
Ex:
iV.Min:
Ex:
Ex:
vi. Variance:
Ex:
vii. Count:
If we specify the column name it counts the distinct values and eliminates null values
Ex: select count(*), count(sal) from emp;
viii. Distinct:
Ex:
ix. Greatest:
Ex:
if we have 7 students in a table and 6 different subjects, for every student if you want to find out
in which subject student has gotten the highest marks on this case we can use greatest function
S-name S1 S2 S3 S4 S5 S6
Prakash 84 86 88 75 68 82
Alex 75 87 90 95 90 80
Martin 96 97 95 94 93 92
Denis 90 89 95 92 91 97
Den mort 85 88 90 97 98 80
Select s-name, greatest (s1, s2, s3, s4, s5, s6) from new;
Prakash 88
Alex 95
Martin 97
Denis 97
Den mort 98
x. Least:
Ex:
select S-name, least (s1, s2, s3, s4, s5, s6) from new;
Prakash 68
Alex 75
Martin 92
Denis 89
Den mort 80
Decode and case statements both give values based on condition, like it-then-else
àIn case function we can use logical all operators including =,<>,>,< and all other operators
But in decode function we cannot use any operators we can use equity check condition
àCase can work as a PL/SQL construct, but decode is used only in SQL statement
àCase expects datatype consistency and decode does not expect datatype consistency
Ex: insert into customer (traded, value) select (ordered, value) from manager;
While inserting from one table to another table the data type should be same on both columns of
tables
CLAUSES IN ORACLE
1. Where clause:
Ex:
The group by clause is used in the select statement to collect data from multiple records
to group the results that have matching values from one or more columns
Note: Group by clause must be used when we have aggregate function in select clause
Syn:
Select col1, col2,….coln, aggregate function (col1) from table-name where condition group by
col1, col2,….coln;
Ex:
select deptno, sum(sal) from emp where sal> 500 group by deptno;
Note:
1 Here where condition is optional to filter the records, the where clause should be preceded
by group by clause
2 all the columns used in select statement along with aggregate functions must be included in the
group by clause
3.Having clause:
It is used in the select statement to filter the data returned by the group by clause
Syn:
select col1, col2,…coln from table-name where condition group by col1, col2,……coln having
condition
Ex:
select deptno, max(sal) from emp where sal> 2000 group by deptno having max(sal) >3000;
Select deptno, max(sal) from emp where sal> 2000 group by deptno having deptno = 10;
Note:
Similar to group by function all the columns that we are specifying in condition with having
must be existed in select clause.
4.Order by clause:
The order by clause us used to sort the records from select statement in ascending or
descending order.
Syn:
Note:
If we omit ascending or descending from the syntax then default data will be sorted in
ascending order
Ex:
select ename, sal from emp where sal> 2000 order by empno, sal;
Here when we are specifying the column names in order by clause, instead of columns we can give
1,2,3,4,… numbers to sort the data
Ex:
Here order by 2 specifies that 2nd column mentioned in the select list i.edeptno
Ex:
The analytical functions in oracle helps us to analyze the data with various functions.
A) Rollup:
The rollupfunction is used to calculate multiple levels of subtotals across the specified group
Of dimensions.
It also calculate the grand total .It is the sample extension to group by clause.
EX:
In the above example the rollup function calculates the grand total of all count of jobs.
EX:
In the above example the rollup function counted the total of all multiple sublevels of managers and
grand total.
B) Cube:-
The cube function is used to calculate subtotals for all possible combinations of group
dimensions.
EX:-
C) Rank:-
Note:
The rank function gives the non-consecutive ranking if the tested values are same.
1) Aggregate Function.
2) Analytical Function.
The rank function returns the rank of a row within group of rows.
EX:
Rank as analytical function returns the rank of the row by dividing other groups.
Syntax:
EX:-
emp;
èwe can mention the where clause in the end to filter the desired records.
EX:
èto get the consecutive rankingswe have to use the dense_rank function .
Ex:-
D) Row_number:-
Note:
EX:-
CONSTRAINTS:
Constraints are the rules enforced on data columns on table.These are used to limit the type
of data that entering into the table.this ensures the accuracy and reliability of the data in the
database.
Constriants could be column level or table level ,column level constraints are applied only to
the column,where as table level constraints are to multiplecolumns at a time.
2) Unique
3) Check
4) Default
5) Primarykey
6) Foreignkey
1) Notnull:-
Syntax:-
2) unique:-
Unique constraint avoid duplicate values from columns of a table.it allows null values.
It allows n number of null values because two null values are not same.
Syntax:-
column level
EX:-
number(5)con_un2 unique);
tablelevel
3) check:-
Check constraint is used to specify range of constraints or rules to the context of a table.
If the condition evaluates to false the record validates the constraint and is not entered into the
table.
Syntax:-
Or
Check(column condition)
EX:-
in(1200,2200)));
EX:-
Note:-
The check constraint allows null values it means though we keep condition as sal>2000,if we
enter null value it accepts the null value as null is unique value. We need to declare not null and
check both constraints to satisfy the condition as follows.
if we create check constraint in table level the constraint will be checked each time the row has been
alters by any type of change.
EX:-
create table emp(sno number not null,star_date date not null,end_date date not
null,joined_date
if we update the star_date or end_date which satisfy the condition the check constraint validation
users.
start_dateend_datejoined_date
10-jan-1610-mar-16 09-feb-16
11-jan-1612-mar-16 10-mar-16
We try to update any of the columns which does not satisfy the condition constraint violation
triggers.
EX:-
4) Default:-
The default constraint provides a default value to the column when the insert into statement
doesn’t provide a specific values.
This rule applicable only when we use the direct method while inserting the values.
Ex:
As we set value of 90 to sal column it will take 90 to the sal column as we set the default value
for this column.
To add the default constraint we can use only modify option to the alter statement.
Ex:
5. Primary Key:
The primary key constraint is a column of unique and not null constraints.
It ensures that null values and duplicate values shouldn’t be entered into the column
“A table can have only one primary key either in table level or column level
Syn:
Primary key
Create table emp (enamevarchar2(10), sal number(10), empid varchar2(10) constraint con_pk
primary key, deptno number(10);
By using above example we have created a table and declared primary key to the empid
column, we cannot declare more than one primary key.
Creating primary key at table level:
By using above syntax we have created a table and declared primary key to the columns as we have
used table level constraint.
With the help of primary key we can relate another table using foreign key of another table.
Note:
If we create or define primary key or unique constraint automatically unique index will get
create on the columns.
6. Foreign key:
Foreign key is used to present actions that would destroy links between two tables.
The table which we are referring to is called as parent table, the table which contains foreign key is
called as child table.
Child table another records always be derived from parent table, it means that the record which we
are insert or which is existed in child table the same record or data must be one of the value in the
table points to
Foreign key constraint also presents k=invalid data from being inserted into the foreign key
column,because the data must be existed in parent table.
Note:
The foreign key can also reference a column that has the unique constraint.
(or)
Create table student (enamevarchar2(10), deptno number(10) foreign key (deptno) references emp
(deptno));
As we discussed carrier by defining foreign key we set the relation between two tables.
So the data dependency is there between two tables the parent table data shouldn’t be deleted if
the data exist in child table.
A. On delete cascade
B. On delete set null
A. On delete cascade:
While creating foreign key if we define on delete set null option, if we delete data from parent
table child table data will also be deleted.
While creating foreign if we define on delete set null option, if we delete data from parent
table chid table records will be update as null.
Ex:
create table student (enamevarchar2(10) not null, stuno number(10), sal number(10) not
null, constraint con_fk foreign key (deptno) references emp(deptno) on delete cascade);
(or)
create table student (ename varchar2(10) not null, stuno number(10), sal number(10) not null,
constraint con_fk foreign key (deptno) references emp(deptno on delete set null:
Joins
Joins are used to fetch the data from one or more tables or views
The prerequisite condition of the join is the columns which we are comparing must have the similar
data type.
In select list the column names should be identified uniquely like table name. column name or alias
name . column name
When we are creating a join condition for three or more tables, oracle first joins two of the tables
based on the join conditions by comparing their columns and then joins the result to another table
based on join condition containing columns of the joined table and the new table
Oracle has following types of joins:
1. Self join
b. Non-equijoin
4. Courtision join
1. Self join:
It means a self-join joins one row of a table with another row in the same table.
With help of aliases we spilt one table into two different tables while creating the query and
performing join condition.
Syn:
Select col1, col2, col3 from table A, table B where A.col1= B.col2;
Ex:
To find out who is the number for earn employee in emp table we can use sel- join.
Select e1.ename “employee”, e2.ename “manager” from emp e1, emp e2 where e1.mgr =
e2.empno;
2. Inner join:
The inner join joins or more tables and returns table rows that follow the join condition
a.Equi join:
Equi-join uses equals to (=) operator in the join condition to match rows from different tables.
Syn:
select ename, dname, job, deptno from emp, dept where empdeptno = dept.deptno and job=
‘clerk’;
b.Nonequi-join:
nonequi join uses an unequal operation that is <>, >, <, !=, between, etc in join condition to
match the data.
Ex:
Select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s where e.sal between s.lowsal
and s.hisal;
3.Outer join:
With the help of outer join we can extract matched and non-matched data from specified
tables.
The outer join returns all rows of table with only those rows from another table that follow the join
condition
It also returns a null value inplace of the record which don’t follow the join condition from another
table.
In this join we will get the matched data right side mentioned table and the whole data from left
side mentioned table and non-matched data from right side tables will be replaced with null values.
Note:
In this join the (+) operator is placed in right side of the equals to operator or any condition
Ex:
select a.empno, a.ename, a.sal, b.deptno, b.dname, b.loc from empa outer join dept b on
(a.deptno = b.deptno);
In this join we will get the matched data left side mentioned table and complete data from right side
table.
Non-matched data replaced with null values.
EX:-
(a.deptno=b.deptno);
With the help of full outer join we can get complete data from two tables, non-matched data will
be replaced with null values.
EX:-
In full outer join if table A is having 6 records and table B having 5 records,if 3 records are common
in two tables ,the final row count is 6+5=11-3=8 records.
4)courtision join:-
It is a join that contains query with that a join condition. Oracle compares each row of one
table with each row of the other table.
If table A is having 3 records and table B is having 5 records,final output will be 5*3=15 records.
EX:-
5)complex join:-
VIEWS
Views is a logical repressentation of a table based on one or more tables or views.
View practically does not contain any data by itself wherever we perform any dml operations it will
hit the base table and provide the result.
The tables that are from view derives the data is called base tables.Base tables can be origin tables
or views.we can use the view in almost same way as we use tables like insert,update,delete and
select.
ADVANTAGES
Views restrict access to the database ,since view contain no data of its own,users can access
a view for information without accessing the basetable where the data is actullay stored.
To provide security on table.
views enable users to simplifying queries and retrieve results from underlying complicated
queries .
views provide data flexibility to multiple group of users by creating multiple views of the
same data.
views are 3 types.
1) simple view.
2) complex view.
3) materialized view.
1) Simple view :
It is view which creates based on one table without contain any group functions such as
max, min, count(*) , etc..,
2.Complex view:
It is a view which derives data from multiple tables or containing any group functions
If you want to perform any DML operations on complex view by using “instead of triggers”
3.Materialized view:
These are used in data ware house and data merge the main objective of materialized views
are to increase the speed of select query
Whenever we create a Materialized view we will get a message like snapshot is created.
These are allocates space in database,where as normal views don’t allocate space in DB
We can use materialized views when we have aggregation on single table and when we join two
tables
When we have to refresh the materialized view always whenever we update the data in base
table,bcoz materialized views are directly contains data and gives results directly without going to
base tables
Force:- It specifies that view needs to be created even if base table doesnot exists
Note:-
When we create a view with force option when base table exists view get creates and
whenever we create the base table the view will be useful
Noforce:- It specifies that views should not be created when base doesn’t exists.
It specifies that rows that would be retrieved from query and where clause can only be
inserted,updated and deleted .
It specifies that rows must only be readable .we can’t perform any DML operations
Indexes
=> Indexes is a schema object where a pointer locates the physical address of the data
=> It is contains entry for each value in the index columns of table
=> the main use of index is to retrieve the data in faster way, in other way we can say that it is used
to speed up the select query performance
=> we generally use indexes when the columns are frequently required.
=> having too many indexes on table will decrease the performance.
The disadvantages of index:
Indexes are takes addition disk space
It will slow down insert, delete,update query .because whenever we update table it must be
updated in index.
1. B_tree index
2. Bitmap index
3. unique index
4. non-unique index
5. function based index
6. clustered index
7. non clustered index
Syntax:
If we specifying more than one column in the column _list it is called as composite index.
Note:
If we don’t specifying any index type while creating the default index that get creates is b
tree index.
After creating an index we should collct statistics of index using below query.
The table called all_in_columns contains ondex names with associated columns
Note:
a unique index is automatically get create when we define unique or primary constraints
To the columns.
Syntax:
Ex:
If we consider emp and dept tables if user usually fetch the data using dept num,if we cluster
these two tables the common data will be reside of the same data block.
Oracle allows maximum of 255 sub query levels in a where clause that is for nested sub
query.
“Mainly sub queries are useful when we need to select rows from the table with a condition
on the data in the table itself”.
A single row sub query returns only one row,it can be used with the =,<,<=,>,>=,<>,!=
symbols.
Ex:
Ex:
select ename,dept_id from emp where dept_id in (select dept_id from dept where
location_id=100);
Correlated sub queries:
A correlated sub queries is a evaluated for each row processed by the main query,it
on excutes the inner query based on the value fletched by the outer query,continues till all
the values returned by the main query that are matched.
EX:
select emp num,fname, sal,dept_id from emp where sal=(select avg(sal)from emp where
dept_id=e.dept_id);
Important queries
Q) How to display duplicate records? From table how to delete duplicate records from table?
To display:
To delete:
Delete from emp where rowid not in (select max (rowid)from table_name groupby
col1,col2,col3,col4…….);
Or
Q ) How to find out second highest salary and first highest salary and nth highest salary
Ans:
Selec ct * from table_name where sal_in (select max (sal) from table_name where sal not_in
(select max(sal from table_name));
Select *from (select table_name.*,danger rank()over (order by sal, desc) rn from high) where
‘rn=&n;
We can substitute any value with n to find out nth highest salary:
Select * from emp where s=(select from emp m )where e.sal<=m.sal count (distinct m.sal)
Ans:
select * from(select Table_ name.*,dense _rank ()over (order by sal desc)rn from
table_name)where rn <=5;
Q ) How to select even rows or odd rows or alternate records from table
Ans:
To even rows
To odd rows
Select * from (select emp.*,dense _rank ()over (partition by dept no order by salary desc()rn
from emp)where rn=1:
Select * from emp where row_id in (select min(rowid)from emp where row id not in (select
max(rowid)from emp));
Table space
1. A table space is a logical storage of the data in database. It logically organize the in database.
2. A table space belongs to only one database.
3. A table space contains atleast one database.
4. A table space can store tables and can also store many other database objects such as
indexes, views,sequences, etc.,.
5. Table spaces are the bridge between certain physical and logical content
6. A table space contain one or more files called data files.
7. Data files are physical structure where the data is collection and stored.
8. The size of the table space is the size of the data files.
9. The size of the database is collective size of the table spaces.
Database errors
1. Table space error
2. Deadlock error
3. Number of connecting limit exceeded
4. Maximum open cursor exceeded
The above are the database errors which we face on frequent basis
This error indicates that the space which is allocated for table space is exceeded.
EX:
So in this case we have to in increase the table space size by adding data file or by resize.
The above error basically indicates when we need to add space to a table space.
We check truly error with DBA learn to increase the table space.for a temporary resolution
we can delete the unwanted data or any backups which are unnecessary and we can re run called
process.
2.Deadlock error:
Whenever particular or processes services try to hit same database object at a time the
database get having and throws deadlock error.
Here the process are hitting the same object in same time using same thread so that is
called of multithread error.
We need to restart the failure services or processes to resolve the issue, when we restart
the process ,processes hits the database at different timings.
In database the DBA teams set the limit to connecting that hit the database object .so when
total number of connections limit exceeded it throws the an error
So we need to innercase the connections limit or we need to start the process when database
object is free from connections.
In oracle program thetre must be certain cursors which gets declare. All the cursors which are
opened should get close within the period of time.if these don’t get close automatically it will throw
an error of maximum open cursor exceeded.
If we are facing this issue frequently we have to increase the limit for this.
Ps-ef|grep-I”PMON”
In windows we have to check under services.mse and need to search for these processes.
Normalization
Normalization is the processes of organizing the data in database.
This includes creating tables and establishing relationships between those tables according
to rules design to protect the data and make the database more flexible.
1. Redundancy
2. Inconsistent dependency
As per the first normal form, no two rows of data must contain repeating group of information.
It means is set of column have unique value so that multiple rows cant be used to fetch the
same row.
Each table shoulb be organized into rows, and each should have a primary key that distinguish it
has unique.
Ex:
Martin 15 bilology,maths
Alex 14 maths
Cary 17 maths
In first NF any row should not contain a columns with more than one value is saved, like
separated with comma rather than that we must separated from data into multiple columns.
Ex:
Martin 15 bilology
Martin 15 maths
Alex 14 maths
Cary 17 maths
By using first nf data redundancy increases there will be many columns with same data in
multiple rows, but each row as whole will be unique.
As per the second normal form there must not be any partial dependency of any column on
primary key. it means that for a table that has concatenated primary key (composite primary
key),each column in the table that is not part of the primary key must depend upon the entire
concatenated key for its existence.
It any columns depends only one part of the concatenation key, then the table files second
normal form.
In example of first normal form there are two rows for martin to include multiple subjects
that martin opted for. And also in first nf we set composite primary key on name, subject columns,
age of the student any depends on name column,which is incorrect as for second normal form.
To achieve second normal form we have to split out the subject into different table and link
them up using name column as foreign key.
Student
Name age
Martin 15
Alex 14
Cary 17
Subject:
Name subject
Martin biology
Martin maths
Alex maths
Cary maths
As per above examples in the student table the primary will be on name columns and other
column that is age depend on it.
In subject table the primary key will be on name columns. Now both the above examples
qualifies for second nf
And we can relate any of the other columns with the help of foreign key relation.
Third normal forms applies that every non prime attribute of table(non primary key
columns)must be dependant in primary key or we can say that there should not be the case that a
non primary key is determined by another non primary attribute.
This transitive functional dependency should be removed from the table and also must be
second normal form.
In this table student id is primary key but street, city and state depends upon zip.
The dependancy between zip and other field called as transitive dependancies.
To achieve third nf we need to more the street,city and state to new table with zip is primary
key.
Address table:
It is a higher version of the third normal forms. this forms deals with certain table of logic that
is not handle by third nf.