SQL Language Overview and Examples
SQL Language Overview and Examples
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
[Link]
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 :
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;
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
[Link] :
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 [Link] 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.
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;
[Link]/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;
[Link] :
-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’;
[Link] 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’ ?
NOT LIKE :
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
● FROM
● WHERE
● GROUP BY
● HAVING
● ORDER BY
SELECT :
1. NUMBER FUNCTIONS
2. CHARACTER FUNCTIONS
3. DATE FUNCTIONS
4. GROUP FUNCTIONS
[Link] 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)
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(‘raju@[Link]’,’@’) 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.
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.
[Link] 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
[Link]
[Link] ALL
[Link]
[Link]
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.
[Link] both tables having same columns.
[Link] tables having same data types.
[Link]
• 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
[Link] 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
[Link] :
• 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.
[Link] format joins(‘on’).
[Link]-ANSI format joins(‘where’).
[Link] format joins(‘on’).
In this join can be fetching data by using ‘on’
keyword into to join the conditions.
Types
[Link] JOIN
[Link] JOIN
[Link] OUTER JOIN
[Link] OUTER JOIN
[Link] OUTER JOIN
[Link] JOIN.
[Link] JOIN :
It using the condition ‘equality(=)’
To satisfy this conditions
[Link] both tables having same columns.
[Link] 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
[Link] JOIN :
( MATCHED + UN MATCHED RECORDS)
[Link] 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
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
[Link] JOIN :
In CROSS JOIN is used to generate a paired
combination of each row of the first table with
each row of the second [Link] is also known as
cartesian join.
SYNTAX :
SELECT * FROM
TABLE1 CROSS JOIN TABLE2;
[Link]-ANSI JOIN : (‘WHERE’)
[Link] JOIN
[Link]-EQUI JOIN
[Link] JOIN.
[Link] JOIN :
In this join to retrieve data with ‘equal(=)’
condition.
SYNTAX :
SELECT * FROM
TABLE1,TABLE2 WHERE
TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME
[Link]-EQUI JOIN :
In this join to retrieve data with
(‘ <’ ,’ >’ ,’ <=’ ,’ >=’ ) conditions.
SYNTAX :
SELECT * FROM
TABLE1,TABLE2 WHERE
TABLE1.COLUMN_NAME (<,>,<=,>=)
TABLE2.COLUMN_NAME
[Link] 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
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).
(OR)
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 :
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()
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: