My SQL Sandy
My SQL Sandy
What Is DBMS:-
DBMS is the abbreviated form of DataBase Management System.
Database management system is a computer software component introduced during
1960’s. It is used for controlling various databases in the desktop computer or server.
It was also termed as Navigational Database Management System. During 1970’s
RDBMS or Relational database management system came into existence.
DBMS has several components. Some of the major components are external
interface, database language engine, query optimizer, database engine, storage
engine, DBMS management component, etc..
What Is RDBMS
RDBMS is the abbreviated form of Relational DataBase Management System.
Software Development Life Cycle (SDLC) is a process used by the software industry to
design, develop and test high quality softwares. The SDLC aims to produce a high-
quality software that meets or exceeds customer expectations, reaches completion
within times and cost estimates.
What is SDLC?
SDLC is a process followed for a software project, within a software organization. It
consists of a detailed plan describing how to develop, maintain, replace and alter or
enhance specific software. The life cycle defines a methodology for improving the
quality of software and the overall development process.
Planning for the quality assurance requirements and identification of the risks
associated with the project is also done in the planning stage. The outcome of the
technical feasibility study is to define the various technical approaches that can be
followed to implement the project successfully with minimum risks.
This DDS is reviewed by all the important stakeholders and based on various
parameters as risk assessment, product robustness, design modularity, budget and
time constraints, the best design approach is selected for the product.
A design approach clearly defines all the architectural modules of the product along
with its communication and data flow representation with the external and third
party modules (if any). The internal design of all the modules of the proposed
architecture should be clearly defined with the minutest of the details in DDS.
Developers must follow the coding guidelines defined by their organization and
programming tools like compilers, interpreters, debuggers, etc. are used to generate
the code. Different high level programming languages such as C, C++, Pascal, Java and
PHP are used for coding. The programming language is chosen with respect to the
type of software being developed.
Then based on the feedback, the product may be released as it is or with suggested
enhancements in the targeting market segment. After the product is released in the
market, its maintenance is done for the existing customer base.
SDLC Models
There are various software development life cycle models defined and designed
which are followed during the software development process. These models are also
referred as Software Development Process Models". Each process model follows a
Series of steps unique to its type to ensure success in the process of software
development.
Following are the most important and popular SDLC models followed in the industry
−
Waterfall Model
Iterative Model
Spiral Model
V-Model
Big Bang Model
Atomicity :-
The atomicity acid property in SQL. It means either all the operations (insert, update,
delete) inside a transaction take place or none. Or you can say, all the statements
(insert, update, delete) inside a transaction are either completed or rolled back.
Consistency :-
This SQL ACID property ensures database consistency. It means, whatever happens in
the middle of the transaction, this acid property will never leave your database in a
half-completed state. If the transaction completed successfully, then it will apply all
the changes to the database.
If there is an error in a transaction, then all the changes that already made will be
rolled back automatically. It means the database will restore to its initial state that it
had before the transaction started.
If there is a system failure in the middle of the transaction, then also, all the changes
made already will automatically rollback.
Isolation:-
Every transaction is individual, and One transaction can’t access the result of other
transactions until the transaction completed. Or, you can’t perform the same
operation using multiple transactions at the same time.
Durability :-
Once the transaction completed, then the changes it has made to the database will
be permanent. Even if there is a system failure, or any abnormal changes also, this
SQL acid property will safeguard the committed data.
Structured Query Language
SQL Commands
CREATE
ALTER -alter,- Modify, -add, -rename
DROP
TRUNCATE
INSERT
UPDATE
DELETE
MARGE
SELECT
GRANT
REVOKE
SETROLL
Oracle has a number of built-in data types illustrated in the following table:
CHAR: The CHAR data type specifies a fixed-length character string. If you insert a
value that is shorter than the column length, then Oracle blank-pads the value to
column length and if the value is too long for the column, then Oracle returns an
error.
The CHAR data type can store a character string with the size from 1 to 2000 bytes
The default value of length is 1 if you skip it like the following Ex:
column_name CHAR ()
Test table
Name A M O L
Vitthal BLANK PADDED
VARCHAR2: To store variable-length character strings, you use the Oracle VARCHAR2
data type. A VARCHAR2 column can store a value that ranges from 1 to 4000 bytes. It
Test table A M O L
Name
Vitthal BLANK PADDING NOT GENERATED
When you create a table with a VARCHAR2 column, you must specify the maximum
string length: VARCHAR2(max_size CHAR)
If you store a character string whose size exceeds the maximum size of of the
VARCHAR2 column, Oracle issues an error.
For Ex, if you define a VARCHAR2 column with a maximum size is 20. In a single-byte
character set, you can store up to 20 characters. If you store 21 characters or more,
Oracle returns an error.
NOTE:- Whenever we are using number datatype with any column then we are not
allowed to insert values more than (p - s) numbers of digits before decimal point.
--Ex- number (p,s) => number (7,2)
7-2= 5
Insert into test values (12345.6789); --------valid insert value
Date datatypes :
[Link] : The DATE data type allows you to store point-in-time values that include
both date and time with a precision of one second. The DATE data type stores the
year, the month, the day, the hours, the minutes, and the seconds.
The standard date format for input and output is DD-MON-YY e.g., 01-JAN-17 which
is controlled by the value of the NLS_DATE_FORMAT parameter.
TIMESTAMP : The TIMESTAMP data type allows you to store date and time data
including year, month, day, hour, minute and second. In addition, it stores the
fractional seconds, which is not stored by the DATE data type.
Syntax: column_name TIMESTAMP[(fractional_seconds_precision)]
**** COMMANDS –SQL STATEMENTS-
[Link] :- T o create a new table (Any DB Object) in Oracle Database, you use the
CREATE TABLE statement. The following illustrates (explain)the basic syntax of the
CREATE TABLE statement:
NOTE: that you must have the CREATE TABLE system privilege to create a new
table in your schema and CREATE ANY TABLE system privilege to create a new
table in another user’s schema.
[Link] :-
To modify the structure of an existing table, you use the ALTER TABLE statement. The
following illustrates the syntax:
ALTER
--Ex-
To add multiple columns to a table at the same time
ALTER TABLE table_name ADD
(col1 datatype constraint, col2 datatype constraint, ... );
To drop multiple columns at the same time, you use the syntax below:
It is possible to restore the table in to different name by using the following SQL
Command,
FLASHBACK TABLE << Dropped Table Name >> TO BEFORE DROP RENAME TO <<New
Table Name >>;
[Link] :-
When you want to delete all data from a table, you use the DELETE statement
without theWHERE clause as follows:
Oracle introduced the TRUNCATE TABLE statement that allows you to delete all rows
from a big table.
By default, to remove all rows from a table, you specify the name of the table that
you want to truncate in the TRUNCATE TABLE clause:
[Link] COLUMN :-
A virtual column is a table column whose values are calculated automatically using
other column values, or another deterministic expression.
Syntax: column_name [data_type] [GENERATED ALWAYS] AS (expression) [VIRTUAL]
This statement shows how to define a virtual column in the CREATE TABLE
statement:
And this statement illustrates how to add a virtual column to an existing table using
the ALTER TABLE statement:
alter table test add (grade as (case when marks <=300 then ‘C-grade’
when marks >300 and marks <=then 500 then ‘B-grade’
marks <=600 then ‘A-grade’ end));
To show virtual columns of a table, you query from the all_tab_cols view:
You can see the virtual column calculation in DATA_DEFAULT column after execution
above query.
To insert a new record again you have to type entire insert command, if there are lot
of records this will be difficult. This will be avoided by using address method.
This will prompt you for the values but for every insert you have to use forward slash.
--Ex- insert into students values (&no, '&sname');
To insert a new row into a table, you use the Oracle INSERT statement as follows:
The Oracle INSERT INTO SELECTstatement requires the data type of the source and
target tables match.
If you want to copy all rows from the source table to the target table, you remove the
WHERE clause. Otherwise, you can specify which rows from the source table should
be copied to the target table.
INSERT ALL
INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)
INTO table_name(col1,col2,col3) VALUES(val4,val5, val6)
INTO table_name(col1,col2,col3) VALUES(val7,val8, val9)
SELECT * FROM dual;
INSERT ALL
INTO table_name1(col1,col2,col3) VALUES(val1,val2, val3)
INTO table_name2(col1,col2,col3) VALUES(val4,val5, val6)
INTO table_name3(col1,col2,col3) VALUES(val7,val8, val9)
SELECT * FROM dual;
[Link] :-
To changes existing values in a table, you use the following Oracle UPDATE
statement:
--- If you need to update a column in one table based on the values in another,
In my Ex I have emp_1 table which is having empno,ename,sal columns as emp table
having
Create table emp_1 as select empno,ename,sal from emp;
UPDATE emp_1
SET comm = (SELECT comm FROM emp WHERE empno = emp_1.empno);
UPDATE (SELECT * FROM emp1 WHERE empno = 7369 AND deptno = 20)
SET emp_time = 20;
[Link] :- Delete one or more rows from a table, you use the DELETE statement:
In this case, when you create the order_items table, you define a foreign key
constraint with the DELETE CASCADE option as follows:
By doing this, whenever you delete a row from the orders table, for Ex:
All the rows whose order id is 1 in the order_items table are also deleted
automatically by the database system.
Truncate is DDL Command Delete is DML Command Drop is also DDL Command
Minimal logging in
transaction log, so it is It maintains the log, so it It maintains the log, so it
performance wise faster. slower than TRUNCATE. slower than TRUNCATE.
System: This includes permissions for creating session, table, etc and all types of
other system privileges.
Object: This includes permissions for any command or query to perform any
operation on the database tables.
In DCL we have two commands,
GRANT: Used to provide any user access privileges or other priviliges for the
database.
REVOKE: Used to take back permissions from any user.
Allow a User to create table : To allow a user to create tables in the database, we
can use the below command,
Grant all privilege to a User : sysdba is a set of priviliges which has all the
permissions in it. So if we want to provide all the privileges to any user, we can simply
grant them the sysdba permission.
Grant permission to create any table : Sometimes user is restricted from creating
come tables with names which are reserved for system tables. But we can grant
privileges to a user to create any table using the below command,
1). Commit
The main use of Commit command is to make the transaction permanent. If there is a
need for any transaction to be done in the database that transaction permanent
through commit command.
Syntax : COMMIT;
COMMIT;
By using the above set of instructions, you can update the wrong student name by
the correct one and save it permanently in the database.
2). Rollback
Using this command, the database can be restored to the last committed state.
Additionally, it is also used with savepoint command for jumping to a savepoint in a
transaction.
Syntax : Rollback to savepoint-name;
ROLLBACK;
This command is used when the user realizes that he/she has updated the wrong
information after the student name and wants to undo this update.
3). Savepoint
The main use of the Savepoint command is to save a transaction temporarily. This
way users can rollback to the point whenever it is needed.
Syntax : savepoint savepoint-name;
Use some SQL queries on the above table and then watch the results
INSERT into CLASS VALUES (101, ‘Rahul);
Commit;
UPDATE CLASS SET NAME= ‘Tyler’ where id= 101
SAVEPOINT A;
INSERT INTO CLASS VALUES (102, ‘Zack’);
Savepoint B;
INSERT INTO CLASS VALUES (103, ‘Bruno’)
Savepoint C;
Rollback to B;
rollback to A;
[Link] Statement
To retrieve data from one or more columns of a table, you use the SELECT statement
with the following syntax:
Note - the SELECT statement is very complex that consists of many clauses such as
ORDER BY, GROUP BY, HAVING, JOIN.
a table may have more or fewer columns in the future due to the business changes. If
you use the asterisk (*) in the application code and assume that the table has a fixed
set of columns, the application may either not process the additional columns or
access the removed columns.
The “AS” keyword is used to distinguish between the column name and the column
alias. Because the AS keyword is optional, you can skip it as follows:
If you want to change the letter case of the column heading, you need to enclose it in
quotation marks (“”).
If the column alias consists of only one word without special symbols like space, you
don’t need to enclose it in quotation marks. Otherwise, you must enclose the column
heading in quotation marks or you will get an error.
Besides making the column headings more meaningful, you can use the column alias
for an expression, for Ex:
we concatenated the first name, space, and the last name to construct the full name
using concate (||) operator.
Besides the SELECT statement, you can use the WHERE clause in the DELETE or
UPDATE statement to specify which rows to update or delete.
--Ex- select * from emp where deptno=10;
Operator Description
= Equality
!= , <> Inequality
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
AND For a row to be selected all the
specified conditions must be true.
OR For the row to be selected at least
one of the conditions must be true.
NOT For a row to be selected the
specified condition must be false.
--Ex- WAQ to display the employees except JOB as CLERK from emp table.
Select * from emp where job <> ‘CLERK’;
--Ex- WAQ to display employee who are getting more than 2000 sal
Select * from emp where sal > 2000;
--Ex- WAQ whose is CLERK and having sal more than 2000 from emp.
Select * from emp where job=‘CLERK’ and sal > 2000;
--Ex- WAQ whose job is CLERK or sal more than 2000 from emp.
Select * from emp where job=‘CLERK’ or sal > 2000;
--Ex –WAQ whose job is CLERK or SALESMAN and sal is more than 2000 from emp
table.
Select * from emp where (job=‘CLERK’ or job=‘SALESMAN’) and sal > 2000;
--Ex- WAQ to display employees details from deptno 10,20,30;
select * from emp where deptno=10 or deptno=20 or deptno=30;
NOTE- Whenever we using AND operator then database server filter the data from
result set.
Whenever we using OR operator then database return the data based on each and
every individual condition from table.
*** NULL :-
Null value is a special value which defines Nothing or you can say it as ‘No Value’.
If there are null values in SQL then user will find wrong results [Link] counting
null values are very confusing.
In so many interview question you will find out the different scenarios with Null in
[Link] most basic scenario i will explain so that user can get information about the
interview questions related to Null in SQL.
In all DB whenever we are using arithmatic operation and NULL value then it will
become NULL;
** NVL () :-
NVL() is function which is used to replace (or) substitute user_define value in place of
nulll value.
** NVL2 () :-
The Oracle NVL2() function is an extension of the NVL() function with different
options based on whether a NULL value exists.
The Oracle NVL2() function accepts three arguments. If the first argument is not null,
then it returns the second argument. In case the second argument is null, then it
returns the third argument.
SELECT empno, comm, sal, NVL2(comm, sal + comm, sal)"Total_sal" FROM emp;
** NULLIF() :
The Oracle NULLIF() function accepts two arguments. It returns a null value if the two
arguments are equal. In case the arguments are not equal, the NULLIF() function
returns the first argument.
In case both expressions evaluate to non-numeric values, then they must be of the
same data type, otherwise, Oracle issues an error.
[Link] / NOT IN :-
The Oracle IN operator determines whether a value matches any values in a list.
Generally we also use IN operator in place of OR operator.
NOT IN exclude the values which are in list.
NOTE:- In all DB “NOT IN” operator doesn’t work with NULL values.
2. BETWEEN / NOT BETWEEN :-
The BETWEEN operator allows you to specify and retrive a range of value. only rows
whose values are in the specified range are returned.
The NOT BETWEEN operator excludes the values which are specify in range.
Syntax :- Select * from table_name where column_name BETWEEN low AND high
--Ex- WAQ to display the employees who are getting sal between 2000-5000.
Select * from emp where sal between 2000 and 5000;
--Ex- WAQ to display the employees who are not getting sal bet 2000-5000
Select * from emp where sal not between 2000 and 5000;
In NOT BETWEEN operator sal is equal to low range value or high range value then
those matched values are excluded from output.
In BETWEEN operator if sal is equal to low range value or high range value then it will
include that in output.
--Ex- WAQ to disaplay employees details those who are not getting commission.
Select * from emp where comm is null;
--Ex- WAQ to disaplay those employees details who are getting commission.
Select * from emp where comm is not null;
--Ex- WAQ to display employee details whos name start with ‘M’ from emp table.
Select * from emp where ename like ‘M%’ ;
--Ex- WAQ to display employees whose name having ‘M’ in any position within
ename column from emp table.
Select * from emp where ename like ‘%M%’ ;
--Ex- WAQ to display employees names whoes names 4th letter is ‘M’ from emp table
Select * from emp where ename like ‘_ _ _M%’ ;
--Ex- WAQ to display employees detail who are join in the month of DEC from emp
table.
Select * from emp where hiredate like ‘%DEC%’ ;
--Ex- WAQ to display those employee details who joined in year 81 from emp table
Select * from emp where hiredate like ‘%81’ ;
We have given false condition in WHERE clause so data will not copy only structure of
old table will copy.
** Concatination Operator ( || ) :-
|| or concatenation operator is use to link columns or character strings. We can also
use a literal. A literal is a character, number or date that is included in the SELECT
statement.
NOTE: Here above we have used || which is known as Concatenation operator which
is used to link 2 or as many columns as you want in your select query and it is
independent of the datatype of column.
** Dual table
DUAL is a table automatically created by Oracle Database along with the data
dictionary.
DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users.
It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with
a value X. Selecting from the DUAL table is useful for computing a constant
expression with the SELECT statement.
It is best example of public synonyms.
8. You can also check the arithmetic calculation from the DUAL table
SELECT 155*5/5 FROM DUAL;
Output: 20
10. In the following code, DUAL involves the use of decode with NULL.
SELECT decode(null,null,1,0) FROM DUAL;
Output: 1
11. DUAL table also use to fetch sequence value like [Link] and nextval.
12. Decode cannot be called directly in the plsql block. to call the decode statement
we need select statement.
FUNCTIONS
Functions are used to solve particular task.
Functions return values.
[Link] Function:-
These function operate over number/integer datatype.
** ABS (): It returns the absolute value of a number. It is used to convert –ve to +ve
number.
--Ex-
select SIGN (-23) , SIGN (-0.001) , SIGN (0) , SIGN (0.001), SIGN (23), SIGN (23.601)
from dual;
SIGN (-23) SIGN(-0.001) SIGN (0) SIGN (0.001) SIGN (23) SIGN (23.601)
-1 -1 0 1 1 1
** sqrt ( +value ): This will give the square root of the given value.
In sqrt function value must be positive.
**trunc (m, n) : This will truncates or chops off digits of precision from a number.
Trunc function doesn’t compare with 50% of value.
--Ex- select trunc (1.8) a, trunc (-1.8) b from dual;
a B
1 -1
a B c D E
120 100 0 0 123
** greatest (value1,value2,value3,….n) : This will give the greatest number from list
of values.
--Ex- select greatest(1, 2, 3) a, greatest(-1, -2, -3) b from dual;
a B
3 -1
--Ex select greatest (0,0,0) a, greatest (null,null,null) b, greatest (1,2,null) c
From dual;
a B c
0 null null
** least (value1,value2,value3,….n): This will give the least number from list of
values.
--Ex- select least (0,0,0) a, least (null,null,null) b, least (1,2,null) c From dual;
a b c
0 null null
** length ( ) : This will give total length of the string/number including spaces.
Syntax: length (string)
--Ex- select length('vitthal mandlik') from dual;
--Ex- select length(' ') from dual;
--Ex- select length(123456) from dual;
NOTE: if we give the parameter length less than string length then it will show the
same output as we given in string but length of that output will be same as
parameter.
If you haven’t specify any unwanted characters it will display entire string.
--Ex- select trim (‘ india ‘) from dual; ---removes the space from both side
o/p:- ‘india’
--Ex- select trim( 'i' from 'indiani') a, trim( 'i' from 'iindianii') b,
trim( 'i' from 'i indiani') c from dual;
A b c
Ndian ndian indian
--Ex- select trim( leading 'i' from 'iiindiani') from dual; -- this will work as LTRIM
o/p- ndiani
NOTE: TRIM will trim the single character and if trim character are repetative then
it will trim consecutively until it get different character as showed in above ex.
--Ex- select trim( trailing 'i' from 'indianiii') from dual; -- this will work as RTRIM
o/p- indian
This will allows you for searching through a string for set of characters.
INSTR function returns the position of a substring in a string, and allows you to
specify the start position and which occurrence to find.
If start_chr_count is +ve integer then search will start from left side of string.
If start_chr_count is –ve integer then search will start from right side of string
REPLACE TRANSLATE
REPLACE(‘i/p_str’,’find_str’,’replace_str’) TRANSLATE(string, from_str , to_str)
Replaces entire string at a time Replaces character one-to-one basis
Returns string if no match found Returns null if no match found
Ex: select replace ('sql','abc','sequel') as Ex: select translate('sqlandplsql','sql','')
replace_string from dual; as str from dual;
o/p- ‘sql’ o/p- null
Difference between SUBSTR and INSTR:
SUBSTR INSTR
It extract a part of the string from the INSTR function extract the position of
whole source string. the string from source string.
The output datatype of SUBSTR is The output datatype of INSTR is number
number for numeric input and character irrespective of the datatype of the input
for date and character input
If the start position of SUBSTR is greater If the start position of the INSTR
than the total length of the input, the function is greater than the total length
output will be returned as NULL of the input, the output will be returned
as 0
In SUBSTR function if the start position is In INSTR function if the start position is
passed as 0 (zero) then by default the passed as 0 (zero) then output is
start position is taken as 1 returned as 0 (zero)
If the “length” argument is not passed, If the “appearance” argument is not
then the output will be the whole input passed, then by default value 1 is
from the start position considered for the appearance of the
string pattern
ROUND TRUNC
ROUND function rounds the number to a TRUNC used to truncate/delete the
specified number of decimal places number from some position
It compare with 50% of given value and It doesn’t compare given value with its
round the given value based on 50% value.
compairsion result.
It sometime take greater value OR it always takes the lesser value.
sometime take same value.
***Regular Expressions
REGEXP_LIKE - Similar to LIKE except it uses a regular expression as the search string.
REGEXP_LIKE is really an operator, not a function.
1). REGEXP_SUBSTR ()
REGEXP_SUBSTR
(source_string, pattern[,start_position[,occurrence[,match_parameter[,subexpr]]]])
Ex- How to seprate user name and domain name from the email using regexp
select email,regexp_substr(email,'\w.[^@]+',1)user_name,
regexp_substr(email,'[^@]+$',1)domain from test1;
o/p- regexp
--Ex- Given a source string, how do we split it up into separate columns, based on
changes of case and alpha-to-numeric, such that this.
‘ArtADB1234567e9876540’
--Ex- We need to pull out a group of characters from a "/" delimited string, optionally
enclosed by double quotes. The data looks like this in table.
978/955086/GZ120804/10-FEB-12
97/95508/BANANA/10-FEB-12
97/95508/"APPLE"/10-FEB-12
NOTE- if your sentence having any special character then it will difficult the
query to find out exact word string from the source so use carot ^ in bracket to
negate the special characters.
--Ex- How to mask mobile number (dynamicaly). First 2 digit and last 2 digit will be
display and rest of digit will replace by “*”.
--Ex- How to mask email of employees. (First letter and last letter will display).
2). REGEXP_INSTR ()
The REGEXP_INSTR() function enhances the functionality of the INSTR()
function by allowing you to search for a substring in a string using a regular
expression pattern.
The REGEXP_INSTR() function evaluates the string based on the pattern and returns
an integer indicating the beginning or ending position of the matched substring,
depending on the value of the return_option argument. If the function does not find
any match, it will return 0.
--Ex- We have a specific pattern of digits (9 99:99:99) and we want to know the
location of the pattern in our data.
1 01:01:01
.2 02:02:02
..3 03:03:03'
We know we are looking for groups of numbers, so we can use "[0-9]" or "\d" or
[[:digit:]]. We know the amount of digits in each group, which we can indicate using
the "{n}" operator, so we simply describe the pattern we are looking for.
NOTE: If we mention ‘+’ sign with match parameter ‘\W’ then it will show the
position of string but if we removed it then it will show the position of each
special character in the source string.
select '[Link]'"Name",
regexp_instr('[Link]', '\W+', 1, 1) "1_special_char",
regexp_instr('[Link]@@@mandlik', '\W+', 1, 2) "2_special_char",
regexp_instr('[Link]@@@mandlik', '\W+', 1, 3) "3_special_char",
regexp_instr('[Link]@@@mandlik', '\W+', 1, 4) "4_special_char" from
dual;
3). REGEXP_REPLACE ()
REGEXP_REPLACE
(source_string, search_pattern [,replacement_string [,start_position
[,nth_occurrence [,match_parameter ]]]])
We need to find each uppercase character "[A-Z]". For each match, we want to
replace it with a space, plus the matching character.
The space is pretty obvious, but we need to use "\1" to signify the text matching the
first sub expression. So we will replace the matching pattern with a space and itself,
"\1". We dont want to replace the first letter of the string, so we will start at the
second occurrence.
SELECT
REGEXP_REPLACE('Th♥is∞ is a dem☻o of REGEXP_♫REPLACE function','[^a-z_A-Z ]')
FROM dual;
SELECT
regexp_replace ( '4024007187788590','(^\d{3}) (.*) (\d{4}$)', '\1**********\3' )
credit_card FROM dual;
output: 402**********8590
SELECT
regexp_replace( 'This line contains more than one spacing between
words', '( ){2,}', ' ' ) regexp_replace FROM dual;
Output: This line contains more than one spacing between words
O/p:- ABC,DDDD,DDE,2LMDL3EME,CEWEC,
SELECT
REGEXP_REPLACE ('TechOnTheNet is a great resource', '\w+','CheckYourMath',1,1)
FROM dual;
SELECT REGEXP_REPLACE ('2, 5, and 10 are numbers in this Ex', '\d', '#')
FROM dual;
SELECT
REGEXP_REPLACE ('2, 5, 10 and 100 are numbers in this Ex', '(\d){2,}', '#')
FROM dual;
o/p: 'AndGrsGn'
It will replace the source string (name) with G wherever it founds ‘a’,’e’,’i’,’o’,’u’ in his
source string
** Match on nth_occurrence
The nth_occurrence parameter allows you to select which occurrence of the pattern
you wish to replace in the string.
-- First Occurrence
Lets look at how to replace the first occurrence of a pattern in a string.
For Ex: SELECT REGEXP_REPLACE ('TechOnTheNet', 'a|e|i|o|u', 'Z', 1, 1, 'i')
FROM dual;
Result: 'TZchOnTheNet'
This Ex will replace the second character ('e') in 'TechOnTheNet' because it is
replacing the first occurrence of a vowel (a, e, i, o, or u) in the string.
-- Second Occurrence
Next, we will extract for the second occurrence of a pattern in a string.
For Ex: SELECT REGEXP_REPLACE ('TechOnTheNet', 'a|e|i|o|u', 'Z', 1, 2, 'i')
FROM dual;
Result: 'TechZnTheNet'
-- Third Occurrence
For Ex: SELECT REGEXP_REPLACE ('TechOnTheNet', 'a|e|i|o|u', 'Z', 1, 3, 'i')
FROM dual;
Result: 'TechOnThZNet'
This Ex will replace the ninth character ('e') in 'TechOnTheNet' because it is replacing
the third occurrence of a vowel (a, e, i, o, or u) in the string.
NEW YORK
DALLAS
CHICAGO
--Ex- set the phone format in given format 1 – (XXX) XXX - XXXX
select name,
REGEXP_REPLACE(phone, '(\d) (\d{3}) (\d{3}) (\d{4}) ','\1 - (\2) \3 - \4') as phone
FROM customers;
4). REGEXP_LIKE ()
--Ex- The following statement returns employee names that contain the letter ‘c’:
--Ex- WAQ to returns employees whose first names start with the letter A.
SELECT ename FROM emp WHERE REGEXP_LIKE( ename, '^a', 'i' ); --case insensitive
SELECT * FROM Emp WHERE regexp_like (ename, ‘^Am|^Su’,’c’); --- case sensitive
--Ex- WAQ to return emp name whos start with ‘s’ and end with ‘h’.
--Ex- WAQ to returns the employee names that end with letter y
SELECT ename FROM emp WHERE REGEXP_LIKE( ename, 'y$', 'i' ) ORDER BY ename;
--Ex- WAQ to returns employees whose names start with either letter m or n.
SELECT ename FROM emp WHERE REGEXP_LIKE(ename, '^m|^n', 'i' ) ;
NOTE: If user does not know the spelling of amit whether it is Amit or Ameet.
--Ex- WAQ to returns the first names that contain exactly two letters L or 'l'.
--Ex- WAQ to match the multiple character from names which have preceding
charcter ‘T’ and ‘L’.
(OR)
SELECT ename FROM emp WHERE REGEXP_LIKE(ename, '([A-Z])\1','i');
--Ex- WAQ retrieve all names that contain a letter in the range of ‘b’ and ‘g’, followed
by any character, followed by the letter ‘a’.
SELECT * FROM emp WHERE regexp_like (ename , ' [B-G] . [A] ') ;
--Ex- find the ename from emp whos name start with 'a' and contain another ‘a’ in it.
--Ex- WAQ to extract those names who have 'O' in his names 1 or more time.
--Ex- WAQ to retrieve all names that contain the letters ‘j’ or ‘z’.
NOTE: use the Square Brackets to specify a matching list that should match any one
of the expressions represented in it.
me@[Link]
me@Ex
@[Link]
[Link]@[Link]
[Link]@ [Link]
[Link]@[Link]
--Ex- WAQ to returns the first and last names for those employees with a first name
of Steven or Stephen
MasterCard:
5[0-9]{3}\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}
5). REGEXP_COUNT ()
The REGEXP_COUNT() function complements the functionality of the
REGEXP_INSTR() function by returning the number of times a pattern occurs in a
string.
REGEXP_COUNT(string,pattern,position,match_parameter)
--Ex- WAQ to count the number of times the character 't' appears in a string.
'TechOnTheNet is a great resource'
Since we did not specify a match_parameter value, the REGEXP_COUNT function will
perform a case-sensitive search
The search pattern ‘[^ ]’checks for characters other than the space character.
SELECT regexp_count(‘I love [Link] is Lovely Language 114 7’, ‘[^ ]+’,1) FROM dual;
o/p- 8
SELECT regexp_count(‘I love [Link] is lovely language 114 7’, ‘[aeiou]’) FROM dual;
o/p- 9
SELECT regexp_count(‘I love [Link] is Lovely Language 114 7’, ‘(.)’,1) FROM dual;
o/p- 39
SELECT regexp_count(‘I love SQL,SQL is Lovely, Language 114 7’, ‘,’,1) FROM dual;
o/p- 2
--Ex- WAQ to calculate the number of dots in the statement
D -- No of days in week
DD -- No of days in month
DDD -- No of days in year
MM -- No of month
MON -- Three letter abbreviation of month
MONTH -- Fully spelled out month
RM -- Roman numeral month
DY -- Three letter abbreviated day
DAY -- Fully spelled out day
Y -- Last one digit of the year
YY -- Last two digits of the year
YYY -- Last three digits of the year
YYYY -- Full four digit year
SYYYY -- Signed year
Y, YYY -- Year with comma
YEAR -- Fully spelled out year
CC -- Century
Q -- No of quarters
W -- No of weeks in month
WW -- No of weeks in year
IW -- No of weeks in year from ISO standard
HH -- Hours
MI -- Minutes
SS -- Seconds
FF -- Fractional seconds
AM or PM -- Displays AM or PM depending upon time of day
A.M or P.M -- Displays A.M or P.M depending upon time of day
FM -- Prefix to month or day, suppresses padding of month or day
TH -- Suffix to a number
SP -- suffix to a number to be spelled out
SPTH -- Suffix combination of TH and SP to be both spelled out
THSP -- same as SPTH
NOTE: Whenever we are using to_char function always 1st parameter must be
oracle date type (dd-mon-yyyy) otherwise oracle server returns error
2. to_date (date)
This will be used to convert the date string into oracle date data type.
-- If you are not using to_char oracle will display output in default date format.
--Ex- WAQ to display the employees who are joining in DEC month from emp table.
Select * from emp where to_char(hiredate,’mm’)=12;
(OR)
Select * from emp where to_char(hiredate,’MON’)=‘DEC’;
NOTE: In oracle whenever we are passing date string into predefined date
function. Then oracle server automatically converts date string into date type.
That’s why in this case TO_DATE function explicitly , but here passed parameter
must be in oracle format otherwise oracle server returns error.
Explicit conversion
Select last_day (‘15-08-2019’) from dual;
o/p – error
Date Functions :
1.add_months (date, no_of_months) :
This will add the specified months to the given date.
ADD_MONTHS always shifts the date by whole months. You can provide a fractional
value for the month_shift parameter, but ADD_MONTHS will always round down to
the whole number nearest zero.
o/p -7
4. last_day (date) :
This will produce last day of the specified month
o/p-- 11-01-1990
A B
01-JAN-2005 01-JAN-2006
If the second parameter was month then round will checks the day of the given
date in the following ranges. 1 – 15 & 16 -- 31
If the day falls between 1 and 15 then it returns the first day of the current
month.
If the day falls between 16 and 31 then it returns the first day of the next
month.
--Ex- select round(to_date('11-jan-2004','dd-mon-yyyy'),'month') A,
round(to_date('18-jan-2004','dd-mon-yyyy'),'month') B from dual;
A B
01-JAN-2004 01-FEB-2004
If the second parameter was day then round will checks the week day of the
given date in the following ranges. SUN -- WED & THU -- SUN
If the week day falls between SUN and WED then it returns the previous
sunday.
If the weekday falls between THU and SUN then it returns the next sunday.
A B
24-DEC-2006 31-DEC-2006
If the you are not specifying the second parameter then round will resets the time to
the begining of the current day in case of user specified date.
If the you are not specifying the second parameter then round will resets the time to
the begining of the next day in case of sysdate.
A B
01-01-2004 01-01-2006
If the second parameter was month then it always returns the first day of the current
month.
A B
01-01-2004 01-01-2004
If the second parameter was day then it always returns the previous sunday.
A B
26-12-2006 26-12-2006
If the you are not specifying the second parameter then trunk will resets the time to
the begining of the current day.
NOTE: RRRR accepts a four-digit input (although not required), and converts two-digit
dates as RR does. YYYY accepts 4-digit inputs but doesn't do any date converting
Essentially, your first Ex YY will assume that 81 as 2081 whereas the RR one assumes
1981.
--Ex- Get the last day of the current year from given date 01-feb-2020
select round(to_date(add_months(‘01-feb-2020’,5),'dd-mm-yyyy'),'yyyy')-1
from dual;
o/p- 31/12/0020
--Ex- Get all Saturday from the current month (sysdate: 19-01-2021)
** Oracle SYSDATE :
The Oracle SYSDATE function returns the current date and time of the Operating
System (OS) where the Oracle Database installed.
SYSDATE + 1 is tomorrow
SYSDATE - 7 is one week ago
SYSDATE + 7 is next one week
SYSDATE + (10/1440) is ten minutes from now.
NOTE:
The Oracle SYSDATE function cannot be used in the condition of a CHECK constraint.
--Ex- WAQ to Display each month Start and End date upto last month of the year
--Ex- WAQ to find Get number of seconds passed since today (since 00:00 hr.)
--Ex- WAQ to find Get number of minutes passed since today (since 00:00 hr.)
--Ex- WAQ to find Get number of hours passed since today (since 00:00 hr.)
--Ex- WAQ to get how many number of hours are left today (till 23:59:59 hr.)
NOTE: In all DB by default all group functions ignores null value except count(*)
sum (column):
This will give the sum of the values of the specified column.
avg (column) :
This will give the average of the values of the specified column.
max (column) :
This will give the maximum of the values of the specified column.
min (column) :
This will give the minimum of the values of the specified column.
--Ex- How to calculate null values from comm column of emp table.
Select count(*) - count (comm) from emp;
o/p- 10
--Ex- select * from emp where sal=min(sal);
o/p- error
NOTE: in all database we are not allowed to use group function in WHERE caluse.
To use group function in filter condition oracle provided HAVING clause.
The GROUP BY clause is often used with aggregate functions such as AVG(), COUNT(),
MAX(), MIN() and SUM(). In this case, the aggregate function returns the summary
information per group.
Rule: Other than group function column specified in select statement must be
specified in the group by clause otherwise server returns error “not a GROUP BY
expression”.
--Ex- WAQ to display no. of employees from each department from emp table.
Select deptno, count (*) from emp group by deptno ;
--Ex- WAQ to display no. of employees in each JOB from emp table.
Select job, count (*) from emp group by job;
--Ex- select count(*), min (sal), max(sal) from emp group by sal;
NOTE: In every DB we can also use group by clause without group function.
Select deptno, sum(sal), job from emp group by deptno , job order by deptno;
NOTE: if you specified extra column names those who are not present in select
statement then its fine.
--Ex- WAQ to display count of employees per year from emp table.
--Ex- WAQ to display those department no who having more than 3 employees.
After group by clause we are not allowed to use WHERE clause in place of that we are
using HAVING clause.
The HAVING clause is an optional clause of the SELECT statement. It is used to filter
groups of rows returned by the GROUP BY clause. This is why the HAVING clause is
usually used with the GROUP BY clause.
If you use the HAVING clause without the GROUP BY clause, the HAVING clause
works like the WHERE clause.
NOTE: Note that the HAVING clause filters groups of rows while the WHERE
clause filters rows. This is a main difference between the HAVING and WHERE
clauses.
--Ex- WAQ to display those deptno those sum of salary is more than 9000 from emp
table
Select deptno, sum (sal) from emp group by deptno having sum(sal) > 9000;
--Ex- WAQ to display year, no. of employees per year in which more than 1 employee
was hired from emp table.
You can use more than one column in the ORDER BY clause. Make sure whatever
column you are using to sort that column should be in the column-list.
--Ex- select deptno , count (*) from emp where sal >1000 group by deptno
Having count (*) >2 order by deptno desc;
For Ex, the following statement uses the UPPER() function in the ORDER BY clause to
sort the employee names case-insensitively:
ORDER BY GROUP BY
Whereas Order by statement sort the Group by statement is used to group
result-set either in ascending or in the rows that have the same value.
descending order.
While it does not use in CREATE VIEW It may be allowed in CREATE VIEW
statement. statement.
One or more columns can be used in All columns in SELECT statement must
ORDER BY clause from as mentioned in be mentioned in GROUP BY clause
select statement.
ORDER BY clause always placed after GROUP BY clause always placed before
GROUP BY clause ORDER BY clause
Syntax of rollup:
Select col1, col2, …. From tablename group by rollup (col1,col2,…);
Syntax of cube :
Select col1, col2, …. From tablename group by cube (col1,col2,…);
If we want to calculate subtotal based on the single column then we are using
ROLLUP function whereas if we want to calculate subtotal based on no. of column
then we are using CUBE.
--Ex- select deptno, job, sum (sal) from emp group by rollup (deptno, job);
--Ex- select deptno, job, sum (sal) , count(*) from emp group by rollup (deptno, job)
Order by septno, job desc;
Execution:
Step 1 : The SQL Query within the with clause is executed at first step.
Step 2 : The output of the SQL query is stored in to temporary relation of with clause.
Step 3 : The Main query is executed with temporary relation produced at last stage.
WITH temp as
(SELECT avg(Attr1) “alias_name” FROM Table),
SELECT Attr1 FROM Table WHERE Table.Attr1 > temp.alias_name;
--Ex- Find all the employee whose sal is more than the avg salary of all employees.
WITH temp as
(SELECT avg(Salary) avg from Employees)
select e.Employee_id, e.first_Name, [Link] FROM Employees e, temp
WHERE [Link] > [Link] order by [Link] desc;
--Ex- user needs to calculate Salary of the Employee with Total number of the
Employees and user needs to show it department-wise then following query is useful.
With Dep_Count As
(Select Deptno,Count(Empno)No_Of_Emp From Emp Group by Deptno)
Select Empno, Sal/No_Of_Emp From Emp E, Dep_Count C Where [Link] =
[Link];
--Ex- WAQ to display all departments with its total count of employees and also show
those departments those doesn’t have any employees.
with a as
(select department_id, count(employee_id) cnt_emp from employees
group by department_id)
select d.department_id, a.cnt_emp from departments d left join a
where d.department_id = a.department_id ;
WITH col_generator AS
( SELECT t1.batch_id, DECODE([Link], 'SENT', [Link]) sent,
DECODE([Link],'RECV', [Link]) received
FROM test t1, test t2
WHERE t2.batch_id(+) = t1.batch_id)
S M:S
100 1:40
7201 120:1
Important Points:
The SQL WITH clause is good when used with complex SQL statements rather
than simple ones
It also allows you to break down complex SQL queries into smaller ones which
make it easy for debugging and processing the complex queries.
The SQL WITH clause is basically a drop-in replacement to the normal sub-
query.
CONVERSION FUNCTIONS
FROM TO
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
DATE VARCHAR2
NUMBER VARCHAR2
1). Decode () :-
Decode is a conversion function which is used to decoding the values.
Decode will act as value by value substitution.
Decode function is same as IF-THEN-ELSIF control statement of PL/SQL.
For every value of field, it will checks for a match in a series of if/then tests.
-2- If the number of parameters are even and different then decode will display last
value.
--Ex- select decode (1,2,3,4) from dual;
o/p- 4
-3- If all the parameters are null then decode will display nothing.
--Ex- select decode (null,null,null,null) from dual;
o/p- null
-4- If all the parameters are zeros then decode will display zero.
--Ex- select decode (0,0,0) from dual;
o/p- 0
--Ex- select deptno , decode (deptno, 10, ‘ten’ , 20, ‘twenty’, ‘others’) from emp;
Update emp
set comm = decode (job, ‘CLERK’, sal*0.10 , ‘SALESMAN’, sal*0.20,sal*0.30) ;
--Ex- count the no. of employees with respect to job and department name
select [Link],
sum(decode(job,'CLERK',1,0))"Clerks",
sum(decode(job,'MANAGER',1,0))"Manager",
sum(decode(job,'SALESMAN',1,0))"Salesman" from emp e, dep d
where [Link]=[Link] group by [Link];
--Ex- display job wise total salary in pivot report format as shown in above Ex.
** DECODE() function and NULL :- NULL cannot be compared to anything even NULL.
However, DECODE() function treats two null values are equal.
Oracle case statement will give us the transformation of values in following format.
Rules:
The CASE statement returns any datatype such as a string, numeric, date, etc.
(BUT all results must be the same datatype in the CASE statement.)
If all conditions are not the same datatype, an ORA-00932 error will be
returned.
If all results are not the same datatype, an ORA-00932 error will be returned.
If no condition is found to be true, then the CASE statement will return the
value in the ELSE clause.
If the ELSE clause is omitted and no condition is found to be true, then the
CASE statement will return NULL.
NOTE: You can have up to 255 comparisons in a CASE statement. Each WHEN ... THEN
clause is considered 2 comparisons.
Oracle CASE expression has two formats: the simple CASE expression and the
searched CASE expression. Both formats support an optional ELSE clause.
If the input expression column_name does not match any comparison expression,
the CASE expression returns the expression in the ELSE clause if the ELSE clause
exists, otherwise, if “ELSE” clause is not present then it returns a null value.
--Ex- The following query uses the CASE expression to calculate the commission for
each JOB i.e., CLERKS 5%, SALESMAN 10%,and other jobs 8%
The searched CASE expression evaluates the Boolean expression (e1, e2, …) in each
WHEN clause in the order that the Boolean expressions appear.
It returns the result expression (r) of the first Boolean expression (e) that evaluates to
true. If no Boolean expression is true, then the CASE expression returns the result
expression in the ELSE clause if an ELSE clause exists; if ELSE clause is not exists the it
returns a null value.
Oracle evaluates each Boolean condition to determine whether it is true, and never
evaluates the next condition if the previous one is true.
--Ex- Display the employees salary between level 0-2000 as low, 2000 – 4000 as
medium, 4000- 6000 as high from emp table.
select ename,sal,CASE
WHEN sal > 0 AND sal < 2000 THEN 'Low'
WHEN sal >= 2000 AND sal < 4000 THEN 'Medium'
WHEN sal >= 4000 AND sal < 6000 THEN 'High'
ELSE 'Grand' END sal_level FROM emp ORDER BY ename;
--Ex- select full_name, std, (case when gender='M' then 'Male' else 'Female' end)as
Gender from students;
SELECT dname, deptno,COUNT(empno) FROM emp INNER JOIN dep USING (deptno)
GROUP BY dname, deptno HAVING
COUNT(CASE WHEN deptno = 10 THEN empno ELSE NULL END ) > 5 or
COUNT(CASE WHEN deptno = 20 THEN empno ELSE NULL END) > 2
ORDER BY dname;
update emp set sal = ( case when [Link] IS NULL then [Link] else [Link] END )
from employee e1 INNER JOIN emp e2 ON [Link] = [Link];
In above Ex we have used the defined case statement in WHERE clause to filter not
null values.
TRANSLATE DECODE
Translate is string function Decode is conversion function
Translate will replace character one-to- Decode replace the whole string by
one basis. string on basis of compairison.
If no match found for translate it will If no match found then it will show
show source string as it is. NULL value as output.
Ex: select translate ('vitthal','z','1') from Ex: select decode ('vitthal','z','a') from
dual; dual;
o/p: - vitthal o/p:- null
3). to_number () :-
The Oracle TO_NUMBER function is used to convert a text value to a number value.
It works similar to the TO_DATE and TO_CHAR functions but converts the values to a
number.
It takes many different data types: CHAR,VARCHAR2,NCHAR,NVARCHAR2
The TO_NUMBER returns a value in the NUMBER data type. Also, the number will be
rounded to the specified number of digits, which may cause undesired effects.
Format elements:
G group seperator
D decimal indicator
$ dollar sign
0 leading zero
L local currancy
, group seperator
. deciaml
G represending a number
Default Format
This Ex converts a simple string to a number value.
Format No Decimals
This Ex converts a number which has no decimal places in it.
SELECT
TO_NUMBER('$17 218,00', 'L999G999D00',' NLS_NUMERIC_CHARACTERS='', ''')
FROM DUAL;
Whenever we are using to_number also use second parameter as same as first
parameter format by using predefine format elements.
4). To_char () :-
To_Char is overleading function i.e this function is used to convert number datatype
into character datatype and also used to convert date datatype into date string.
Format elements:
G group seperator
D decimal indicator
$ dollar sign
0 leading zero
L local currancy
, group seperator
. deciaml
G represending a number
SELECT TO_CHAR(1111.87,’9999.9′) FROM DUAL; --It will round of the decimal value
o/p - 1111.9
--Ex- select TO_DATE( '5 Jan 2017', 'DD MON YYYY' ) from dual;
--Ex- select TO_DATE( '5 Jan 2017', 'DD MON YYYY' )+7 from dual;
In this Ex, because Feb 01 2017 is not Oracle standard date format, you have to use
the TO_DATE() function to convert it to a DATE value before storing in the table.
LISTAGG ()
PIVOT ()
1). LISTAGG :-
The Oracle LISTAGG() function is an aggregation function that transforms data from
multiple rows into a single list of values separated by a specified delimiter. The
Oracle LISTAGG() function is typically used to denormalize values from multiple rows
into a single value which can be a list of comma-seprated values or other human
readable format for the reporting purpose.
Syntax: LISTAGG
(column_name [, delimiter]) WITHIN GROUP( ORDER BY sort_expressions );
--Ex- WAQ to show all employees names department wise in single row.
SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS
employees FROM emp GROUP BY deptno ORDER BY deptno;
you can run a query using LISTAGG in Oracle and eliminate duplicates from the
output of the LISTAGG function.
Notice how we did not use a GROUP BY. The GROUP BY is not needed if you use the
OVER PARTITION BY clause.
NOTE: The way to do this is to SELECT from a subquery which already removes the
duplicates, and do your LISTAGG on that.
Select listagg (level,’ ‘) within group (order by level) from dual connect by level<=5;
2). PIVOT () :-
Oracle 11g introduced the new PIVOT clause that allows you to write cross-tabulation
queries which transpose rows into columns, aggregating data in the process of the
transposing. As a result, the output of a pivot operation returns more columns and
fewer rows than the starting data set.
--Ex- Separate the below table data into different columns, like alpha values in one
column and numeric value in another column.
Here we have created two alias table for our table and we inserted data in two
different virtual tables with using where condition to split our data and then
combined the virtual result set data by using join.
---Ex- convert the row level data in column level data for below table.
Input- Olympic
Country Medal Sport
India Bronze 100mtr
India Gold 100mtr
India Silver 200mtr
China Gold 400mtr
China Gold Cricket
Nepal Gold Basket ball
Output-
India China Nepal
Bronze - 100mtr Gold – 400mtr Gold – Basket ball
Gold – 100mtr Gold – cricket
Silver – 200mtr
With
table1 as
(select rownum rnk1, medal ||’ - ‘||sport as india from olympic where
country=‘India’),
Table2 as
(select rownum rnk2, medal ||’ - ‘||sport as china from olympic where
country=‘China’),
Table3 as
(select rownum rnk3, medal ||’ - ‘||sport as nepal from olympic where
country=‘Nepal’)
Select [Link] , [Link], [Link]
from table1 full outer join table2
On table1.rnk1 = table2.rnk2 full outer join table3 on table1.rnk1 = table3.rnk3 ;
--Ex- Now display the oputput of below column table into row level .
Input table: C3
India China Nepal
Bronze - 100mtr Gold – 400mtr Gold – Basket ball
Gold – 100mtr Gold – cricket
Silver – 200mtr
Output we want-
Country Medal Sport
India Bronze 100mtr
India Gold 100mtr
India Silver 200mtr
China Gold 400mtr
China Gold Cricket
Nepal Gold Basket ball
with olympic_tab as
(select 'india' country, regexp_substr (india,'\w+',1,1) Medal, regexp_substr
(india,'\w+',1,2) Sports from c3 where regexp_substr (india,'\w+',1,1) is not null
union all
select 'China' country, regexp_substr (China,'\w+',1,1) Medal, regexp_substr
(China,'\w+',1,2) Sports from c3 where regexp_substr (China,'\w+',1,1) is not null
union all
select 'nepal' country, regexp_substr (nepal,'\w+',1,1) Medal, regexp_substr
(nepal,'\w+',1,2) Sports from c3 where regexp_substr (nepal,'\w+',1,1) is not null)
select * from olympic_tab ;
--Ex- WAQ to display number of medal in tabular format for below table.
Output-
MEDAL India China Nepal
Silver 1 0 0
Bronze 1 0 0
Gold 1 2 1
--Ex- Differentiate the negative values and positive values from given test_1 table.
Sno O/p:- Sno Sno
-1 -1 1
-2 -2 2
-3 -3 3
1
2
3
with
a as
(select rownum rnk1, sno as negative from test_1 where sign(sno) = -1),
b as
(select rownum rnk2, sno as positive from test_1 where sign(sno) = 1)
select [Link], [Link] from a full outer join b on a.rnk1 = b.rnk2;
--Ex- Count the negative values and positive values from above Ex table.
with
a as
(select count(sign(sno)) as cnt_neg from test_1 where sign(sno)=-1),
b as
(select count(sign(sno)) as cnt_pos from test_1 where sign(sno)=-1)
select a.cnt_neg, b.cnt_pos from a ,b;
(OR)
select [Link], [Link] from
(select count(sign(sno)) Negative from test_1 where sign(sno) = -1) a1,
(select count(sign(sno)) Positive from test_1 where sign(sno) = 1) b1;
SET OPERATORS
Set operators allow you to combine the results of multiple separate queries into a
single result set. Set operators are also called as vertical joins.
Types of set operators-
[Link]
[Link] all
[Link]
[Link]
Syntax:
Select column1…column n from table1;
union
Select column1…column n from table2;
Rules:
When selecting your columns, the number of columns needs to match between
queries, and the data type of each column needs to be compatible.
So, if you select three columns in the first query, you need to select three columns in
the second query. The data types also need to be compatible, so if you select a
number and two character types in the first query, you need to do the same in the
second query.
Also, if you want to order your results, the ORDER BY must go at the end of the last
query. You can’t add ORDER BY inside each SELECT query before the set operator.
[Link] :
Union Operator combines the result of 2 or more tables and fetches the results of
two select [Link] operator eliminates the duplicates from the table and
fetches the result.
For each duplicate row in table only one row is displayed in the [Link] considering
the performance of SQL using union is not preferable option but if there is situation
where user wants to remove the duplicate data from two or more table the use of
Union is preferable.
--Ex- Suppose we have 2 employee tables. One is for USA location and one is for
CANADA location and both tables having same columns and datatype then.
(Employee_USA and Employee_CAN)
[Link] ALL :
Union ALL Operator combines the result of 2 or more tables and fetches the results
of two or more select [Link] all operator does not eliminate duplicate
[Link] shows duplicate records also.
By considering the performance of SQL using union all is preferable option because it
does not check the duplicate values so no sorting required at the time of fetching the
[Link] all operator is most widely used operator in reporting purpose where
user needs to fetch the records from different tables.
[Link] :
Intersect operator fetches the record which are common between 2 tables.
For Intersecting 2 tables the datatype and column name must be same between 2
tables.
[Link] :
When user wants to fetch the record from one table only and not the common
records between two tables user needs to use Minus [Link] operator
selects all the rows from first table but not from second [Link] eliminates duplicate
rows from first and second [Link] removes the results from second table and always
considered first table only.
In the Ex below, the first query would return departments 10, 20, 30, but
departments 10 and 20 are removed because they are returned by the second query.
This leaves a single rows for department 30.
In below query output will null because 1st query all records are have matching with
2nd query .
JOIN UNION
JOIN combines data from many tables SQL combines the result-set of two or
based on a matched condition between more SELECT statements.
them.
It combines data into new columns. It combines data into same column
Number of columns selected from each Number of columns selected from
table may not be same. each table should be same.
Datatypes of corresponding columns Datatypes of corresponding columns
selected from each table can be selected from each table should be
different. same.
It may not return distinct columns. It returns distinct rows.
INTERSECT MINUS
It fetch the common records from the It fetch the record from one table only
two different tables and not the common records between
two tables
For Intersecting 2 tables the datatype For Minus 2 tables the datatype and
and column name must be same column name must be same between
between 2 tables. 2 tables.
It consider duplicate rows from first and It eliminates duplicate rows from first
second table. and second table.
It always keep the result from both It removes the results from second
table common records. It consider both table and always considered first table
tables result only.
JOINS
Joins are used to retrive the data from multiple tables based on values of the related
columns. The related columns are typically the primary key column(s) of the first
table and foreign key column(s) of the second table.
Types of 8i joins:-
[Link] Join
[Link] Equi Join
[Link] Join
[Link] Join
Types of 9i joins :-
[Link] Join
[Link] Outer Join
[Link] Outer Join
[Link] Outer Join
--Ex- select ename, sal, deptno, dname, loc from emp, dep
Where [Link]=[Link];
For avoiding this error then we must use column alias names with join condition
using dot (.) operator.
We can create table alias name in FROM clause and we can use that table alias name
with all columns which are in select statement to define which column referneces to
which table.
--Ex- select [Link], [Link], [Link], [Link], [Link] from emp e , dep d
Where [Link]=[Link];
--Ex- WAQ to display employees who are working in locaton “CHICAGO” from emp,
dep table using EQUI JOIN.
NOTE: If you want to filter data after joining condition then we are using AND
operator in 8i joins where as in 9i joins we are using either AND (OR) where
clause also.
--Ex- WAQ to display the dname, sum of sal from emp , dep tables using equi join
Select [Link], sum ([Link]) from emp e, dep d where [Link]= [Link]
Group by [Link];
Select [Link], [Link], sum ([Link]) from emp e , dep d where [Link]=[Link]
Group by [Link], [Link] ;
--Ex- WAQ to display location, no. of employees, minimum salary, max salary, avg
salary from emp and dep table using equi join
Select [Link] , count (*) , min ([Link]) , max ([Link]), avg ([Link]) from emp e, dep d
Where [Link]=[Link] group by [Link];
--Ex- WAQ to display location, no. of employees, minimum salary, max salary, avg
salary from emp and dep table having sum of salary > 10000 using equi join
Select [Link] , count (*) , min ([Link]) , max ([Link]), avg ([Link]) from emp e, dep d
Where [Link]=[Link] group by [Link] having sum(sal) > 10000 ;
Select a.*, b.* from test_1 a, test_2 b where [Link] > [Link];
Select a.*, b.* from test_1 a, test_2 b where [Link] <> [Link];
[Link] Join :
Joining a table to itself is called self join. In other words we can say that it is a join
between two copies of the same table.
Conditional column must belong to same datatype.
Whenever we want to compare two different column value from same table then we
must use self join. We must use alias name for both tables.
--Ex- WAQ to display ename and mgrname from emp table by using self join.
Select [Link] “employees” , [Link] “manager” from emp e1, emp e2
Where [Link] =[Link];
(OR using literal in query)
Select [Link] || ' Working for ' || [Link] "Employee working for manager"
from emp e1, emp e2 Where [Link] =[Link];
--Ex- WAQ to display the employees who are getting more salary than their manager
salary from emp table.
--Ex- WAQ to display the employees who are joining before their manager from
emp table.
Self-Joins Using the ON Clause: The ON clause can be used to join columns that have
different names, within the same table or in a different table.
--Ex- WAQ to display the employees who are getting more salary than their manager
salary from emp table using self join with ON clause.
Select [Link] "emp", [Link] "mgr" from emp e1 INNER JOIN emp e2
ON [Link] = [Link] and [Link]> [Link] ;
NOTE: You can use self join within all 9i joins as we used inner join for self join
in above Ex. You can use LEFT JOIN, RIGHT JOIN, FULL JOIN instead of inner
join
[Link] Join :
This join is used to retrive all rows from one table and matching rows from another
table.
If we want to retrive non-matching rows then we are using JOIN operator (+) within
joining condition of the EQUI JOIN this is called OUTER JOIN.
NOTE: This join operator can be used one side at a time within joining
condition.
--Ex- select [Link], [Link], [Link], [Link], [Link] from emp e, dep d
Where [Link] (+) = [Link]; (It work like right outer join)
--Ex- select [Link], [Link], [Link], [Link], [Link] from emp e, dep d
Where [Link] = [Link] (+); (It work like left outer join)
** 9i joins :
[Link] Join :
This join also returns matching rows only, here also join condition column must
belong to same datatype. When tables having one common column then only we can
use innner join.
--Ex- select [Link], [Link], [Link], [Link], [Link] from emp e INNER JOIN dep d
ON [Link] = [Link] ;
--Ex- WAQ to display the employees who are working in loc “CHICAGO” from emp
table , dep table using inner join.
USING Clause: In 9i joins we can also use USING clause in place of ON clause to
define the join condition. USING clause only return common column one time only.
Select [Link] , [Link], [Link], [Link] from emp e INNER JOIN dep d
Using ([Link]) where [Link] >2000 ;
o/p- ERROR
select ename, sal, deptno, dname from emp INNER JOIN dep using (deptno)
where sal >= 2000 ;
NOTE: We cant use alias names in join query if we used USING clause to define
join condition.
[Link] Outer Join:
This join always return all rows from left table and matching records from right side
table and also returns NULL values in place of non-matching records in another table.
Syntax:
SELECT [Link], [Link] FROM table1 LEFT OUTER JOIN table2
ON ([Link] = [Link]);
NOTE: You can use USING clause in place of ON clause to eliminate the common
column duplication.
--Ex- WAQ to display the NEW YORK loc employees details using left outer join.
NOTE: You can use USING clause in place of ON clause to eliminate the common
column duplication.
--Ex- WAQ to display the NEW YORK loc employees details using right outer join.
NOTE: You can use USING clause in place of ON clause to eliminate the common
column duplication.
--Ex- WAQ to display the NEW YORK loc employees details using full outer join.
--Ex- WAQ to display the NEW YORK loc employees details using full outer join.
NOTE: We are not allowed to use alias names in NATURAL JOIN because inernally
this join uses USING clause to define the join condition. And USING clause doesn’t
work with alias names.
[Link] Join :
The SQL CROSS JOIN produces a result set which is the number of rows in the first
table multiplied by the number of rows in the second table if no WHERE clause is
used along with CROSS [Link] kind of result is called as Cartesian Product.
If WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.
--Ex- select ename, sal, dname, loc from emp cross join dep ; ---cross join
--Ex- select ename,sal,dname, loc from emp , dep; --- cross join
--Ex- select e.*,d.* from emp e cross join dep d where [Link]=[Link];
Excersice:-
--Ex- create two tables A and B and perform ALL joins ON given table.
Table A Table B
ID ID
1 1 Select [Link] ,[Link] from t1 a, t2 where [Link]=[Link];
2 2 Select [Link] ,[Link] from t1 a INNER JOIN t2 b on [Link]=[Link];
3 3 Select [Link] ,[Link] from t1 a LEFT JOIN t2 b on [Link]=[Link];
Null Select [Link] ,[Link] from t1 a RIGHT JOIN t2 b on [Link]=[Link];
4 Select [Link] ,[Link] from t1 a FULL JOIN t2 b on [Link]=[Link];
5
6
EQUI JOIN INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN
ID ID ID ID ID ID ID ID ID ID
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
NOTE: EQUI Join and INNER join doesn’t accept Null Null Null Null
any null values for comparison. Whereas all Null 5 Null 4
other 9i joins accepts the null values for Null 6 Null 5
comparison. Null 4 Null 6
T1 T2 In this tables t1 and t2 both are having same number as input so all
0 0 joins will produce “CARTESION PRODUCT” so all joins will give the
0 0 output in 16 digits as cross join (cartesion product).
0 0 Whenever you get single digit (0 to 9) in two tables always it will
0 0 produce cartesion product as o/p for all joins.
--Ex- create two tables tab4 and tab5 and perform ALL joins on given table.
EQUI JOIN INNER JOIN LEFT OUTER RIGHT OUTER FULL OUTER
JOIN JOIN JOIN
SNO SNO SNO SNO SNO SNO SNO SNO SNO SNO
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0
null null null null Null Null
null null Null Null
null Null
--Ex- create two tab_2 and tab_3 and perform ALL joins on given table.
Tab_2 Tab_3
select a.*,b.* from tab_2 a, tab_3 b where [Link]=[Link];
NOS NOS
select a.*,b.* from tab_2 a INNER JOIN tab_3 b on
1 1
[Link]=[Link];
2 1
select a.*,b.* from tab_2 a LEFT JOIN tab_3 b on [Link]=[Link];
4 2
select a.*,b.* from tab_2 a RIGHT JOIN tab_3 b on
5 2
[Link]=[Link];
null 6
select a.*,b.* from tab_2 a FULL JOIN tab_3 b on [Link]=[Link];
7
EQUI JOIN INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN
SNO SNO SNO SNO SNO SNO SNO SNO SNO SNO
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
4 null Null 6 4 Null
5 Null Null 7 5 Null
null Null null Null
null 6
null 7
CONSTRAINTS
CONSTRAINTS are used to define some conditions that restrict the invalid data to
maintain valid data while inserting or updating or deleting data in the column. It will
maintain the integrity of the data.
The SQL CONSTRAINTS are used to implement the rules of the table. If there is any
violation of the constraints caused some action not performing properly on the table
the action is aborted by the constraint.
While adding constraints you didn’t specify the name for constraint then oracle will
internally name the constrain, name will start from SYS_.
If you want to give a name to the constraint, you have to use the CONSTRAINT clause.
*Column Level : Constraints can be specified for individual columns as part of the
column specification.
*Table Level : In this method we are defining constraints on group of columns i.e first
we specifying all columns and last only we are specifying constraint type along with
group of columns.
The enabled and disabled states of a constraint can be changed by using ENABLE and
DISABLE. The default is ENABLE.
ENABLE VALIDATE:
All existing and new data must meet the constraint. If any row does not meet the
constraint, the constraint remains disabled or not created.
Specifying this for a primary key will ensure that a validation process is run to ensure
NULL values do not exist. You can avoid this by specifying a NOT NULL constraint on
the column first.
ENABLE NOVALIDATE:
All new data must meet the constraint.
Existing data is not checked against the constraint.
DISABLE VALIDATE:
Disables the constraint.
Drops the index on the constraint.
Keeps the constraint valid.
DISABLE NOVALIDATE:
No effort is made to maintain the constraint or ensure data complies with it.
Optimizer can use constraints in this state.
If you specify ENABLE, then the default is VALIDATE. If you specify DISABLE, then the
default is NOVALIDATE.
COLUMN LEVEL
Define constraint without giving userdefine constraint name-
--Ex- create table student(no number(2) NOT NULL, name varchar(10),
marks number(3));
ALTER LEVEL
alter table students MODIFY marks NOT NULL; --- without constraint name
alter table students MODIFY marks constraint mrk_nn NOT NULL; --With name
NOTE: In all DB whenever we are copying a data from one table to another
table except NOT NULL all other constraint are never been copied.
If we have a table with data and null values then we have to use NOVALIDATE state
with alter statement.
Alter table student MODIFY marks constraint mrk_nn NOT NULL enable novalidate;
COLUMN LEVEL
--Ex- create table student(no number(2) UNIQUE, name varchar(10),
marks number(3));
TABLE LEVEL
--Ex- create table student(no number(2) , name varchar(10), marks number(3),
UNIQUE (no));
ALTER LEVEL
--Ex- alter table student add UNIQUE (no);
--Ex- If we try to add or Modify UNIQUE constraint on table column and that column
is having duplicate data then we have to use following steps as shown in Ex.
(OR) if you want to insert duplicate data into column by disabling PK/UQ constraint
for short time of period.
INSERT INTO ziggy SELECT rownum , ‘Ziggy’ FROM dual CONNECT BY LEVEL <= 100;
Note that the ID column is populated with unique values. However, let’s now
introduce a duplicate value, 42:
INSERT INTO ziggy VALUES (42, ‘DUPLICATE’);
Because by default Oracle will attempt to create a Unique index when creating a PK
constraint. A Unique index MUST always contain unique values and so complains
when it stumbles across our duplicate 42 ID value.
If we look at the status of the constraint and the type of index used to police the
constraint
This is used to insert the values based on specified condition. If the expression
evaluates to true, Oracle accepts the data and carry the insert or update. Otherwise,
Oracle will reject the data and does not insert or update at all.
COLUMN LEVEL
--Ex- create table student(no number(2) , name varchar(10),
marks number(3) CHECK (marks > 300));
TABLE LEVEL
--Ex- create table student(no number(2) , name varchar(10),
marks number(3), CHECK (marks > 300));
ALTER LEVEL
--Ex- alter table student add CHECK (marks>300);
If your table is having data and you want to assign CHECK constraint on that table
then you should have the data which fulfill the CHECK condition otherwise it will
through error but we can minimise that by skipping already inserted data by by
passing it from CHECK condition using NOVALIDATE.
--Ex- alter table student add constraint chk_con CHECK (marks>300) enable
novalidate;
This is used to avoid duplicates and nulls. This will work as combination of unique and
not null. Whenever we are creating Primary key then oracle internally create btree
indexes on those column. We can add this constraint in all three levels.
A table can only have one primary key on it. If you try to create a second primary key,
you’ll get an error.
A composite primary key can’t have more than 32 columns.
The same column or combination of columns cannot be part of a primary key and a
unique constraint.
Properties :
No duplicate values are allowed, i.e. Column assigned as primary key should have
UNIQUE values only.
NO NULL values are present in column with Primary key.
Only one primary key per table exist although Primary key may have multiple
columns.
COLUMN LEVEL
--Ex- create table student(no number(2) PRIMARY KEY, name varchar(10),
marks number(3));
--Ex- create table student(no number(2) constraint con_pk PRIMARY KEY,
name varchar(10), marks number(3));
TABLE LEVEL
--Ex- create table student(no number(2) , name varchar(10), marks number(3),
PRIMARY KEY(no));
--Ex- create table student(no number(2) , name varchar(10), marks number(3),
Constraint con_pk PRIMARY KEY(no));
ALTER LEVEL
--Ex- alter table student add PRIMARY KEY(no);
In this Ex, we’ve created the table with a primary key on both the first_name and
last_name columns, which means that the combination of those values needs to be
unique.
--Ex- If we want to add PK constraint on table which is holding some data and that
data has duplicate value then we have to use use NOVALIDATE with constraint.
So this is how we can alter PK and unique key constraint while table is having
duplicate data.
COLUMN LEVEL
Create table dep ( deptno number (6) FOREIGN KEY references emp (deptno), dname
varchar2 (20), Loc varchar2 (20));
Create table dep ( deptno number (6)constraint con_fk FOREIGN KEY references
emp (deptno), dname varchar2 (20), Loc varchar2 (20));
TABLE LEVEL
create table emp(empno number(2), ename varchar(10), deptno number(2),
PRIMARY KEY(empno), FOREIGN KEY(deptno) references dept(deptno));
ALTER LEVEL
alter table dept add FOREIGN KEY(deptno) references emp(deptno);
Syntax –
create table dep(deptno varchar2(10), dname varchar2(20), loc varchar2(20),
FOREIGN KEY(deptno) references emp(deptno) ON DELETE CASCADE);
NOTE: Generally when we are truncatinting master table by using truncate table
table_name then DB server returns error to overcome this problem oracle 12c
provided CASCADE clause along with truncate table table_name.
Syntax: truncate table master_tablename CASCADE;
Before we are using this command we must use ON DELETE CASCADE clause along
with foreign key while creation of table or u can alter the foreign key at alter level.
[Link] :
This constraint is used to provide a default value for the fields. That is, if at the time
of entering new records in the table if the user does not specify any value for these
fields then the default value will be assigned to them.
COLUMN LEVEL
Create table student (ID number(6),NAME varchar2(10),AGE number DEFAULT 18 );
ALTER LEVEL
Alter table Student MODIFY ID DEFAULT 100;
If you want to view default value of any column then we are using -
Select * from user_tab_columns where table_name= ‘STUDENT’ ;
In result window you can check the default condition in DATA_DEFAULT column.
You can not drop DEFAULT value constraint from table you can set it to null only
otherwise if you need to DROP it then you may have to recreate your table.
Use below query to make your table copy so default constraint will get removed.
When you create the copy of your base table then all constraints will not copied only
NOT NULL constraint will get copy. This is how you can remove DEFAULT value from
your table column.
ENABLE :- This will enable the constraint. Before enable, the constraint will check the
existing data.
--Ex- alter table student enable constraint un;
ENFORCE :- This will enforce the constraint rather than enable for future inserts or
updates. This will not check for existing data while enforcing data.
NOTE: If we want to drop primary key along with referenced foreign key then we
are using CASCADE clause along with alter drop.
If you don’t know the constraint name then first we have to find it-
Select * from user_cons_columns Where table_name=‘EMP’;
Q. Suppose you have the table T1 and it has relation with many tables and its
primary key constraint name is "pk_t1" you want to disable these foreign keys.
BEGIN
FOR I IN (SELECT table_name, constraint_name FROM user_constraint
WHERE r_constraint_name='pk_t1') LOOP
EXECUTE IMMEDIATE ' alter table ' || I.table_name || ' disable constraint ' ||
i.constraint_name;
END LOOP;
END;
Sub Queries
In SQL a query within another query is called as Subquery. In other words we can say
that a Subquery is a query that is embedded in WHERE clause of another SQL query.
A subquery is a query within another query. The outer query is called as main query
and inner query is called as subquery.
The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING
clause, FROM clause.
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with
expression operator. It could be equality operator or comparison operator such as =,
>, =, <= and Like operator.
ORDER BY command cannot be used in a Subquery. GROUPBY command can be used
to perform same function as ORDER BY command.
Used primarily for solving complex use cases and increasing the performance or
speed of a DBMS operation.
You can use a subquery in many places such as:
With the IN or NOT IN operator
With comparison operators
With the EXISTS or NOT EXISTS operator
With the ANY or ALL operator
In the FROM clause
In the SELECT clause
In non-corelated subqueries child queries are executed first then only parent queries
executed.
Whereas in correlated subqueries parent queries are executed first and then only
child queries are executed.
1..Non-correlated Subqueries :
Non-correlated subqueries in two parts – child queries and parent query.
Child query: A query which provides values to the another query is called child query.
Parent query: A query which receives value from another query is called parent query
4 types of Non correlated subqueries-
Single row subqueries
Multiple row subqueies
Multiple column subqueries
Inline view subqueries
--Ex- Find the departments where the total number of employees is more than the
total number of employees in 10.
select [Link], count([Link]) from emp e inner join dep d on [Link] = [Link]
group by [Link]
having count([Link]) > (select count(empno) from emp where deptno = 10);
Syntax 3 : Subquery in FROM Clause
SELECT col (s) FROM (SELECT col (s) from table_name) as table_alias
WHERE condition;
--Ex- finds the salaries of all employees, their average salary, and the difference
between the salary of each employee and the average salary.
Select empno, ename from Emp where Sal=(Select max(Sal) from Emp);
--Ex- WAQ to display the employees details who are getting more sal than avg sal.
select * from emp where sal > (select avg(sal) from emp);
--Ex- WAQ to display the employees who are working in SALES department.
select * from emp where deptno (select deptno from dep where dname='SALES');
NOTE: Generally we are not allowed to use child query table column with
parent query because SubQuery always return parent query table column in
output, To overcome this problem we must use joins within parent query.
--Ex- WAQ to display the employees who are working in SALES department.
--Ex- WAQ to display those employee who are working same as ‘SMITH’ job.
Select * from emp where deptno= (select deptno from emp where ename=‘SMITH’);
--Ex- WAQ to display the employee details who are getting more salary than highest
salary paid employee of department 20.
Select * from emp where sal> (select max(sal) from emp where deptno=20);
--Ex- WAQ to display department name of highest paid employee from emp, dep
table
--Ex- WAQ to display lowest average salary JOB from emp table.
NOTE: Whenever in query we use nested group function then we must use group by
clause in child query.
--Ex- WAQ to display which job avg salary having more than CLERK job avg sal.
--Ex- WAQ to display the employees who are working for BLAKE as manager.
Select * from emp where mgr = (select empno from emp where ename=‘BLAKE’);
--Ex- Fetch the list of Employees which is assigned to SALES and ACCOUNTING
Department.
--Ex- WAQ to display employee details who are getting highest salary in each
Departments.
Select * from emp where sal in (select max(sal) from emp group by deptno) ;
--Ex- WAQ to display the employees who are working in ‘SALES’ or ‘RESEARCH’
Department
--Ex- find all employees who do not locate at the location ‘DALLAS
Select * from emp where deptno not in (select deptno from dep where loc=‘DALLAS’)
Whenever resource table is having large amount of data and also child query having
max or min aggregate function and also we are compairing values by using relational
comparator (<,>,<=,>=,=) then those types of query degrades the performance of the
application. To overcome this problem for improvement of query SQL provided
subquery special operators these are – ALL , ANY operators
These operators are used along with relational operator in parent query WHERE
condition.
IN It returns same values in the list of child query.
ALL It satisfies all values in the list of child query.
ANY It satisfies any value in the list of child query
You must place an =, <>, <, >, <=, or >= operator before ANY and ALL.
“=ANY” is Equivalent to ‘IN’ Operator.
>ALL means greater than every value--in other words, greater than the maximum
value. For Ex, >ALL (1, 2, 3) means greater than 3.
>ANY means greater than at least one value, that is, greater than the minimum. So
>ANY (1, 2, 3) means greater than 1.
--Ex- WAQ to display employees who are getting more salary than highest paid
employee of the department 20.
--Ex- WAQ to display the employees who are getting more salary then the all salary of
the CLERK from emp table.
Select * from emp where sal >ALL (select sal from emp where job=‘CLERK’);
--Ex- WAQ to find all employees whose salaries are greater than or equal to the
highest salary of every department.
Select * from emp where sal > any ( select max(sal) from emp group by deptno) ;
NOTE: If a subquery returns zero rows using ALL operator , the condition
evaluates to TRUE. In the following Ex, the subquery returns zero rows, which
means the whole expression "sal > ALL (zero rows)" evaluates to TRUE, so all
rows are displayed.
NOTE: Whenever we are using ALL operator in subquery then internally server
uses logical operator ‘AND’ operator. When we use Any operator in subquery
then internally server uses logical ‘OR’ operator.
In all DB we can also compare multiple columns values of child query table with
multiple column values of parent query table, these type of subqueries are called as
multiple column subqueries.
--Ex- WAQ to display the employees whos job ,mgr match with the job,mgr of the
employee ‘SCOTT’ from emp table.
Select * from emp where (job,mgr) in (select job,mgr from emp where
ename=‘SCOTT’) ;
--Ex- WAQ to display the employee who are getting highest salary from emp table
Select deptno, sal, ename from emp where (deptno, sal) IN (select deptno, max(sal)
from emp group by deptno ) ;
--Ex- WAQ to display sal,comm matching with sal,comm of the employees who are
working at location ‘DALLAS’
2..Correlated Subqueries
In correlated subqueries we must give alias names for parent query and then pass
alias name in child query WHERE condition.
It does not use IN and NOT IN clause.
If we want to modify 1 table column value based on another table column then only
we are using CORRELATED UPDATES.
If we want to delete 1 table column value based on another table column then only
we are using CORRELATED DELETE.
Whenever we are submitting co-related subqueries into the DB server then the DB
gets the candidate row from parent query table and then control passed to child
query WHERE condition and then based on evaluation values , it compares value with
parent query.
Whenever resource table is having duplicate data in column then above query
doesn’t return any result. To overcome this issue we must use DISTINCT clause.
EXISTS is much faster than IN, when the sub-query results is very large,the EXISTS
operator provides a better [Link] is faster than EXISTS, when the sub-query
results is very small.
The Exists keyword evaluates true or false, but IN keyword compare all value in the
corresponding sub query column.
--Ex- WAQ to find all departments which have at least one employee with the salary
is greater than 3000.
select [Link] from dep d where exists (select [Link] from emp e where [Link] > 3000
and [Link]=[Link]) ;
--Ex- WAQ to find all departments which don’t have at least one employee with the
salary is greater than 3000.
select [Link] from dep d where exists (select [Link] from emp e where [Link] > 3000
and [Link]=[Link]) ;
--Ex- WAQ to display those department names who have employees in emp table.
Select * from dep where exists (select deptno from emp);
--Ex- WAQ to display the employees who are getting same salary as ‘SCOTT’ from
emp table.
EXISTS IN
SQL Engine will stop the process as SQL Engine compares all values in IN
soon as it finds a single positive condition
condition in EXISTS condition
The answer of EXISTS can be TRUE or The answer of IN can be TRUE or
FALSE FALSE or NULL
EXISTS cannot compare values between IN compares values between parent
parent query and sub-query query and sub-query
It can be used to determine if any IN is used as multiple OR operator
values are returned or not
EXISTS is faster than IN if sub-query IN is faster than EXISTS if sub-query
result is large result is less
NULL can be compared using EXISTS NULL can be compared using IN
condition condition
JOINS SUBQUERY
It connects two or more tables and Subquery fetch the data from one
selects data from them into a single table based on inner query output.
result set.
joins are used to return rows. Subqueries can be used to return
either a scalar (single) value or a row
set.
Join shows the data in result set from Subquery will show the data in result
both joined tables. set from outer query result set only
Join are faster when large amount of Subquery is faster when small amount
data. of data.
Join condition is needed, to place join Join condition is not needed.
between multiple table.
Joins are used in the FROM clause of subqueries used in most clauses such
the WHERE statement as SELECT , WHERE, FROM, HAVING.
Difference between correlated and noncorrelated subquery :
CORRELATED NONCORRELATED
In correlated subquery, inner query is In non-correlated query inner query
dependent on the outer query does not dependent on the outer
query
It does not use IN and NOT In clause Non-Correlated subquery are used
along-with IN and NOT IN clause
Inner query can not run alone Inner query can run alone and it's not
depended on outer query
correlated subqueries are slower They are faster than correlated
queries subqueries
Inline View
Generally we are not allowed to use order by clause in child query to overcome this
problem oracle introduced subqueries in FROM clause these type of queries are
called INLINE VIEW .
Advantages:
We do not need to create the temporary table. This prevents the database
from having too many objects, which is a good thing as each additional object
in the database costs resources to manage.
We can use a single SQL query to accomplish what we want.
Generally we are not allowed to use column alias names in WHERE clause if we want
to use column alias name in WHERE clause then must use INLINE VIEW.
--Ex- select ename, sal, sal*12 annsal from emp where annsal > 3000;
ERROR: “ANNSAL” : Invalid identifier
Solution: select * from (select ename, sal, sal*12 annsal from emp)
where annsal > 3000 ;
update (select sal from emp INNER join dep using (deptno) where dname='Sales')
set sal = sal + 100;
following statement delete the Sales department employees whos salary is less than
1000:
delete (select sal from emp INNER JOIN dep using(deptno) where dname = 'Sales')
where sal < 1000;
Pseudocolumns are actually associated with the table data but it has nothing to do
with table [Link] & ROWNUM are pseudocolumns which are not actual
columns in the table but behave like actual columns.
Pseudocolumns are nothing but logical columns which behaves like a physical
columns in database.
** ROWID:
ROWID is nothing but the physical memory location on which that data/row is
[Link] basically returns address of row.
ROWID uniquely identifies row in database.
ROWID is combination of data object number,data block in datafile,position of
row and datafile in which row resides.
ROWID is 16 digit hexadecimal number whose datatype is also ROWID Or
UROWID
The fastest way to access a single row is ROWID
ROWID is unique identifier of the ROW.
** ROWNUM :
ROWNUM is magical column in Oracle which assigns the sequence number to
the rows at the time of selection in the table.
To limit the values in the table you can use ROWNUM pseudocolumn
ROWNUM is nothing but logical sequence number given to the rows fetched
from the table.
ROWNUM is logical number assigned temporarily to the physical location of
the row.
You can limit the values in the table using ROWNUM
ROWNUM is also unique temparary sequence number assigned to that row.
Ex: Select Rownum from dual;
Answer- 1
ROWID ROWNUM
ROWID is nothing but Physical memory ROWNUM is nothing but the
allocation sequence which is allocated to that
data at the time of selection.
ROWID is permanant to that row which ROWNUM is tempararily allocated
identifies the address of that row. sequence to the rows.
ROWID is 16 digit Hexadecimal number ROWNUM is numeric sequence
which is uniquely identifies the rows. number allocated to that row
temporarily.
ROWID returns PHYSICAL ADDRESS of ROWNUM returns the sequence
that row. number to that row.
ROWID is automatically generated ROWNUM is an dynamic value
unique id of a row and it is generated at automatically retrieved along with
the time of insertion of row. select statement output.
ROWID is the fastest means of ROWNUM is not related to access of
accessing data. data.
Top-N analysis
Top-N queries are useful in scenarios where the need is to display only the n top-
most or the n bottom-most records from a table based on a condition. This result set
can be used for further analysis. For Ex, using Top-N analysis you can perform the
following types of queries:
Top three earners in the company
Four most recent recruits in the company
Top two sales reps who have sold the maximum number of products
Top three products that have had maximum sales in the last six months
A WHERE clause, which specifies the n rows to be returned. The outer WHERE clause
must use a < or <= operator.
--Ex- WAQ to display first row from emp table using rownum.
Generally rownum doesn’t work with more than 1 positive integer i.e it works only
with < ,<= operators.
--Ex- WAQ to display first five highest salary employees from emp table.
Select * from (select * from emp order by sal desc) where rownum<=5;
--Ex- WAQ to find the top 4 senior most employees in the emp table.
select * from
(select ename,hiredate from emp order by hiredate) where rownum <=4;
select * from(select * from emp order by sal desc) where rownum <=5
minus
select * from(select * from emp order by sal desc) where rownum <=4;
select * from(select * from emp order by sal desc) where rownum <=7
minus
select * from(select * from emp order by sal desc) where rownum <=3;
Whenever we are using alias name for ROWNUM then in inline view that alias name
works with all SQL operators.
Select * from (select rownum r, e.* from emp e) where r between 3 and 7;
--Ex- WAQ to display first row and last row of emp table.
--Ex- WAQ to display 5th highest salary employee details from emp table.
Select * from (select rownum r, ename,sal from (select * from emp order by sal
desc)) where r=5 ;
** WITH Clause and ROWNUM
--Ex- WAQ to display ‘n’th highest salary employees from emp table
WITH highest_sal AS
(select * from emp order by sal desc)
select * from highest_sal where rownum<= &no ;
with high_3 as
(select rownum r, empno, ename, sal, deptno from (select * from emp order by sal
desc))
select * from high_3 where r=5;
--Ex- give the emp detail wos sal is greter than the avg sal
WITH temp as
(SELECT avg(Salary) avg from Employees)
select e.Employee_id, e.first_Name, [Link] FROM Employees e, temp
WHERE [Link] > [Link] order by [Link] desc;
With Dep_Count As
(Select Deptno,Count(Empno)No_Of_Emp From Emp Group by Deptno)
Select Empno, Sal/No_Of_Emp From Emp E, Dep_Count C Where [Link] =
[Link];
with a as
(select department_id, count(employee_id) cnt_emp from employees
group by department_id)
ANALYTIC FUNCTIONS
An aggregate function, as the name suggests, aggregates data from several rows into
a single result row.
For Ex, we might use the AVG aggregate function to give us an average of all the
employee salaries in the EMP table.
AVG(SAL) : 2073.21429
DEPTNO AVG(SAL)
---------- ---------------
10 2916.66667
20 2175
30 1566.66667
In both cases, the aggregate function reduces the number of rows returned by the
query.
Notice how the AVG function is still reporting the departmental average, like it did in
the GROUP BY query, but the result is present in each row, rather than reducing the
total number of rows returned.
The following query uses an empty OVER clause, so the average presented is based
on all the rows of the result set.
Omitting a partitioning clause from the OVER clause means the whole result set is
treated as a single partition. In the following Ex we display the number of employees,
as well as all the original data.
Using an empty OVER clause turns the MIN function into an analytic function. The
lack of a partitioning clause means the whole result set is treated as a single partition,
so we get the minimum salary for all employees, as well as all the original data.
Adding the partitioning clause allows us to display the minimum salary per
department, along with the employee data for each department.
Using an empty OVER clause turns the MAX function into an analytic function. The
lack of a partitioning clause means the whole result set is treated as a single partition,
so we get the maximum salary for all employees, as well as all the original data.
SELECT empno, ename, deptno, sal, MAX(sal) OVER () AS max_sal FROM emp;
Adding the partitioning clause allows us to display the maximum salary per
department, along with the employee data for each department.
SELECT empno, ename, deptno, sal, MAX(sal) OVER (partition by deptno) AS max_sal
FROM emp;
Omitting a partitioning clause from the OVER clause means the whole result set is
treated as a single partition. In the following Ex we display the total salaries of all
employees, as well as all the original data.
SELECT empno, ename, deptno, sal, SUM(sal) OVER () AS sum_sal FROM emp;
Adding the partitioning clause allows us to display total salary within a partition.
SELECT empno, ename, deptno, sal, MAX(sal) OVER (partition by deptno) AS sum_sal
FROM emp;
Using an empty OVER clause turns the AVG function into an analytic function. The
lack of a partitioning clause means the whole result set is treated as a single partition,
so we get the mean salary for all employees, as well as all the original data.
SELECT empno, ename, deptno, sal, AVG(sal) OVER () AS avg_sal FROM emp;
Adding the partitioning clause allows us to display the average salary per
department, along with the employee data for each department.
SELECT empno, ename, deptno, sal, AVG(sal) OVER (partition by deptno) AS avg_sal
FROM emp;
This analytical function uses to fetch first value from group depends on
analytic_clause without minimizing original table data.
The FIRST_VALUE analytic function is similar to the FIRST analytic function, allowing
you to return the first result from an ordered set.
SELECT empno,deptno,sal, FIRST_VALUE(sal) IGNORE NULLS OVER
(PARTITION BY deptno ORDER BY sal) AS lowest_in_dep FROM emp;
The "{RESPECT | IGNORE} NULLS" clause indicates if NULLs are considered when
determining results.
This analytical function uses to fetch last value from group depends on
analytic_clause without minimizing original table data.
The LAST_VALUE analytic function is similar to the LAST analytic function, allowing
you to return the last result from an ordered set. Using the default windowing clause
the result can be a little unexpected.
As with the previous function, the "{RESPECT | IGNORE} NULLS" clause indicates if
NULLs are considered when determining results. The default action is RESPECT
NULLS.
If the LEAD would span a partition boundary, the default value is returned. In the
following Ex we partition by department, so the SAL_NEXT column has a default
value of "0" for the last row in each department.
If the LAG would span a partition boundary, the default value is returned. In the
following Ex we partition by department, so the SAL_PREV column has a default
value of "0" for the first row in each department.
Unlike the RANK() function, the DENSE_RANK() function returns rank values as
consecutive integers. It does not skip rank in case of ties. Rows with the same values
for the rank criteria will receive the same rank values.
In the following Ex we assign a unique row number to each employee based on their
salary (lowest to highest). The Ex also includes RANK and DENSE_RANK to show the
difference in how ties are handled.
SELECT empno, ename, deptno, sal,
ROW_NUMBER() OVER (ORDER BY sal) AS row_num,
RANK() OVER (ORDER BY sal) AS row_rank,
DENSE_RANK() OVER (ORDER BY sal) AS row_dense_rank FROM emp;
Adding the partitioning clause allows us to assign the row number within a partition.
In the following Ex we assign the row number within the department, based on
highest to lowest salary.
--Ex- WAQ to display the employees details of highest salary to lowest salary and also
automatically assign RANK in each department from emp table.
Select * from (select deptno , ename, sal, row_number () over (partition by deptno
Order by sal desc)r from emp) where r <= 10;
--Ex- WAQ to display 2nd highest salary from emp table department wise.
Select * from (select deptno, ename, sal, dense_rank () over (partition by deptno
order by sal desc) r from emp) where r=2;
Select * from (select ename,sal,deptno, dense_rank () over (order by sal desc) r from
emp ) where r=5 ;
Select * from (select ename, job, sal, deptno , dense_rank () over (order by sal desc) r
from emp ) where r = &no;
ANALYTIC FUNCTION USING ROWID : We can use min (), max() with ROWID.
Select * from (select ename, sal, deptno , row_number () over (order by rowid) r
from emp) where r=2 ;
Select * from (select ename, sal, deptno, row_number ()over (order by rowid desc) r
from emp) where r <= 2;
--Ex- WAQ to display 2nd row of each department from emp table.
Select empno, count(*) from emp group by empno having count(*) >1;
(OR)
select * from emp where rowid in (select max(rowid) from emp group by empno);
Delete from emp where rowid not in (select max(rowid) from emp group by empno);
RANK DENSE_RANK
RANK might have gaps in the ranking DENSE_RANK doesnt have any gaps in
value the ranking value
RANK counts each tie as a RANKED row DENSE_RANK handles tie differently
VIEWS
View is a database object which is used to provides authority level of security.
Views do not contain any data
it is just a stored query in the database that can be executed when called.
All the data it shows comes from the base tables. One can think of a view as a
virtual table or logical table.
To create a view in your own schema, you must have the CREATE VIEW system
privilege. To create a view in another user's schema, you must have the CREATE ANY
VIEW system privilege.
[Link] security: Each user can be given permission to access the database only
through a small set of views that contain the specific data the user is authorized to
see, thus restricting the user's access to stored data.
[Link] Integrity: If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets the specified integrity
constraints.
[Link]: Views create the appearance of a table, but the DBMS must still
translate queries against the view into queries against the underlying source tables.
[Link] restrictions: When a user tries to update rows of a view, the DBMS must
translate the request into an update on rows of the underlying source tables. This is
possible for simple views, but more complex views are often restricted to read-only.
[Link] view :- Simple view is a view which is created on only one base table those
views called as simple view.
Contains only one single base table or is created from only one table.
We cannot use group functions like MAX(), COUNT(), etc.
Does not contain groups of data.
DML operations could be performed through a simple view.
INSERT, DELETE and UPDATE are directly possible on a simple view.
Simple view does not contain group by, distinct, pseudo column like rownum,
columns defined by expressions.
Does not include NOT NULL constraints(excuding not null) from base tables.
2. We must include base table NOT NULL column into the view only then after we are
allow to perform insertion operation through simple view.
NOTE: If you want to check structure of any view then we are using USER_VIEW
data dictionary.
Select * from user_views where view_name=‘V1’;
Select text from user_views where view_name=‘V1’;
Select * from USER_VIEWS_AE;
Views also used for simplifying query purpose i.e regularly used query we are putting
in view and whenever necessary select that view.
If query of view is using functions on column then we must use alias name for those
columns otherwise oracle server throughs error.
In oracle when query having rownum it also have a alias name otherwise it oracle
server throughs error.
Select * from v3 ;
The above all constraints we can assign to complex view as well as simple view.
[Link] View :
Complex view is a view which is created from multiple tables.
Contains more than one base tables or is created from more than one tables.
We can use group functions.
It can contain groups of data.
DML operations could not always be performed through a complex view.
We cannot apply INSERT, DELETE and UPDATE on complex view directly.
It can contain group by, distinct, pseudocolumn like rownum, columns defiend
by expressions.
NOT NULL columns that are not selected by simple view can be included in
complex view.
--Ex- create or replace view v4 as
Select ename,sal,dname,loc from emp e ,dep d where [Link]= [Link] ;
Generally we cant perform DML operation through complex view on base table.
In oracle when we are trying to perform DML operation through complex view to
base table then some other table column are effected so it will through error but if
we perform DML operation through complex view on base table and it doesn’t effect
any other table columns then DML operation will successfully completed as explain in
above Ex.
If we want to see effected and uneffected columns of any complex view then use
USER_UPDATEABLE_COLUMNS data dictionary
Generally in oracle also we cant perform DML operation on table through complex
view. To overcome this problem oracle 8.0 introduced INSTEAD OF TRIGGER in pl/sql.
When we create a INSTEAD OF TRIGGER on complex view then we are allow to
perfrom DML operations on base table.
By default INSTEAD OF TRIGGER is ROW LEVEL trigger.
**** Trigger:- Trigger is also same as stored procedure and also it will
automatically invoked whenever DML operation performed on base table.
You can choose the event upon which the trigger needs to be fired and the timing of
the execution. The purpose of trigger is to maintain the integrity of information on
the database.
Trigger Syntax:-
CREATE OR REPLACE TRIGGER trigger_name
BEFORE/AFTER Trigger specifications
INSERT [OR] / UPDATE [OR] / DELETE} ON table_name
(FOR EACH ROW)
WHEN (condition)
DECLARE
Declaration-statements
BEGIN Trigger Body
Executable-statements
EXCEPTION
Exception-handling-statements
END;
[Link] level trigger :- In statement level triggers , trigger body is executed only
once for DML statement.
[Link] level trigger:- In row level trigger, trigger body is executed for each row DML
statements. That’s why we are using “for each row” clause in trigger specification and
also DML transaction values are internally stored in two rollback statements
qualifiers,these are :OLD , :NEW are also called as record type variable.
Instead of trigger : Instead of trigger are row level trigger and also instead of trigger
are created on views.
Generally we cant perform DML operation through complex view on base table.
NOTE: in Oracle, the VIEW continues to exist even after one of the tables (that
the Oracle VIEW is based on) is dropped from the database. However, if you try
to query the Oracle VIEW after the table has been dropped, you will receive a
message indicating that the Oracle VIEW has errors.
If you recreate the table (the table that you had dropped), the Oracle VIEW will
again be fine.
[Link] View :-
A view can be created even if the defining query of the view cannot be executed. We
call such a view as view with errors or force views.
For Ex, if a view refers to a non-existent table or an invalid column of an existing table
or if the owner of the view does not have the required privileges, then the view can
still be created and entered into the data dictionary.
We can create such views (i.e. view with errors) by using the FORCE option in the
CREATE VIEW command:
NOTE: When Force command is used in the view syntax then even if select
statement is invalid, VIEW gets created successfully.
--Ex- In this example we are trying to create a view using a table that does not exist in
the database.
The advantage of force view is that in future if view script becomes valid, we can
start using the view.
force view is use basically for the situation when we create a view using a table but
the table is not created at that time we use force command;
You cannot use ALTER VIEW for removing a column or adding column. To recreate
the view without the column, use CREATE OR REPLACE VIEW.
Compile view- alter view view_name COMPILE ;
MATERIALIZED VIEW
Materialized views are also the logical view of our data-driven by the select query but
the result of the query will get stored in the table or disk, also the definition of the
query will also store in the database. MV also sync newly added data into it after
refreshing. Materialized view stores replication of remote database into loacl node.
A materialized view is a replica of a target master from a single point in time. The
master can be either a master table at a master site or a master materialized view at
a materialized view site. Whereas in multimaster replication tables are continuously
updated by other master sites, materialized views are updated from one or more
masters through individual batch updates, known as a refreshes, from a single master
site or master materialized view site, as illustrated in Figure
Advantages of MV:
[Link] : You can define a materialized view on a base table, partitioned table or
view and you can define indexes on materialized view
[Link] creation : Materialized Views can be created in the same database where
the base tables exists or in a different database as well.
5. Secure Sensitive Data: Users can only view data that satisfies the defining query
for the materialized view.
You should have create materialized views privileges to create a Materialized views.
Conn hr/hr
NOTE: before 10g version whenever user want to create MV on any table then that
table must have primary key but after 11g version user can create MV on any table
those don’t have any primary key at all.
Here in those both query both rowid are same (base table and view) that’s why view
doesn’t store any data so it is called as virtual table.
MV also stores data same like base table but when we are changing into base table
those changes not going to reflect into MV until we refresh MV.
After refresh MV will sync the data from base table.
Internally ROWID are created when we are refreshing MV. Every time ROWID are
dropped and again created in MV with complete refresh. The refresh is executed
within one single transaction, i.e. with a DELETE and INSERT statement and this is the
disadvantage of MV with complete refresh.
During this time, users can still use the materialized view and see the old data. At the
end of the refresh, the transaction is committed, and the new data is visible for all
users.
The advantage of this behavior is that the users can still use the materialized view
while it is refreshing.
This MV performance is very high compare to complete refresh MV. Because in this
MV rowid are not changed when we are refreshing MV number of times.
With this refresh method, only the changes since the last refresh are applied to the
materialized view.
Before we are create MV with fast refresh it need mechanism to catch any changes
made to its base tables. This refreshment is also called as ‘MV log’.
Specify FORCE if, when a refresh occurs, you want Oracle Database to perform a fast
refresh if one is possible or a complete refresh otherwise.
In REFRESH FAST Categories we saw an insert-only materialized view which could be
fast refreshed after inserts into the base table but needed a complete refresh after
other types of DML like update an old record of base table.
FORCE Clause With these types of materialized views it is often most convenient to
let Oracle decide which refresh method is best. The REFRESH FORCE method does
just that. It performs a FAST refresh if possible, otherwise it performs a COMPLETE
refresh.
select * from t2 ;
KEY T_KEY AMT
10 1 100
20 1 300
30 1 200
40 2 250
50 2 150
create materialized view log on t2 with primary key, rowid, sequence ( t_key, amt )
including new values;
First let's try an insert some records of base table and then refresh the mview based
on that table.
Since the rowids did not change but the AMT_MAX values did we can tell that a FAST
refresh was performed.
Now let's try a delete some record from base table then refresh the mview.
This time with REFRESH FORCE we did not got error “ORA-32314: REFRESH FAST of
"HR"."MV" unsupported after deletes/updates” . Instead Oracle performed a
COMPLETE refresh (note how the rowids for each row changed).
If the compile_state column shows NEEDS COMPILE, the other displayed column
values cannot be trusted as reflecting the true status. To revalidate the materialized
view, issue the following statement:
The updatable MV is only update the data at MV contain data but it doesn’t update
the base table data.
Note that the changes aren't pushed to the base table. As soon as you refresh it, the
changes are lost.
We can’t not update the MV to update base table its impossible to update base table
through MV.
If you require a materialized view whose defining query is more general and cannot
observe the restrictions, then the materialized view is complex and cannot be fast
refreshed.
*** can we modify Materialized view query . Is is possible to do the same without
droping and recreating it.
To modify the Materialized view you have to drop the materialized view first and
then recreate it.
No, you cannot alter the query of a materialized view without dropping it.
The CREATE MATERIALIZED VIEW syntax does not support that feature.
The START WITH value establishes the next automatic refresh for the materialized
view to be 9:00 a.m. tomorrow. At that point, Oracle Database performs a complete
refresh of the materialized view, evaluates the NEXT expression, and subsequently
refreshes the materialized view every week.
View Mview
View is nothing but the logical Materialized views (Snapshots) are
structure of the table which will also logical structure but data is
retrieve data from 1 or more table. physically stored in database.
When we are dropping base table When we are dropping base table
then view cannot be accessible. then MV can be accessible until you
perform next complete refresh.
View doesn’t store data Materialized view store the data
It uses for security purpose Improve performance purpose
Data access is not as fast as Data retrieval is fast as compare to
materialized views simple view because data is accessed
from directly physical location
Through view we can perform DML We cant perform DML operation on
operation on base table base table through MV.
View are basically sync with base table MV are not in sync with base table so
so it is auto refresh method without they need refresh explicitely.
using commit.
Base table rowid and view rowid are Base table rowid and MV rowid are
same different
SEQUENCE
Syntax
CREATE SEQUENCE sequence_name ---varchar2
[START WITH start_num] ---number
[INCREMENT BY increment_num] ---number (not null)
[MAXVALUE maximum_num | NOMAXVALUE] ---number
[MINVALUE minimum_num | NOMINVALUE] ---number
[CACHE cache_num | NOCACHE] ---varchar2(1)
[CYCLE | NOCYCLE]; ---varchar2(1)
START WITH
Here you have to specify a numeric value from which you want your sequence to
start. Start with clause can not be altered. START WITH can not be less than
MINVALUE.
Create sequence s_11;
INCREMENT BY
This attribute also takes a numeric value; to increment the sequence by the number
that you specify here will serve as the interval between sequence numbers.
INCREMENT BY value cannot be 0 but it can be any positive or negative value.
If this value is negative, then the sequence descends. If the value is positive, then the
sequence ascends. If you omit this clause, then the interval defaults to 1.
MAXVALUE / NOMAXVALUE
Using these attributes you can set the maximum upper bound for your sequence.
MAXVALUE must be equal to or greater than START WITH and must be greater than
MINVALUE attribute.
In case you don’t want to set the MAXVALUE for your sequence then you can use
NOMAXVALUE attribute.
MINVALUE / NOMINVALUE
we use MINVALUE attribute to set the lower bound of our sequence. As a value this
attribute also accepts the numeric value and it should be less than or equal to START
WITH as well as less than MAXVALUE. In case you don’t want to set the lower bound
for your sequence then you can use NOMINVALUE attribute instead.
CACHE/ NOCACHE
As the value of cache attribute, you specify the number of integers to keep in
memory. The default number of integers to cache is 20. The minimum number of
integers that may be cached is 2. The maximum integer that may be cached is
determined by the formula:
Specify NOCACHE to indicate that values of the sequence are not pre-allocated. If you
omit both CACHE and NOCACHE, the database caches 20 sequence numbers by
default.
CYCLE/NOCYCLE
If you set the flag on CYCLE then your sequence continues to generate values after
reaching either its maximum or minimum value.
When you set the CYCLE flag on then you have to must specify MAXVALUE and
MINVALUE parameter.
You specify NOCYCLE flag when you do not want your sequence to generate more
values after reaching its maximum or minimum value. If in case you omit both these
flags then by default oracle engine will set the flag on NOCYCLE.
If you want to generate sequence value or access sequence value then we are using
following 2 pseudo columns-
1). Currval 2). Nextval
If we want to generate sequence value by using select statement then we must use
dual table.
There is one another way you can create sequence like below-
Create sequence s_10;
Once you created the sequence and you want to check its current value then use it
This statement internally select the by default values for all clause of sequence as
below.
SEQUENCE MIN MAX INCREMENT CYCLE ORDER CACHE LAST
NAME value value BY FLAG FLAG SIZE NUMBER
S_10 1 1E28 1 N N 20 1
That means you can’t not RUN CURRVAL when sequence that doesn’t started.
You may have to RUN NEXTVAL statement first then you can run CURRVAL statement
after sequence initiated.
When you call s_10.nextval, the values from 1-20 will taken from the sequence and
cached in the SGA. When you call it again like s_10.nextval, the value 2 will be
returned but this value 2 is not taken from Sequence, it has been taken from Cache
(SGA). It will do so till your call reaches 21. So till 2 to 20 there is no "Real" call to
sequence and hence the improvement in [Link] 21 it will generate again
next 20 numbers in CACHE.
NOTE: cache size must be greater than cycle by default value (1) i.e cache must be
atleast 2. When you are using CYCLE parameter you must have MAXVALUE
specified in your sequence.
In Oracle 12c
Create sequence s_11;
In Oracle 11 g
Create sequence s_12
create table test (sno number(10) primary key, name varchar2 (20));
Above query will create a sequence named sequence_2.Sequence will start from 100
and should be less than or equal to maximum value and will be incremented by -1
having minimum value 1.
--Ex- Sequence using with Trigger- creating SEQUENCE with all defaults values
CREATE SEQUENCE my_sequence;
This sequence can then be used immediately in triggers when inserting new records
in a table:
How To Modify A Sequence: - There are some limitations on what you can modify in
a sequence such as:
Create is allow in sequence creation but replace is not allowed. Sequence
cannot be rollback.
You cannot change the start value of a sequence.
The minimum value cannot be more than the current value of the sequence.
The maximum value cannot be less than the current value of the sequence.
Suppose you want to modify the value of INCREMENT BY attribute from 2 to 4, so for
that ALTER SEQUENCE command will be:
Altering Sequences
To alter a sequence, your schema must contain the sequence, or you must have the
ALTER ANY SEQUENCE system privilege. You can alter a sequence to change any of
the parameters that define how it generates sequence numbers except the sequence
starting number. To change the starting point of a sequence, drop the sequence and
then re-create it.
Ex, the following statement alters the emp_sequence:
Drop sequence-
DROP SEQUENCE sequence_name ;
NOTE: If you using sequence in your insertion operation and after that you close
the session and then sequence CACHE will be flushed so after some time if you
started new session and used same sequence again then it will start from next
integer of flushed sequence numbers.
Now you fetch values from SEQUENCE. Let’s say I have fetched four times as shown
below.
After executing above four commands the value of the SEQUENCE will be 4. Now
suppose i want to reset the value of the SEQUENCE to 1 again. Follow all the steps in
the same order as shown below:
NEXTVAL CURRVAL
901 901
And I have taken some values from the sequence and its current value (currval) is
1436. Now I wanted to reset the sequence current value to 501 (smaller value).
INDEX
Index is database object which is used to retrieve data fastly from database.
Indexes are schema objects that are logically and physically independent of the data
in the objects with which they are associated. Thus, an index can be dropped or
created without physically affecting the table data. The index points directly to the
location of the rows containing that value.
Index are basically created on table columns.
SQL Indexes are nothing but way of reducing the cost of the query. More the cost of
the query less the performance of the query. The main task of query tuner is to
reduce the cost of the query using indexing, reduce the Full table scans, and reduce
the time to fetch the records from the query.
Indexes help speed up searching in the database. If there is no index on any column
in the WHERE clause, then the SQL server has to scan through the entire table and
check each and every row to find matches, which might result in slow operation on
large data.
**Advantages of Indexes:
**Disadvantages of Indexes:
[Link] slows down the performance of insert and update [Link] always
we need follow best practice of disabling indexes before insert and update the table
[Link] takes additional disk space so by considering memory point indexes are
costly.
1). Automatically /Implicit index :- In oracle whenever we are creating a primary key
or unique key in a table column then oracle server internally automatically B-tree
indexes on those columns.
2). Manually :- We can also create index explicitly by using following syntax-
A B-tree index has two types of blocks: branch blocks for searching and leaf blocks
that store values. The upper-level branch blocks of a B-tree index contain index data
that points to lower-level index blocks.
The root branch block has an entry 0-40, which points to the leftmost block in the
next branch level. This branch block contains entries such as 0-10 and 11-19. Each of
these entries points to a leaf block that contains key values that fall in the range.
A B-tree index is balanced because all leaf blocks automatically stay at the same
depth. Thus, retrieval of any record from anywhere in the index takes approximately
the same amount of time.
The leaf blocks contain every indexed data value and a corresponding rowid used to
locate the actual row. Each entry is sorted by (key, rowid). the leftmost leaf block (0-
10) is linked to the second leaf block (11-19).
Whenever we are specifying this clause oracle server internally automatically creates
plan table, which display query performance.
A function-based index is also useful for indexing only specific rows in a table. For Ex,
the cust_valid column in the [Link] table has either I or A as a value. To index
only the A rows, you could write a function that returns a null value for any rows
other than the A rows. You could create the index as follows:
--Ex- Create a function base index to show only month and year as hiredate from
emp table
--Ex- create function based index to calculate difference between two dates.
create index ind_delay
on emp (round(months_between('24/jan/2021', hiredate) / 12, 2)) ;
Cardinality of emp table on job column = 5/14 =0.357 --- Low cardinality
When 1 to 10 distinct values then bitmap indexes are very [Link] will improve the
performance of query drastically.
When distinct values between 100 –unlimited distinct values i will recommend you
not to use bitmap indexes. It will decrease the performance of queries.
If Table contains the distinct values which are not more than 20 distinct values then
user should go for Bit map [Link] should avoid the indexing on each and every
row and do the indexing only on distinct records of the table column.
You should able to check drastic change in query cost after changing the normal
index to Bit map index.
The bit map indexes are very much useful in dataware housing where there are low
level of concurrent [Link] map index stores row_id as associated key value
with bitmap and did the indexing only distinct [Link] If in 1 million records
only 20 distinct values are there so Bitmap index only stores 20 values as bitmap and
fetches the records from that 20 values only.
In bitmap structures, a two-dimensional array is created with one column for every
row in the table being indexed. Each column represents a distinct value within the
bitmapped index. This two-dimensional array represents each value within the index
multiplied by the number of rows in the table.
At row retrieval time, Oracle decompresses the bitmap into the RAM data buffers so
it can be rapidly scanned for matching values. These matching values are delivered to
Oracle in the form of a Row-ID list, and these Row-ID values may directly access the
required information.
The real benefit of bitmapped indexing occurs when one table includes multiple
bitmapped indexes. Each individual column may have low cardinality. The creation of
multiple bitmapped indexes provides a very powerful method for rapidly answering
difficult SQL queries.
remember that bitmap indexes are only suitable for static tables and materialized
views which are updated at night and rebuilt after batch row loading. If your tables
experience multiple DML's per second, BE CAREFUL when implementing bitmap
indexes!
1 - 7 distinct key values - Queries against bitmap indexes with a low cardinality
are very fast.
8-100 distinct key values - As the number if distinct values increases,
performance decreases proportionally.
Ex/Real Life Scenario: “Suppose There are 2 tables which has milions of [Link]
need to improve the performance of [Link] It is taking 4 mins to fetch 1 million
Records.”
Step 1: Explain Plan select * from DEP d,EMP e where [Link]= [Link];
Step 3: Check description of the table and check whether the normal index where the
Unique index and where bitmap indexes are applicable.
Step 5: EMPNO has unique values so kindly create UNIQUE INDEX ON that
[Link] has also unique values so for DEPTNO column we need to create
unique index.
and Results will come in 10 Seconds..Hope everyone get idea about basic indexing
and how it is been used in real life scenarios.
**Unique Index: :
Here the concept is bit [Link] needs to check the values of the table to create
unique [Link] table contains uniquely identified values in specified column then you
should use unique index.
Especially while creating the table if we specify the primary key then unique index is
automatically created on that [Link] for Unique key constaint columns you
separately need to do indexing. Kindly make sure that Unique key indexes created on
the columns which has unique values only.
--Ex- create table t_00 (sno number constraint sno_pk primary key);
Table will create unique index on primary key column and the name of the UNIQUE
index will be same as name of the PRIMARY KEY/UNIQUE constraint.
If you didn’t specify constraint name while table creation then index name will be
same as constraint name which will be generated by system.
**Composite Index:
When 2 or more columns in single table are related which each other and used in
where condition of select statement then user should create composite index on the
columns which are created. If all columns selected by in query are in composite index
then oracle will return the values from the index without accessing the table.
It has been suggested that using reverse-key indexes will speed-up Oracle INSERT
statements, especially with an increasing key, like an index on an Oracle sequence
(which is used for the primary key of the target table). For large batch inserts, Oracle
reverse key indexes will greatly speed-up data loads because the high-order index
key has been reversed.
--Ex- For example, by using a sequence to generate a primary key, the sequence will
generate values like :
987500,
987501,
987502,
and so on.
These values are sequential, so if I were using a conventional B*tree index, they
would all tend to go to the same right-hand-side block, thus increasing contention for
that block.
With a reverse key index, Oracle will logically index :
005789,
015789,
205789,
and so on.
Oracle will reverse the bytes of the data to be stored before placing them in the
index, so values that would have been next to each other in the index before the byte
reversal will instead be far apart.
This reversing of the bytes spreads out the inserts into the index over many blocks.
**Clustered Indexes:
The clustered indexes are indexes which are physically stored in order means it
stores in ascending or descending order in Database.
Clustered indexes are created one for each table.
When primary key is created then clustered index has been automatically
created in the table.
If table is under heavy data modifications the clustered indexes are preferable
to use.
What is mean by Global and Local Index? (Types of Indexes in SQL in term of access
of Table )
When there is partition on the table and we need to apply the indexes on that table
then we need to use global indexes or local indexes. When table is partitioned then
we need to use global or local parameters/keywords in DDL of create index
statement.
**Global Index:
Usually when you create index on the table has indexed but when you are using
partitioned table we need to change the syntax of the create index and need to use
the Global index for one to many relationship. Global index is one to many
relationships which allows index partition to map to many table partitions. The global
index can be partitioned by range or hash method and it can be defined on any kind
of partitioned or non partitioned table.
Syntax: Create index Indexname On table_name(Column_name)
GLOBAL
(PARTITION Partition_name values(value_of_partition),
PARTITION Partition_name values(value_of_partition),
PARTITION Partition_name values(value_of_partition),
PARTITION Partition_other values(value_of_partition));
**LOCAL INDEX:
Local indexes are indexes where there is one to one mapping between index partition
and table partition. These indexes are basically used to improve the performance of
partitioned tables. Local indexes directly uses divide and conquer approach to
generate the Fast and best execution plan of SQL Query.
Syntax: Create index indexname on table_name(Column_name)
LOCAL
(Partition Partition_name1,
Partition Partition_name2,
Partition Partition_name3….);
Alter Index:-
Rename indexes:- Alter index Index_name Rename to New_indexname;
Enable an Index: alter index index_name rebuild;
Disable an index: alter index index_name unusable;
You can check the status of index by using USER_INDEXES data dictionary.
select * from all_indexes where table_name = 'TABLE_NAME';
After run above query check the STATUS column of index if it is VALID then index is
enable if it is DIABLED means index is disabled.
If a query does not have a WHERE clause to filter out the rows which appear in the
result set, then a full table scan might be performed.
There are some scenarios in which a full table scan will still be performed even
though an index is present on that table.
If a query does have a WHERE clause, but none of the columns in that WHERE clause
match the leading column of an composite index on the table, then a full table scan
will be performed.
Even if a query does have a WHERE clause with a indexed column but still full table
scan can still occur. This situation arises when the comparison being used by the
WHERE clause prevents the use of an index. Here are some scenarios in which that
could happen:
If the NOT EQUAL (the “<>“) operator is used. An Ex is “WHERE NAME <>
‘XYZ'”. This could still result in a full table scan, because indexes are usually
used to find what is inside a table, but indexes (in general) cannot be used to
find what is not inside a table.
If the NOT operator is used. An Ex is “WHERE NOT NAME = ‘AAAA’”
If the wildcard operator is used in the first position of a comparison string. An
Ex is “WHERE NAME LIKE ‘%INTERVIEW%'”.
If IS NOT NULL/ IS NULL operator used then also full table scan will happen.
Rowid Scan: Rowid scan is the fastest Access paths to retrieve a single row, because
the exact location of the row is specified and optimizer does not perform any scan.
Rowid contains as shown in below diagram :-
The rowid of a row specifies the datafile and data block containing the row and the
location of the row in that block. Locating a row by specifying its rowid is the fastest
way to retrieve a single row, because the exact location of the row in the database is
specified.
To access a table by rowid, Oracle first obtains the rowids of the selected rows, either
from the statement's WHERE clause
or through an index scan of one or more of the table's indexes.
Oracle then locates each selected row in the table based on its rowid.
--Ex-
-----------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
-----------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 3 | 189 | 10 (10)|
| 1 | NESTED LOOPS | | 3 | 189 | 10 (10)|
| 2 | NESTED LOOPS | | 3 | 141 | 7 (15)|
|* 3 | TABLE ACCESS FULL | EMPLOYEES | 3 | 60 | 4 (25)|
| 4 | TABLE ACCESS BY INDEX ROWID| JOBS | 19 | 513 | 2 (50)|
|* 5 | INDEX UNIQUE SCAN | JOB_ID_PK | 1 | | |
| 6 | TABLE ACCESS BY INDEX ROWID | DEPARTMENTS | 27 | 432 | 2 (50)|
|* 7 | INDEX UNIQUE SCAN | DEPT_ID_PK | 1 | | |
-----------------------------------------------------------------------------------
The scenario where this index would be invoked is, Whenever the Oracle SQL
optimizer detects that the query is executable without touching table rows, Oracle
invokes this fast full index scan and quickly reads every block of the index without
touching the table itself provided that query doesn’t contain any ORDER BY clause.
The definition for this scan is more or less similar to the index full scan but the only
difference is that former will be invoked when ORDER BY clause is not mentioned in
the query. It differs from the index full scan in another way where output won’t be in
the sorted order since ORDER BY clause is not mentioned.
The major difference between fast full index scan and full index scan is that Index
fast full scan will be invoked only if ORDER BY clause is not mentioned in the query.
Another difference between fast full index scan and full index scan is that table
data will never be accessed at any cost if the Index fast full scan is invoked.
You can use fast full index scans by setting the OPTIMIZER_FEATURES_ENABLE
initialization parameter or using the INDEX_FFS hint.
ADVANTAGE:
If index full scan is followed, then we can eliminate full table scan completely
thereby we can reduce the execution time of query, number of data blocks to
be referred and I/O.
Since multi index blocks read is supported by this scan (unlike index full scan
where only single index block can be read at a time), query performance would
be good and better.
--Ex- explain plan for select /*+ index_ffs(departments dept_id_pk) */ count(*) from
departments;
If your table is having primary key and that primary key is using for filter condition in
WHERE clause then it will do INDEX UNIQUE SCAN also
--Ex- explain plan for select * from emp where empno =7839;
Optimizer will use a range scan for accessing selective data ( instead of unique row )
via using Index as follows.
Index Range Scan means the retrieval of one or more ROWIDs from an index. Indexed
values are generally scanned in ascending order.
Index Range Scan is applicable to both B*Tree Unique Index and B*Tree Non-Unique
Index unlike Index Unique Scan, where it is applicable only to B*Tree Unique Index.
If Oracle has to follow Index Range Scan, if B*Tree Unique index is created on the
table, then in the SQL, any non-equality operator must be used like <=, <, >, >=, IN,
BETWEEN. If any of these operators is used, it means more than one index record is
going to be referred in the index table and in turn which returns more than one
ROWID (because in the unique index, single index value is mapped to single ROWID.
So if 5 index records are accessed, it means 5 ROWIDs are retrieved).
If Oracle has to follow Index Range Scan, if B*Tree Non-Unique index is created on
the table, then in the SQL, it can have equality operator (=). If this is used, it means
only one index record is going to be referred in the index table and in turn which
returns more than one ROWID (because in the non-unique index, single index value is
mapped to more than one ROWID).
A composite index could only be used if the first column, the leading edge, of the
index was referenced in the WHERE clause of a statement.
However, if the leading column isn’t referenced now, Oracle can use the index
anyways via an Index Skip Scan access path
NOTE: If we want to view column names along with indexname then we are using
USER_IND_COLUMNS data dictionary.
SYNONYMS
Synonyms are database object which provide security. Oracle SQL / PLSQL uses
synonym as an alias name for any database object such as tables, views, sequences,
stored procedures, and other database object.
In other words we can say that in Oracle SQL / PLSQL a synonym is an alternative
name for database objects. Generally synonyms hides another schema username,
object name.
When you grant object privileges on a synonym, you are granting privileges on the
underlying object, and the synonym only acts as an alias in the GRANT statement.
In all DB by default synonym are Private synonym .
use the OR REPLACE option if you want to re-create the synonym if it already exists.
In case the synonym does not exist, the OR REPLACE has no effect.
1). Public Synonyms :- The synonym will be accessible for all the valid users, but the
user must have the sufficient privileges for the object to use its synonym.
Syntax:
CREATE OR REPLACE PUBLIC SYNONYM synonym_name FOR [Link]@dblink ;
Before we creating public synonym DBA first give us CREATE PUBLIC SYNONYM
system privilagesto user by using following syntax otherwise oracle server returns
error insufficient privilages
Syntax: grant create public synonym to user_name ;
2). Private Synonyms :- The synonym are only accessible to schema users.
Syntax:
CREATE OR REPLACE SYNONYM synonym_name FOR [Link]@dblink ;
--Ex - Suppose you have a table called employee in the schema owned by the user
HR, and you granted the SELECT privilege for the employee table to PUBLIC.
To query data from the employee table, you use the following statement:
Notice that you must include the name of the schema and table name in the query.
To simplify this query, you can create a public synonym using the following CREATE
PUBLIC SYNONYM statement:
Notice that the employee public synonym hides the name of the employee table and
its schema HR.
use the FORCE keyword to delete the synonym even if it has dependent tables or
user-defined types.
If you want to drop a private synonym, you must be the owner of the schema to
which the synonym belongs or you must have the DROP ANY SYNONYM privilege. In
case you want to drop a PUBLIC synonym, you must have the DROP PUBLIC
SYNONYM privilege.
CLUSTER
Cluster is database object which contains group of table together and also shares
same data block.
In all DB cluster DB objects are used to improve performance of the joins that’s why
cluster DB objects are created by DB administrators [Link] tables must have
common column name, common column is also called as CLUSTER KEY.
Generally clusters are created at the time of table creation.
In all DB whenever we are submitting INNER JOIN or OUTER JOIN then DB server
internally checks from clause tables are available in cluster or not ?
If those tables are available in cluster then DB server retrive data fastly from the
cluster table.
When to use a cluster : The ideal places to use a cluster are when you have a group
of tables that are frequently queried together.
Step1 :- create a cluster based on common column name, this common column name
is also called as cluster KEY.
Create table emp10 (empno number (10), ename varchar2(10), sal number (10),
deptno number (10)) cluster emp_dep (deptno);
Create table dep10 (deptno number(10), dname varchar2 (10), loc varchar2(10))
cluster emp_dep (deptno);
To see the structure of cluster table you can use USER_CLUSTERS, ALL_CLUSTERS,
and DBA_CLUSTERS data dictionary views :
You can check table structure so you will see the table has cluster or not.
NOTE: In oracle cluster tables having same ROWID. We cant not drop cluster, if
cluster is having tables to overcome this issue oracle 8.0 introduced including table
clause along with the drop cluster cluster_name which is used to drop cluster with
tables.
HIERARCHICAL QUERIES
You can use hierarchical queries to travel along parent-child relationships in your
data. For Ex, family trees, computer directory structures, and company organization
charts.
LEVEL : The position in the hierarchy of the current row in relation to the root node.
START WITH : You state which rows are the roots here. These are the rows that
appear at the "top" of the tree.
In a company org chart this is the CEO. Here that's employee_id 100, Steven King. So
you can begin the chart with him using:
CONNECT BY : You state the parent-child relationship here. This links the columns
that store the parent and child values. You access values from the parent row using
the keyword prior.
In a company each employee's "parent" is their manager. Thus you need to join the
parent row's employee_id to the child's manager_id. So you connect the prior
employee_id to the current manager_id, like so:
CONNECT_BY_ROOT : Returns the root node(s) associated with the current row.
SYS_CONNECT_BY_PATH : It can be useful to see values from all the rows between
the root and the current row. Sys_connect_by_path allows you to do this. It builds up
a string, adding the value from the first argument for the current row to the end of
the list. It separates these using the second argument.
PRIOR : is a unary operator which is used or indicates that “father of” the records or
first record.
Top down hierarchy : Whenever we are using PRIOR operator infront of child column
(employee_id) then oracle server uses TOP-BOTTOM search within tree structure.
--Ex- WAQ to display employees who are working under ‘BLAKE’ from employee table
--Ex- WAQ to find the tree structure data of employee table in asending order.
**NOCYCLE:
It's possible to store loops in your hierarchy. Usually this is a data error. But some
structures may contain loops by design.
For Ex, the following sets the CEO's manager to be a lowly programmer:
You can avoid this using the nocycle keyword. This spots when the query returns to
the same row. The database hides the repeated row and continues processing the
tree.
To use it, place nocycle after connect by:
This is another important unary operator in oracle which will gives the basic idea
about the root of the [Link] you want to see the boss’s hierarchy then user
needs to use connect_by_root keyword .
PARTITIONS TABLE
Partitioning is a divide-and-conquer approach to improving Oracle maintenance and
performance of the application in backup and recovery process.
Partition table are created by DB administrator in very large database (VLDB).
When To Partition?
There are two main reasons to use partitioning in a VLDB environment. These
reasons are related to management and performance improvement.
Partitioning offers:
Management at the individual partition level for data loads, index creation and
rebuilding, and backup/recovery. This can result in less down time because
only individual partitions being actively managed are unavailable.
Increased query performance by selecting only from the relevant partitions.
This weeding out process eliminates the partitions that do not contain the data
needed by the query through a technique called partition pruning.
When to Use partitioning:
When a table reaches a "large" size. Large being defined relative to your
environment. Tables greater than 2GB should always be considered for
partitioning.
When table performance is weak and we need to improve performance of
application.
Advantages of Partition:
[Link] Performance
[Link] availability
[Link] Simpler management
[Link] Partition:
When in the specified table the data is based on the specific date range and it is
properly divided in some range then user should go for the partitioned named as
‘Range Partition’.
This partition type is most common type of Table partitioning which is been useful for
Data warehouse to store the historical data in given date [Link] partitioning is
done in such way that the expression values lies within the specific [Link] kind of
Table partition is used when there is a particular date range available.
Syntax:
Create table Tablename (Col1 datatype(size)…..Coln datatype(size))
Partition by range(Column needs to be partitioned)
(Partition partition_name1 values less than(value1)….
Partition partition_name-n values less than(maxvalue));
Add partition:-
Alter table Employee add partition p5 values less than(50000);
Split partition:
Alter table Employee Split partition p1 at (5000) into (partition p10,partition p11);
*** To see how many partitioned tables are there in your schema give the
following statement
When there is a set of distinct values in the table which is properly divided then user
should go with list [Link] listing the distinct values user should do the partition.
Syntax:
Create table Tablename (Col1 datatype(size)….Coln datatype(size))
Partition by list (Column needs to be partitioned)
(Partition partition_name1 values (value1,value2,…)
Partition partition_name-n values (default));
Simple ex is the table storing the country data in which state is distinct [Link]
You can partition the table using list of state values.
Add new partition: Alter table Employee add partition p5_Kerala values(‘Kerala’);
--Ex-
CREATE TABLE sales_by_region_and_channel
(deptno NUMBER, deptname VARCHAR2(20), quarterly_sales NUMBER(10,2),
State VARCHAR2(2), channel VARCHAR2(1) )
PARTITION BY LIST (state, channel)
(PARTITION q1_north_direct VALUES (('OR','D'), ('WA','D')),
PARTITION q1_north_indirect VALUES (('OR','I'), ('WA','I')),
PARTITION q1_south_direct VALUES (('AZ','D'),('UT','D'),('NM','D')),
PARTITION q1_ca_direct VALUES ('CA','D'),
PARTITION rest VALUES (DEFAULT) );
--Ex- In the following Ex, names of individual partitions, and tablespaces(ts) in which
they are to reside, are specified. The initial extent size for each hash partition
(segment) is also explicitly stated at the table level, and all partitions inherit this
attribute.
[Link]
WITH temp as
(SELECT avg(Salary) avg from Employees)
select e.Employee_id, e.first_Name, [Link] FROM Employees e, temp
WHERE [Link] > [Link] order by [Link] desc;
With Dep_Count As
(Select Deptno,Count(Empno)No_Of_Emp From Emp Group by Deptno)
Select Empno, Sal/No_Of_Emp From Emp E, Dep_Count C Where [Link] =
[Link];
with a as
(select department_id, count(employee_id) cnt_emp from employees
group by department_id)
select d.department_id, a.cnt_emp from departments d left join a
where d.department_id = a.department_id ;