0% found this document useful (0 votes)
206 views

Structured Query Language (SQL) : Database

This document provides an overview of structured query language (SQL) and its components. SQL is used to retrieve data from databases and includes commands for data definition (DDL), data manipulation (DML), data retrieval (DQL), transaction control, and data control. It discusses SQL commands like CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE. It also covers data types, operators, and relational database management systems (RDBMS) like Oracle, SQL Server, MySQL.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
206 views

Structured Query Language (SQL) : Database

This document provides an overview of structured query language (SQL) and its components. SQL is used to retrieve data from databases and includes commands for data definition (DDL), data manipulation (DML), data retrieval (DQL), transaction control, and data control. It discusses SQL commands like CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE. It also covers data types, operators, and relational database management systems (RDBMS) like Oracle, SQL Server, MySQL.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

STRUCTURED QUERY LANGUAGE (SQL)

SQL :
SQL is used to fetch data from the data base for
reporting.
DATABASE :
It is a collection of meaningful data which can store in
the form of rows & columns in a table.
RDBMS :
Relational Database Management System
MANAGEMENT SYSTEM :
It is a software it help to manage the data base
management system should able to perform the following
activities very easily.
● Inserting the new file
● Upating the existing file
● Deleting unnecessary data
● Retriving the required data
EXAMPLES OF RDBMS :
● ORACLE
● SQL SERVER
● DBL
● MYSQL
● SYBASE
● TERA DATA.
SQL :
SQL pronounced as (SEQUEL) .This language is use to
communicate with oracle database.
SQL COMMANDS :
1. DDL -- DATA DEFINITION LANGUAGE
2. DML -- DATA MANIPULATION LANGUAGE
3. DRL/DQL -- DATA RETRIVAL/QUERY LANGUAGE
4. TCS -- TRANSACTION CONTROL LANGUAGE
5. DCL -- DATA CONTROL LANGUAGE.
1. DATA DEFINITION LANGUAGE :
This language is used to manage database objects.
These are 5 commads
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5.RENAME
NOTE :
* DDL can deal with structure (meta data).
* DDL commands have “auto commit” option.
* DDL commands can store operations that what we
perform & stores permantly.
* DDL commands deals with disc always.

DML

NO AUTO COMMIT

1. CREATE
To create a table to use CREATE command
SYNTAX :
CREATE table table_name(
Column1 datatype (size),
Column2 datatype (size),
----
----
Column3 datatype (size)
);
EX:
CREATE table python batch
(sno number(38),
Sname varchar2(100),
Sloc varchar2(100),
Srank number(10),
Sphone number(10)
);
2. ALTER :

WE use ALTER command to modification of the structure


of the table.
● We have 3 important ALTER commands are
A.ADD
B.MODIFY
C.DROP.
(a).ADD :
WE use ALTER+ADD for adding a new column in a new
table.
SYNTAX :
ALTER table table_name add(column1 datatype(size),
(column2 datatype(size),…);
EX:
ALTER table python batch add(sstate varchar2(100),
Scountry varchar2(100));
Table altered
(b) MODIFY :
We can use ALTER+MODIFY to change datatype
name& to change size of the column.
** TO VIEW TABLE STRUCTURE
SYNTAX : desc table_name;
desc python batch;

SYNTAX OF MODIFY :
ALTER table table_name modify(column name
Datatype(size),……);
EX :
ALTER table python batch modify(sstate
number(38));
table is altered
(c).DROP :
We can use ALTER+DROP to remove single column
(or) multiple column from the table in the database.
SYNTAX FOR ONE COLUMN :
ALTER table table_name drop columnname;
EX :
ALTER table python batch drop sstate;
Table altered
SYNTAX FOR MORE THAN ONE COLUMN :
ALTER table table_name drop(column1,column2,..);
EX :
ALTER table python batch drop(sstate,smail);
Table altered
3. DROP :
We use DROP command to remove objects from
the database such as table,view,index&structure….
SYNTAX :
DROP table table_name;
EX :
DROP table python batch;
Table altered
4. TRUNCATE :
We can use TRUNCATE command to remove the
data permently from the table.
SYNTAX :
TRUNCATE table table_name;
EX :
TRUNCATE table python batch;
Table truncated
NOTE :
● When we are doing TRUNCATE operation
data will be removed from the table
permently& structure remains same.
● There is no filter operation in TRUNCATE
command.
5. RENAME :
We can use RENAME to change name of the table.
SYNTAX :
RENAME old table_name to new table_name;
EX :
RENAME python batch to sql batch;
Table renamed
NOTE :
Whenever we are performing RENAME operation
the old names wont be available in database.
***FLASHBACK QUERY :
We use FLASHBACK QUERY to restores the
dropped table from the recycle bin.
SYNTAX :
FLASHBACK table table_name to before drop;
EX :
FLASHBACK table python batch to before drop;

2. DATA MANIPULATION LANGUAGE :


This language is used to manipulated the data
you have stored.it is collection of 4 commands.
1. INSERT
2. UPDATE
3. DELETE
1. INSERT :
WE use INSERT command to store and insert data .
To INSERT data into 3 methods
METHOD 1 :
SYNTAX :
INSERT into table_name values(coumn1,column2,..);
EX :
INSERT into emp values(111,’raju’,’IT’,’8765’,’23-JAN-
95’,400);
1 row created
**inserting the data into particular column.
METHOD 2 :
SYNTAX :
INSERT into
table_name(column1,column2,…)
values(value1,value2,…);
EX :
INSERT into
Emp(eno,ename,esal)
Values(565,raju,50000);
1 row created
METHOD 3 :
SYNTAX :
INSERT into
Table_name(column1,column2,…)
Values(&column1,&column2,…);
EX :
INSERT into
Emp(eno,ename,esal)
Values(&eno,&ename,&esal);
EXECUTION:
Enter value for emp no 565
Enter value for emp name :raju
Enter value for emp sal 50000
****
TO CHECK COUNT OF A TABLE
SELECT COUNT(*) FROM EMP;
2.UPDATE :
We can use UPDATE command to change required
value from the particular in the table.
SYNTAX :
UPDATE table_name set column=’new value’
Where column=’unique value for a record’;
EX :
UPDATE emp set job=’police’
Where empno=’102’;
1 row updated
3.DELETE :
We can use DELETE command to remove
single(or)multiple records from the table.
SYNTAX :
FOR SINGLE RECORD :
DELETE from table _name
Where column name= value;
EX :
DELETE from emp
Where esal=2000;
1 record deleted
FOR MULTIPLE RECORDS :
DELETE from table_name;
EX :
DELETE from emp;
Table deleted
DIFFERENCE BETWEEN DELETE/TRUNCATE
DELETE TRUNCATE
1.DML Command 1.DDL command
2.to remove the data from the 2.to remove the data from the
Table table
3.to use rollback after delete 3.we cannot use rollback
Command to get back the data because truncate can removes
data permently from the table
4.delete can store in buffer 4.truncate can remove the data
permently but structure
remains same
5.delete has temporary memory 5.truncate has no temporary
memory to store the data
6.delete can be performs slowy 6.truncate performance is high
Because of buffer . because of no buffer.
3. DATA RETRIVIAL/QUERY LANGUAGE :
This language is used to retrive the data from
database. It is a collection of only one command.
1. SELECT
1.SELECT :
SYNTAX :
SELECT * from table_name;
Where * -- all columns of a table
EX :
SELECT * from emp;
SELECT ename,eno,esal ;
*PURGE :
PURGE is to drop (or) delete data permently
not in recycle bin also.
SYNTAX :
DROP table table_name PURGE;
EX :
DROP table emp PURGE;
4. TRANSACTION CONTROL LANGUAGE :
It is used to maintain the transactions of
oracle database.it has 3 commands
1. COMMIT
2. ROLLBACK
1. COMMIT :
It is used to save the data Permently.
SYNTAX :
COMMIT;
2. ROLLBACK :
It is used to get back data from recycle bin.
*to use before commit rollback cannot work.
SYNTAX :
ROLLBACK;
5.DATA CONTROL LANGUAGE :
This language is used to control the axis of data
to the users.it has 2 commands
1. GRANT
2. REVOKE

1. GRANT :
To give access to any one to use GRANT for
authentication.
2. REVOKE :
It give access then it will be take back
permissions to user.

DATA TYPES
DATA TYPES :
We use data types to store values in a
database.
● CHAR
● VARCHAR2
● NUMBER
● DATE
1.CHAR :
CHAR datatypes is used to store text
information. CHAR datatype size is 2 thousand.
2.VARCHAR2 :
VARCHAR2 datatype is used to store text
information. And VARCHAR2 datatype size is 4000.

3. NUMBER :
NUMBER data type to store integer &
decimal values in database.NUMBER datatype size is
‘38’. It is type.
It is default datatype.
● We can specify NUMBER datatype
without metric size as well.
NUMBER(P,S)
P—pre
s---scale
p s
300.70
4. DATE :
*We can use DATE datatype to store date
values.

* default DATE is “DD-MON-YY”


BLANK PADDED MECHANISM :
● We can use CHAR&VARCHAR2 datatype to
store text information in database.
● If we use CHAR datatype then it will
occupy complete memory for a given
range.
● If we use VARCHAR2 datatype then it will
be occupy “only memory for
values”.eventhough if you specify any
range of values.

OPERATORS
SQL operators is a special symbol in database which
can be used for mathematical & logical operators.
1. ARITHMETIC OPERATORS
2. COMPANISION/RELATIONAL
OPERATORS
3. LOGICAL OPERATORS
4. SPECIAL OPERATORS
1. ARITHMETIC OPERATORS :
We can use ARITHMETIC OPERATORS for
mathematical operators.
1. ADD(+)
2. SUBSTRACT(-)
3. MULTIPLY(*)
4. DIVISION(/)
EX :
MULTIPLY :
-SELECT ename,sal,sal*12 from emp;
SUBSTRACT :
-SELECT ename,sal,sal-300 from emp;
ADD :
-SELECT ename,sal,sal+300 from emp;
DIVISION :
-SELECT ename,sal,sal/30 from emp;
2.COMPANISION/RELATIONAL OPERATORS :
We can use COMPANISION OPERATORS is
comparing values in the tabe.
● = → EQUALS TO
● > → GREATER THAN
● >= → GREATER THAN OR EQUALS
TO
● < → LESS THAN
● <= → LESS THAN OR EQUALS TO
● <> → NOT EQUALS TO
EX :
EQUALS TO :
-SELECT * from emp
where ename=’raju’;
GREATER THAN :
-SELECT * from emp
where sal>2000;

LESS THAN :
-SELECT * from emp
where sal<1000;
GREATER THAN OR EQUAL TO :
-SELECT * from emp
where sal>=3000;
LESS THAN OR EQUAL TO :
- SELECT * from emp
where sal<=3000;
NOT EQUAL TO :
- SELECT * from emp
where sal<>3000;

3. LOGICAL OPERATORS :
We can use LOGICAL OPERATORS to perform
logical conditions in a table.
● AND
● OR
● NOT
1. AND :
-If all the conditions what ever we are passing
in select statements must specify the conditions then
only it will be print the data.
-if one condition is false then it won’t print any
data from the table.
-display the emp who is working as a salesman
under dep no =10 from emp table
----SELECT * from emp
where job=’salesman’;
(true)
----SELECT * from emp
where job=’salesman’ and dep no=10;
(false)
No row selected
Note :
AND operator will search for the data from
“conditions output”.
2. OR :
-In OR operator any one condition satisfy (or)
true then it is going to display the data from the table.
-all conditions are “independent in select”
statement.
EX :
SELECT * from emp
where job=’salesman’ or dep no=30;
3.NOT :
-it is going to return the data “based on NOT
operator “ in the select table.
-display the employee expect salesman records from
emp.
--SELECT * from emp
where NOT job=’salesman’;
4.SPECIAL OPERATORS :
IN NOT IN
BETWEEN NOT BETWEEN
LIKE NOT LIKE
IS NULL IS NOT NULL

IN :
-Display emps who is working as salesman & clerks
from emp table?
---- SELECT * from emp
where job IN (‘salesman’,’clerk’);
NOT IN :
-Display how many emps are there from emp
table except salesman & clerks ?
----SELECT count(*) from emp
Where job NOT IN (‘salesman’,’clerk’);
BETWEEN :
-Display the emps who is getting sal from 2000 to
5000 ?
-----SELECT * from emp
Where sal BETWEEN 2000 and 5000;
(and---to find range of values)
--dispay the emps from emp table who have joined
from 1981 to 1982 ?
----SELECT * from emp
Where hiredate BETWEEN’01-JAN-81’ and ’01-jan-
82’;
NOT BETWEEN :
SELECT * from emp
Where sal NOT BETWEEN 2000 and 5000;
LIKE :
IN this operator used to emp from tabe who’s
letter starts with ‘A’ ?

SELECT * from emp


Where ename LIKE ‘%A’;

*%A—ENDS WITH ‘A’ LETTER


A%---STARTS WITH ‘A ‘LETTER
--Display total number of emps who has joined in
April month

SELECT COUNT(*) emp


Where hiredate LIKE ‘%APR%’;
EX :
select * from emp
where ename LIKE 'S%';

(Emp name starts with S Letter)

select * from emp


where ename LIKE '%S’;
(Emp name ends with S Letter)

NOT LIKE :

select * from emp


where ename NOT LIKE 'S%';

(Emp name not starts with S Letter)

select * from emp


where ename NOT LIKE '%S' ;

(Emp name ends with S Letter)


NULL :
NULL is not a zero not a value “NULL is a absence
of value”.
NULL is not equal to zero
---display NULL values from commission column
using emp table ?
SELECT * from emp;
NOT NULL :
Except NULL values
SELECT * from emp;
Where comm is NOT NULL ;

NVL FUNCTION :
We use NVL function to “hande null values in a
database”.
SYNTAX :
NVL(EXP1,EXP2)
EX :
--NVL(NULL,20) →20
--NVL(20,80) →20
--NVL(100,NULL) →100
--NVL(NULL,NULL) →NULL

--SELECT ename,sal,comm,sal+NVL(comm,0) as total


from emp;
SELECT QUERY FLOW

● SELECT
● FROM
● WHERE
● GROUP BY
● HAVING
● ORDER BY
SELECT :

IN this SELECT statement we specify column names.


FROM :
IN this FROM clause we specify table names.
WHERE :
IN this WHERE clause we specify filter conditions.
GROUP BY :
IN this GROUP BY clause to group of data from the
table.
HAVING :
IN this HAVING clause to group of data from group by
output.
ORDER BY :
IN we use ORDER BY clause to sort the data in
ascending order (or) descending order of data.
--can we pass WHERE clause without GROUP BY?
(NO)
--can we use HAVING clause without GROUP BY?
(YES)but it apply the table data.
Difference between where clause & having clause
*where clause can be filter the rows from the table
data.
*having clause filter the data from group by outD
SQL FUNCTIONS

1. NUMBER FUNCTIONS
2. CHARACTER FUNCTIONS
3. DATE FUNCTIONS
4. GROUP FUNCTIONS

1.NUMBER FUNCTIONS :
ABS → abs(value)
In this abs function to avoid negative(-) to positive
sql>select abs(-900) from dual;
abs (-900)
900
MOD → mod(value1,value2)
In this mod function gives remainder value
sql>select mod(7,2) from dual;
mod (7,2)
1
ROUND → round(value),round(value1,value2)
In this round function avoids fraction value if it is
50% of above in fraction to add 1 in front value
sql>select round(100.547) from dual;
if fraction part 547 it is above 500% so add 1
round(100.547)
101.
TRUNCATE → trunc(value),trunc(value1,value2)
In this trunc to removes fraction part
sql>select trunc(100.56) from dual;
trunc(100.56)
100.
GREATEST → greatest(value1,value2,value3,….)
In this greatest to give highest valve
sql>select greatest(100,20,50) from dual;
greatest(100,20,50)
100.
CIEL → ceil(value)
In this function is gives nearest greatest value
sql>select ceil(1.2) from dual;
ceil(1.2)
2
FLOOR → floor(value)
In this function is gives nearest lowest value
sql>select floor(2.9) from dual;
floor(2.9)
2

2. CHARACTER FUNCTIONS :

LOWER → lower(ENAME)
In this function to make it lower case letters
sql>select lower(ENAME) from emp;
lower(‘RAJU’)
raju
UPPER → upper(ename)
In this function to make it upper case letters
sql>select UPPER(ename) from emp;
UPPER(‘raju’)
RAJU
INITCAP → initcap(ENAME)
In this function to make first letter is upper letter
sql>select initcap(ENAME) from emp;
initcap(‘raja sekhar reddy’)
Raja Sekhar Reddy
CONCAT → concat(exp1,exp2)
In this function to add two arguments in one
argument
sql>select concat(‘wel’,’come’) from dual;
concat(‘wel’,’come’)
welcome
LENGTH → length(ENAME)

In this function to give length (no) of a data,space


also includes one length
sql>select length(‘raju’) from dual;
length(‘raju’)
4
sql>select length (raju--) from dual;
6

2. CHARACTER FUNCTIONS :

SUBSTRING
SUBSTR →
SUBSTR(EXP1,EXP2)/SUBSTR(EXP1,EXP2,EXP3)
In this substring to get datatype in which position wil be
taken.
sql>select substr(‘BANGALORE’,3) from dual;
---- NGALORE
sql>select substr(‘RAJU’,2) from dual;
----AJU
IN substring substr(exp1,exp2,exp3) in exp3 will be no of
characters will be taken.
sql>select substr(‘BANGALORE’,3,3) from dual;
-----NGA
sql>select substr(‘EXPRSDATA’,6,4) from dual;
------DATA

INSTRING
INSTR(exp1,exp2)
In this function the exact position of character will
given.
sql>select instr(‘[email protected]’,’@’) from dual;
----5 (position)

LPAD
LPAD → lpad(exp1,exp2,exp3)
In lpad to gives adding the characters in the lift side of a
expression.
sql>select lpad(‘RAJU’,2) from dual;
-----RA
sql>select lpad(‘RAJU’,5,’#’) from dual;
----#RAJU(to occupied 5 position ‘#’)
sql>select lpad(‘RAJU’,8,’#’) from dual;
-----####RAJU
sql>select lpad(‘RAJU’,8,’*’) from dual;
------****RAJU
sql>select lpad(‘RAJU’,8) from dual;
---- RAJU(SPACE allocate 4 positions in lift side)

RPAD
RPAD → rpad(exp1,exp2,exp3)
In this RPAD gives to add in right side of expression.
sql>select rpad(‘RAJU’,2) from dual;
----JU
sql>select rpad(‘RAJU’,5,’#’) from dual;
----#RAJU
sql>select rpad(‘RAJU’,8,’#’) from dual;
----RAJU####
sql>select rpad(‘RAJU’,8,’*’) from dual;
-----RAJU****
sql>select rpad(‘RAJU’,8) from dual;
----RAJU (4 positions space allocated)
LTRIM
Ltrim(exp1,exp2)
In this LTRIM to remove unwanted spaces in lift
side.
sql>select
length(‘INDIA’),length(‘INDIA’),length(ltrime(‘
india’)) from dual;
length(INDIA) length(_INDIA) length(ltrim(INDIA))
5 6 5

RTRIM
RTRIM → rtrim(exp1,exp2)
In this rtrim can be remove unanted spaces in right side.
sql>select
length(‘INDIA’),length(‘INDIA’),length(rtrime(‘
india ’)) from dual;
length(INDIA) length(INDIA _) length(rtrim(INDIA))
5 6 5

REPLACE
REPLACE → replace(exp1,exp2,exp3)
In this REPLACE can be used string by string.

sql>select replace(‘INDIA’,’I’,’xy’) from dual;


------xNDxA
( I is replace x only by string only)
TRANSLATE
TRANSLATE → translate(exp1,exp2,exp3)
In this TRANSLATE can be used character by
character.

sql>select translate(‘INDIA’,’I’,’xy’) from dual;


-----xyNDxyA
( I is translate into xy by character by character)
3. DATE FUNCTIONS :
SYSDATE (**sysdate should be in
(dd-mon-yy1)(02-jan-20)

In this sysdate is system date or current date.


Select sysdate from dual;
ADD_MONTHS
Select add_months(‘sysdate’,’+8’) from
dual;
IN This ADD_MONTHS to adding months in the data.

LAST_DAY
In this LAST_DAY Given if any date can be given to find the
last day of the That particular given date of last day can be
executed.
NEXT_DAY
In this NEXT_DAY gives the date to give any date of week
of next day in the month will be shown.
MONTHS_BETWEEN
In this MONTHS_BETWEEN can be givs the difference
between one date/monthyear to
anotherdate/months/years.
3.GROUP FUNCTIONS :
MIN() FUNCTION
In this MIN() FUNCTION return the lowest value of a
column.
SYNTAX :
Select min(column_name)
FROM table_name
WHERE condition ;
In emp table
sql>select MIN(sal) from emp;
------MIN(sal)
4000
MAX() FUNCTION
In this function returns the largest value of the column.
SYNTAX :
SELECT MAX(column_name)
FROM table_name
WHERE condition ;
In emp table
sql>select MAX(sal) from emp;
-----MAX(sal)
20000
AVG() FUNCTION
The AVG() function returns the average value of a
numeric column.
SYNTAX :
SELECT AVG(column_name)
FROM table_name
WHERE condition ;
In EMP table
sql>select AVG(sal) from emp;
------AVG(sal)
2000
SUM() FUNCTION

numeric column.
SYNTAX :
SELECT SUM(column_name)
FROM table_name
WHERE condition;
In EMP table
sql>select SUM(sal) from emp;
------SUM(sal)
40000
COUNT() FUNCTION :

table.
SYNTAX :
SELECT COUNT(column_name)
FROM table_name
WHERE condition ;
In EMP table
sql>select COUNT(sal) from emp;
-----COUNT(sal)
7(rows)
USING GROUP BY
ROLLUP

extra row to represents the subtotals(or) grand total of


rows in DOWN the rows.
Select emp(sal)
From emp
Group by emp(sal);
-------emp(sal)
200
100
400
ROLLUP-------700(TOTAL SAL)
CUBE() :

row to represents the subtotals(or) grand total of rows in


TOP the rows.
Select emp(sal)
From emp
Group by emp(SAL);
-------EMP(sal)
CUBE-------700(TOTAL SAL IN TOP)
200
100
400.

SET OPERATIONS IN SQL

• Set operations which can be performed on


table data.
• Which gives meaning ful results from data
stored in the table.
• 4 types of set operations in sql.

1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS
CONDITIONS OF SET OPERATIONS
In this conditions will be satisfies then set
operations will be applied if not satisfied
those conditions set operations not taken.
1.in both tables having same columns.
2.both tables having same data types.

1.UNION
• UNION is used to combine the results of
two or more SELECT statements.
• It eliminates duplicates rows from the
resultset.
• In this union,number of columns and
datatypes must be same in both
tables,then UNION operations being
applied.
• It does not allows duplicate rows.
SYNTAX :
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2;
EX :
To create tables EMP1 and EMP2.
EMP1 TABLE :
ENO ENAME
1 A
2 B
EMP2 TABLE :

ENO ENAME
2 B
3 C

RESUIT :
Select * from EMP1;
UNION
Select * from EMP2;
ENO ENAME
1 A
2 B
3 C
2.UNION ALL :
• It is similar to union operation.
• But it allows the duplicate rows.
SYNTAX :
SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2;
EX :
To create tables EMP1 and EMP2.

EMP1 TABLE :
ENO ENAME
1 A
2 B
EMP2 TABLE :

ENO ENAME
2 B
3 C

RESUIT :
Select * from EMP1;
UNION ALL
Select * from EMP2;
ENO ENAME
1 A
2 B
2 B
3 C
INTERSECT :
• INTERSECT operation is used to combine
two SELECT statements.
• But it ony returns the records which are
common from both SELECT statements.
• It has also no of columns and datatype must
be same.
SYNTAX :
SELECT * FROM TABLE1
INTERSECT
SELECT * FROM TABLE2;
EX :
To create tables EMP1 and EMP2.
EMP1 TABLE :
ENO ENAME
1 A
2 B
EMP2 TABLE :

ENO ENAME
2 B
3 C
RESUIT :
Select * from EMP1;
INTERSECT
Select * from EMP2;
ENO ENAME
2 B

4.MINUS :
• The MINUS operation combines results
of two SELECT statements.
• It return only those in the final
result,which belongs to the first set of
result.
SYNTAX :
SELECT * FROM TABLE1
MINUS
SELECT * FROM TABLE2;
EX :
To create tables EMP1 and EMP2.

EMP1 TABLE :
ENO ENAME
1 A
2 B
EMP2 TABLE :

ENO ENAME
2 B
3 C
RESUIT :
Select * from EMP1;
MINUS
Select * from EMP2;
ENO ENAME
1 A
JOINS
It is fetching and retrieving the data from
multiple tables at a time.
1.ANSI format joins(‘on’).
2.NON-ANSI format joins(‘where’).
1.ANSI format joins(‘on’).
In this join can be fetching data by using ‘on’
keyword into to join the conditions.
Types
1.INNER JOIN
2.OUTER JOIN
A.LEFT OUTER JOIN
B.RIGHT OUTER JOIN
C.FULL OUTER JOIN
3.CROSS JOIN.
1.INNER JOIN :
It using the condition ‘equality(=)’
To satisfy this conditions
1.in both tables having same columns.
2.both tables having same data types.
SYNTAX :
SELECT * FROM
TABLE1 INNER JOIN TABLE2 ON
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME

EX :
TO create two tables STUDENT and
COURSE .
TABLE1 : STUDENT

SNO SNAME SCOURSEID


1 A 101
2 B 102
3 C 103
TABLE2 : COURSE

CNO CNAME CCOURSEID


4 N 101
5 O 104
6 P 105
RESULT :
Select * from
STUDENT inner join course on
Student.scourseid=course.ccourseid;

SNO SNAME SCO_ID CNO CNAME CCO_ID


1 A 101 4 N 101

In this to selected matched records only will


be taken.

2.OUTER JOIN :
( MATCHED + UN MATCHED RECORDS)
A.LEFT OUTER JOIN :
In this to retrieve the matched data with
LEFT SIDE table data also taken.
SYNTAX :
SELECT * FROM
TABLE1 LEFT OUTER JOIN TABLE2 ON
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME
EX :
TO create two tables STUDENT and
COURSE .
TABLE1 : STUDENT
SNO SNAME SCOURSEID
1 A 101
2 B 102
3 C 103
TABLE2 : COURSE

CNO CNAME CCOURSEID


4 N 101
5 O 104
6 P 105
RESULT :
Select * from
STUDENT left outer join course on
Student.scourseid=course.ccourseid;

SNO SNAME SCO_ID CNO CNAME CCO_ID


1 A 101 4 N 101
2 B 102 NULL NULL NULL
3 C 103 NULL NULL NULL

B.RIGHT OUTER JOIN :

In this to retrieve the matched data


with RIGHT side table data also taken.
SYNTAX :
SELECT * FROM
TABLE1 RIGHT OUTER JOIN TABLE2 ON
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME
EX :
TO create two tables STUDENT and
COURSE .
TABLE1 : STUDENT

SNO SNAME SCOURSEID


1 A 101
2 B 102
3 C 103
TABLE2 : COURSE

CNO CNAME CCOURSEID


4 N 101
5 O 104
6 P 105

RESULT : Select * from


STUDENT right outer join course on
Student.scourseid=course.ccourseid;
SNO SNAME SCO_ID CNO CNAME CCO_ID
1 A 101 4 N 101
NULL NULL NULL 5 O 104
NULL NULL NULL 6 P 105

C.FULL OUTER JOIN :

In this to retrieve the matched data


and unmatched data taken.NULL values not
taken.

SYNTAX :
SELECT * FROM
TABLE1 FULL OUTER JOIN TABLE2 ON
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME

EX :
TO create two tables STUDENT and
COURSE .
TABLE1 : STUDENT
SNO SNAME SCOURSEID
1 A 101
2 B 102
3 C 103
TABLE2 : COURSE

CNO CNAME CCOURSEID


4 N 101
5 O 104
6 P 105
RESULT :
Select * from
STUDENT full outer join course on
Student.scourseid=course.ccourseid;
SNO SNAME SCO_ID CNO CNAME CCO_ID
1 A 101 4 N 101
2 B 102 5 O 104
3 C 103 6 P 105

3.CROSS JOIN :
In CROSS JOIN is used to generate a paired
combination of each row of the first table with
each row of the second table.it is also known as
cartesian join.
SYNTAX :
SELECT * FROM
TABLE1 CROSS JOIN TABLE2;
2.NON-ANSI JOIN : (‘WHERE’)
1.EQUI JOIN
2.NON-EQUI JOIN
3.SELF JOIN.
1.EQUI JOIN :
In this join to retrieve data with ‘equal(=)’
condition.
SYNTAX :
SELECT * FROM
TABLE1,TABLE2 WHERE
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME

2.NON-EQUI JOIN :
In this join to retrieve data with
(‘ <’ ,’ >’ ,’ <=’ ,’ >=’ ) conditions.
SYNTAX :
SELECT * FROM
TABLE1,TABLE2 WHERE
TABLE1.COLUMN_NAME (<,>,<=,>=)
TABLE2.COLUMN_NAME

3.SELF JOIN :
A SELF JOIN is a regular join ,but the
table is joined with itself.
SYNTAX :
Select A.COLUMN_NAME,B.COLUMN_NAME
From TABLE A,TABLE B
WhereA.COMMON_FIELD=B.COMMON_FIELD;
SQL CONSTRAINTS

➢ CONSTRAINTS are used to stop invalid


data entry into tables.
➢ We use CONSTRAINTS for columns in
the table.
➢ 5 types CONSTRAINTS are there.
TYPES OF CONSTRAINTS :
1.NOT NULL
2.UNIQUE
3.PRIMARY KEY
4.FOREIGN KEY
5.CHECK.
1.NOTNULL :
➢ NOT NULL doesn’t support NULL VALUES.
➢ It will accept DUPLICATE VALUES.
NOTE :
❖This CONSTRAINT is not supported
for TABLE LEVEL.
EX :
CREATE table clg(cno number(10) NOT
NULL,cname varchar2(1000));
Table created
Insert into clg values(10,’raj’);
1 row created
Insert into clg values(‘ ‘,’raj’);
Error
Error due cno is not null.and the duplicate
allows ‘raj’ will be taken several times only
if you mention value as not null constraint
will be mustSatisfy is not null(absence of
number).
Insert into clg values(null,’raj’); → error
2.UNIQUE :
➢ UNIQUE constraint doesn’t accept
duplicate values.
➢ But it will accepts null values.
Reciprocal to not null.
➢ This is defined at column level & at
table level.
EX :
CREATE table clg(cno number(10)
UNIQUE,cname varchar2(1000));
Table created
Insert into clg values(‘ ‘,’raj’);
1 row created (accept null values)
Insert into clg values(‘10’,’raja’);
1 row created (not accept duplicate)
Insert into clg values(‘10’,’raju’);
Error
❖In this unique constraint to spicify
column will be unique that means it
accept null value and not accept
duplicate value in specified
columnname.
3.PRIMARY KEY :
➢ PRIMARY KEY doesn’t accept both NULL &
DUPLICATE VALUES.
➢ This key used to identify the UNIQUE record
from the table.
➢ We use primary key for relationship with
another tables.
➢ Primary key table is parent table (or) master
table.
➢ Only one primary key for one table.
EX :
create table clg (cno number(10) primary
key ,cname varchar2(10),primarykey(sno,name));
-> Error
(one table only one primary key)
Create table clg(cno number(10) primary
key,cname varchar2(1000));
table created
insert into clg values(10,’raj’);
1 row created
Insert into clg values(20,’ram’);
1 row created (in specify table primary key having
doesn’t accept null& duplicate)

Insert into clg values(20,’raj’);


Insert into clg values(‘ ‘,’raj’); error(null)
❖In this primary key having to specify
the columnname should be doesn’t
accept null&duplicate values.
COMPOSITE PRIMARY KEY :
IN this composite primary key used to give
primary key set of columnnames.
EX :
Create table clg(cno number(10),name
varchar2(1000),primary key(cno,cname));
4.FOREIGN KEY :
➢ We use foreign key to maintain the relation
ship with the tables.
➢ We can call it as ‘referential integrity
constraints’.
➢ FOREIGN KEY always connection of
‘PRIMARY KEY COLUMNS’.
➢ PRIMARY KEY COLUMN & FOREIGN KEY
COLUMN must be same datatype.
➢ FOREIGN KEY COLUMNS will accept
duplicate and null values.
➢ This is called ‘CHILD TABLE’.
EX :
CREATE table clg(cno number(10) references
Clgoldprimarykey(cno),cname varchar2(1000));
Insert into clg values(20,’raj’);
Error because the foreign is relation of
primary key 20 is not in primary key.if any values
in primary key with same datatype will accept
foreign key of values in specify columnname.
Insert into clg values(2,’raj’);
1 row created.
(2 value will be primary key with
same datatype in specify columnname).
NOTE :
❖All constraints can be used for column
level to avoid ambiguity.
❖Only primary key data will be inserted
into foreign key columns in any tables.
5.CHECK :
➢ CHECK constraint is used to stop invalid
entry to the columns in a table.
➢ In this constraint to accept the conditions in
a column.
EX :
CREATE table clg(cno number(10),cname
varchar2(1000),cid number(10) check(cid>5));
insert into clg (1,’raj’,’6’);
1 row created (cid>5,6 is greter than 5 )
Insert into clg(2,’dev’,’5’);
Error (cid>5,but 5 is not greater 5 is equal)
Insert into clg(3,’ram’,’2’);
Error (cid>5 but 5 is not greater than 3)

Create table clg(cno number(10),cname


varchar2(1000)
check(cname=upper(cname));

insert into clg values(1,’RAJ’);


1 row created
Insert into clg values(2,’raj’);
Error because not satisfy the condition of
constraint.it shows lower case letters that’s the
error will be present.
NOTE :
TO SEE THE CONSTRAINTS DETAILS
SELECT constraint_name,constraint_type,
table_name from user_constraints
where table_name like ‘%clg%’;

HOW TO SEE CONSTRAINTS :


➢ We can see the constraints for columns
using ‘data dictionaries’.(real only tables
from database).
➢ For constraints we use USE_CONSTRAINTS
table to verify.

STEP 1 :
Desc USER_CONSTRAINTS;
STEP 2 :
SELECT constraint_name,constraint_type,
table_name from user_constraints
where table_name like ‘%clg%’;
HOW TO CREATE TABLE FROM
ANOTHER TABLE ?
TO CREATE STRUCTURE IN ONE TABLE FROM ANOTHER
TABLE :(ONLY STRUCTURE NO DATA).

CREATE table EMP_NEW as select * from EMP


WHERE 1=2;

(1=2 is only reference purpose you


take 2=3,7=9 anything just for reference).
TO CREATE DATA IN ONE TABLE FROM ANOTHER
TABLE :(ONLY DATA NO STRUCTURE).

CREATE table EMP_NEW as select * from EMP


WHERE 1=1;

(1=1 is only reference purpose you


take 2=2,7=7 anything just for reference).

(OR)

CREATE table EMP_NEW as select * from EMP;


ANALYTICAL FUNCTIONS

➢ We use ANALYTICAL FUNCTIONS to


ASSIGN ‘RANKS’ to each row in a table
either group wise or row wise in a table.
➢ It is similar to ‘group by’ only.
➢ 3 main analytical functions are there.
1.Row_Number()
2.Rank()
3.Dense_Rank()
Analytical functions syntax :
FOR GROUP WISE ROWS :

SELECT column1,column2,column3,…analytical
function name
Over(partition by column name order by column
names[asc/desc] from table name;
FOR ROW WISE ROWS :

SELECT column1,column2,…analytical function


name
Over (order by column name) from table name;
ANALYTICAL FUNCTIONS :

ROW_NUMBER()
It will assign different rank numbers when
values are same.
RANK()
The function will assign same ranks when values
are same but rank() will SKIP NEXT
CONSECUTIVE rank numbers.
DENSE_RANK()
The function will assign same ranks when values
are same but Dense_rank() will DOESN’T SKIP
NEXT CONSECUTIVE rank numbers.
Analytical functions examples:
EXAMPLE :
To take empsal to find the
RANK(),DENSE_RANK()

EMPSAL RANK() DENSE_RANK()


5000 1 1
5000 1 1
4000 3 2
4000 3 2
4000 3 2
4000 3 2
4000 3 2
4000 3 2
4000 3 2
3000 10 3
2000 11 4
**rank() will taken by same sal has same
rank but it consider as next number.
**dense_rank will taken as same rank in
consecutive to next number.
ROW_NUMBER()

SELECT empno,sal,deptno,row_number()
Over(partition by deptno order by sal
Desc)
Sal_rank from emp;

RANK()

SELECT empno,sal,deptno,rank()
Over(partition by deptno order by sal
Desc)
Sal_rank from emp;

DENSE RANK()

SELECT empno,sal,deptno,Dense_rank()
Over(partition by deptno order by sal
Desc)
Sal_rank from emp;
Nth Highest Salary:

Write a query to get Nth highest salary using


Emp table.
Select * from (select
deptno,ename,sal,dense_rank()
over(order by sal desc)r from emp)
where r=&n;

Write a query to get Nth highest salary in


department wise using Emp table.
Select * from (select
deptno,ename,sal,dense_rank()
over (partition by deptno order by sal desc)
r from emp) where r=&n;

You might also like