Structured Query Language Notes
Structured Query Language Notes
Data: Data is a collection of small volume of facts and figures. Data DataBase
Examples: Name, Age, Gender, Phone number, email id, e.t.c.,
DataBase: Database is a collection of large volume of facts and figures. Small Large
Examples: University Details, Hospital Details, Bank Details, e.t.c., Volume
Volume
Management of facts & figures: Collection of facts and figures
Store Permanently
Retrieve Efficiently
How Data was managed in Olden days?
Ledger
Management of facts and figures is difficult in Olden Days
C
Java
D B M S
Programming languages were successful in storing the small volume of facts and figures but they fail
to manage the large volume of facts and figures.
Because, for every fact and figure we need to declare a variable, data type & perform initialization.
DataBase Management System (DBMS):
DBMS came into picture when programming languages fail to manage large volume of facts and
figures.
Different Databases available in the market are:
1. Oracle 2. MySQL 3. Sybase 4, DB2
History of Oracle:
1. In 1977, Larry Ellison cofounded Oracle corporation with Bob Miner & Ed Oates under the name
Software Development Laboratory (SDL).
2. In 1979, SDL changed or renamed to Relational Software Corporation (RSI).
3. In 1982, RSI changed or renamed to Oracle System Corporation (OSC).
4. In 1995, OSC changed or renamed to Oracle Corporation.
5. Officially, Oracle Corporation is called as Oracle.
Versions of Oracle:
Oracle 1: 1978
Oracle 2: 1979
Oracle 3: 1983
Oracle 4: 1984
Oracle 5: 1985
Oracle 6: 1988
Oracle 7: 1992
Oracle 8: 1997
Oracle 8i: 1999
Oracle 9i: 2001
Oracle 10g: 2004
Oracle 11g: 2007
Oracle 12c: 2013
Oracle 18c: 2018
Oracle 19c: 2019
RAM
Oracle
Name: Basha Branch: ECE
Table / Relation
Rules to follow while storing the data in database:
1. Creating a table.
2. Specify columns for the table.
3. Insert the values into the table.
Creating and Specifying the columns for a table
Syntax:
create table table_name(Col_name1 datatype, Col_name2 datatype, Col_name3 datatype, e.t.c.,);
Example:
create table student(Name varchar2(16), Age number, Gender char(6), Branch varchar2(16), Id int, Marks
int);
Inserting the values into the table
Syntax:
insert into table_name values(Value1, Value2, Value3, e.t.c.,);
or
if want only some columns to insert the values then we have to use this syntax,
insert into table_name(Col_name1, Col_name2) values(Value1, Value2)
Example:
insert into student values(‘Shaik Mahaboob Basha’, 23, ‘Male’, ‘E.C.E’, 458, 93);
Note: In SQL, for creation a table and inserting the values into the table we have to use semicolon (;). By
inserting semicolon means it separates the line of insertion.
By using the above examples after creation of table, it looks like as,
Name Age Gender Branch Id Marks
Shaik Mahaboob Basha 23 Male E.C.E 458 93
In Hard Disk table is created as,
Number
Size of 21 bytes.
It will accept integers, real numbers
Syntax:
Col_name varchar2(Size)
Example:
Salary number
Number(P,S)
o Precision (P): Indicates the total number of digits before the decimal point.
o Scale (S): Indicates the total number of digits after the decimal point.
Example:
Percentage Number(4,2)
8 ()
73.69 ()
61.3267 ()
61.3 ()
564 ()
100 ()
Alphanumeric
I. char(size)
It will accept alphabets, numbers and special symbols.
It is static in nature.
It can take upto 2000 characters.
Synatx:
Col_name char(Size)
Example:
Name char(10)
Sachin
S a c h I n
|-----------Memory is Wasted----------|
II. varchar2(size)
It will accept alphabets, numbers, and special symbols.
It is dynamic in nature.
It can take upto 4000 characters.
Syntax:
Col_name varchar2(Size)
Example:
Name varchar2(10)
Sachin
S a c h I n
|---------Memory is not Wasted-------|
Date
Syntax:
Oracle Format: DD-MM-YYYY
Example: 29-May-2000
MySQL Format: YYYY-MM-DD
Example: 2000-05-29
RETRIEVING THE DATA
1. Selection: Fetching data from the table by eliminating certain rows from it.
2. Projection: Fetching data from the table without eliminating any rows from the table.
Write a query to display name from the student table.
select name from student;
NAME
Cat
Rat
Tiger
Lion
Write a query to display name, age, gender from the student table.
select name, age, gender from student;
NAME AGE GENDER
Cat 23 Male
Rat 24 Female
Tiger 26 Female
Lion 18 male
Write a query to display details of students who scored greater than 60 marks.
select * from student where marks>60;
NAM E AGE GENDER M ARKS
Cat 23 Male 93
Rat 24 Female 88
Tiger 26 Female 98
CASE SENSITIVITY
I. Commands and Keywords are not case sensitive.
II. Table name and Column name are not case sensitive.
III. Data types are not case sensitive.
IV. Data in the table are case sensitive.
V. Constraints are not case sensitive.
CONSTRAINTS
Constraints are the rules or restrictions which are implemented on particular column of the table.
Constraints will standardize the table and helps in achieving business rules, clients requirements.
Types of Constraints:
1. Unique
2. Not null
3. Primary key
4. Foreign key
5. Default
6. Check
Unique:
Unique constraint ensures that the particular column on which it is implemented cannot have duplicate values
but can have null values.
Syntax:
create table student (id int Unique, name varchar2(54), age int, institute varchar2(64));
Unique
01 Basha 23 KodNest
02 Tom 64 KodNest
03 Jerry 16 KodNest
- Motu 48 -
- Patlu - KodNest
Note:
In SQL, Null ≠ Null; Null ≠ 0; Null + 5 = Null
Not Null
01 Dhoni 56 KodNest
02 Raina 45 KodNest
03 Kohli 65 KodNest
- Sunny - -
- Vikas - KodNest
Primary Key:
Primary key is a combination of Unique and Not null constraint.
Primary Key constraint ensures that the particular column on which is implemented cannot have
duplicate values and cannot have null values.
There can be only and one primary key for one table.
Primary Key is the one which will help to identify each row uniqly in a table.
A table with primary key is called Parent Key.
Syntax:
create table student (id int, name varchar2(54) primary key, age int, institute varchar2(65));
Primary Key
Foreign Key:
Foreign Key will always refer primary key column of another table for its identity.
The concept of RDBMS is achieved by Foreign Key.
RDBMS stands for Relational Database Management System / Software.
Foreign Key column will always accept both duplicate and null values.
Foreign Key constraint is also called as “Referential Integrity Constraint”.
A table with Foreign Key is called Child table.
Syntax:
create table Department (did int Primary key, dname varchar2(54));
create table Employee(id int Primary Key, name varchar2(87), salary number, did int, Foreign
key(did) references department(did));
Employee:
Primary Key Foreign Key
Primary Key
Department:
dname did
Run 101
Eat 102
Sat 103
Check:
Check constraint ensures that the values that are getting inserted into the particular column in which it is
implemented satisfies the given check condition.
Syntax:
create table student(is int, name varchar2(54), age int check(age>18), institute varchar2(54));
check(age>18)
01 Pen 25 KodNest
02 Paper 26 KodNest
03 Eraser 45 KodNest
04 Sharpener 16 KodNest
05 Book 13 KodNest
06 Bag 18 KodNest
Default:
Default Constraint ensures that when there is no value specified into the column on which it is implemented
it well take the default value mentioned.
Syntax:
create table student ( id int, name varchar2(54), age int; institute varchar2(54) default ‘KodNest’);
default ‘KodNest’
Write a query to create citizen table with the following columns present in it
1. Id which should accept integers
2. Name, which should accept varchar2
3. Gender, which should accept varchar2
4. Address, which should accept varchar2
5. Phone_number, which should accept number
6. Age, which should accept integers
Note: Id should be unique and it should not be null (Primary Key).
Name should not be null.
If no value is entered to gender then by default it should be male.
Before accepting the value to age, DBMS should check whether the value is greater than 18 or not.
Create table citizen (
Id int primary key,
Name varchar2(65),
Gender varchar2(65),
Address varchar2(54) default 'India',
Phone_number number Not null,
age int check(age>18));
Dept Table:
DEPT_ID DEPT_NAME M ANAGER_ID LOC_ID
20 Admin 300 2100
21 Marketing 301 2200
22 Shipping 302 2300
23 IT 303 2400
24 Sales 304 2500
25 Executive 305 2600
110 Acc 306 2700
190 Contracting - 2800
26 Admin 307 2900
J_grade table:
Write a query to display employee id, job id, department id and salary by giving hike of 10 percent.
select emp_id,job_id,dept_id,salary+(salary*(10/100))
from emp;
EMP_ID JOB_ID DEPT_ID SALARY+(SALARY*(1 0/100))
1 AD_PRES 21 37400
2 AD_VP 22 49500
3 AD_VP 24 60500
4 IT_PROG 110 39600
5 IT_PROG 25 19800
7 ST_MAN 22 93500
8 ST_CLERK 22 31350
9 ST_CLERK 23 13200
10 ST_CLERK 110 58300
11 ST_CLERK 24 58300
12 SA_MAN 23 27500
13 SA_REP 22 50050
14 SA_REP 23 50600
15 SA_REP 24 13200
16 AD_ASST 23 21450
17 MD_MAN 22 43450
18 MD_REP 22 32450
19 AC_MGR 110 32450
20 AC_ACCOUNT 110 10450
Write a query to display employee id, job id, department id and salary by reducing the salary of 20
percent.
select emp_id,job_id,dept_id,salary-(salary*(20/100))
from emp;
EMP_ID JOB_ID DEPT_ID SALARY-(SALARY*(2 0/100))
1 AD_PRES 21 27200
2 AD_VP 22 36000
3 AD_VP 24 44000
4 IT_PROG 110 28800
5 IT_PROG 25 14400
7 ST_MAN 22 68000
8 ST_CLERK 22 22800
9 ST_CLERK 23 9600
10 ST_CLERK 110 42400
11 ST_CLERK 24 42400
12 SA_MAN 23 20000
13 SA_REP 22 36400
14 SA_REP 23 36800
15 SA_REP 24 9600
16 AD_ASST 23 15600
17 MD_MAN 22 31600
18 MD_REP 22 23600
19 AC_MGR 110 23600
20 AC_ACCOUNT 110 7600
Write a query to display the details of employees whose department id is greater than 30.
select * from emp where dept_id>30;
EMP F_N L_N PHONE_N HIRE_ JOB_I SAL COMM ISSI M ANAG DEP
_ID AM E AM E EM AIL UM BER DATE D ARY ON_PCT ER_ID T_ID
Ashwi ash@gmai 27-FEB- IT_PRO
4 K 66554433 36000 .75 - 110
n l.com 11 G
adam@gm 16-APR- ST_CLE
10 Adam Sam 325674 53000 1.2 196 110
ail.com 07 RK
Sardh Sar@gmail 29-APR- AC_MG
19 L 322378445 29500 1.2 - 110
ar .com 10 R
Jinnat jinn@gmail 30-APR- AC_ACC
20 Whala 322378445 9500 1.2 - 110
h .com 10 OUNT
Write a query to display details of employees whose salary is less than 10000 from emp table
select * from emp where salary < 10000;
EMP F_N L_N PHONE_N HIRE_ JOB_I SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE D ARY ON_PCT ER_ID _ID
Jinnat jinn@gm 30-APR- AC_ACC
20 Whala 322378445 9500 1.2 - 110
h ail.com 10 OUNT
Write a query to display email id, phone number whose commission percentage is greater than or equal
to 5 from emp table.
select email, phone_number from emp where commission_pct >= 5;
no data found
Write a query to display emp id, f_name, l_name from emp table whose salary is less than or equal to
34000.
select email,f_name, l_name from emp where salary <= 34000;
EM AIL F_NAM E L_NAM E
[email protected] Akash Pandey
[email protected] John Williams
[email protected] Andy J
[email protected] Daniel King
[email protected] Madavan Manish
[email protected] Savitha Singh
[email protected] Mrudul Kumar
[email protected] Janardhan Tohn
[email protected] Sardhar L
[email protected] Jinnath Whala
Write a query to display the details of employees who is not clerk (ST_CLERK ) from emp table.
select * from emp where job_id != 'ST_CLERK';
EMP F_NA L_N PHONE_N HIRE_ JOB_I SAL COMM ISSI M ANAG DEP
_ID ME AM E EM AIL UM BER DATE D ARY ON_PCT ER_ID T_ID
Pande akash@g 29-MAR- AD_PRE
1 Akash 9997766 34000 - - 21
y mail.com 12 S
Prabha Ganes pk@gmail. 25-MAY-
2 77665522 AD_VP 45000 - 100 22
karan han com 12
deep@gm 19-APR-
3 DEEP Nair 876297 AD_VP 55000 .5 101 24
ail.com 12
ash@gmail 27-FEB- IT_PRO
4 Ashwin K 66554433 36000 .75 - 110
.com 11 G
Willia sfda@gma 15-DEC- IT_PRO
5 John 7456465 18000 1.5 110 25
ms il.com 10 G
Sac@gmai 25-AUG-
7 Shashi Raj 9575673 ST_MAN 85000 1.2 - 22
l.com 10
Madav Manis mad@gma 30-DEC-
12 4353213 SA_MAN 25000 .3 198 23
an h il.com 08
Bhupa Brav@gma 27-SEP-
13 Braven 12342231 SA_REP 45500 .2 114 22
thi il.com 08
Mamat Mam@gm 25-JUL-
14 T 53434334 SA_REP 46000 .2 - 23
ha ail.com 10
savi@gmai 23-FEB-
15 Savitha Singh 3443333 SA_REP 12000 .15 - 24
l.com 10
mru@gmai 30-APR- AD_ASS
16 Mrudul Kumar 322378445 19500 1.2 - 23
l.com 10 T
pap@gmai 23-APR- MD_MA
17 Pankaj patel 322378445 39500 1.2 - 22
l.com 10 N
Janard Tohn@gm 28-MAY-
18 Tohn 322378445 MD_REP 29500 1.2 - 22
han ail.com 11
Sardha Sar@gmail 29-APR- AC_MG
19 L 322378445 29500 1.2 - 110
r .com 10 R
jinn@gmail 30-APR- AC_ACC
20 Jinnath Whala 322378445 9500 1.2 - 110
.com 10 OUNT
Write a query to concatenate Sachin and Tendulkar and display it as full name.
select 'Sachin '||' Tendulkar' as "full name" from dual;
Full Name
Sachin Tendulkar
DUAL TABLE
The DUAL table is a special one-row, one-column table present by default in Oracle and other database
installations.
In Oracle, the table has a single VARCHAR2(1) column called DUMMY that has a value of X;
Note1: if the query “desc dual” is executed then following will be the output
Table Column Data Type Length Precision Scale Primary Nullable Default Comment
Key
DUAL DUMMY VarChar2 1 - - - - -
1-1
Note2: if the query “select * from dual” is executed then following will be the output
Dummy
X
Note3: Selecting from the DUAL table is useful for computing a constant expression with the SELECT
statement. Because DUAL has only one row, the constant is returned only once. Alternatively, you can
select a constant, pseudo column, or expression from any table, but the value will be returned as many
times as there are rows in the table.
Write a query to concatenate 111 and 222 and display it as full number.
select 111||222 as "full number" from dual;
Full Number
111222
Write a query to concatenate Bond and 7777 and display it as movie character.
select 'Bond'||7777 as "movie character" from dual;
Movie Character
Bond7777
Write a query to concatenate bond with null and display the result.
select 'bond'||null as "result" from dual;
Result
bond
Write a query in order to display the following output by accessing the data from emp table.
Salary Details
Akash works in department 21
Prabhakaran works in department 22
Andy works in department 22
...
Keywords As Operators:
Write a query to display unique department id from employee table.
select distinct dept_id from emp;
DEPT_ID
22
25
21
24
110
23
Write a query to display the grade and low salary whose low salary is in the range of 2000 to 4000.
select grade, low_sal from j_grade where low_sal between 2000 and 4000;
GRADE LOW_SAL
A 2000
Write a query to display the details of employees whose commission percentage is the range 1.2 to 1.5.
select * from emp where commission_pct between 1.2 and 1.5;
EMP F_N L_N PHONE_N HIRE_ JOB_I SAL COMM ISSI M ANAG DEP
_ID AM E AM E EM AIL UM BER DATE D ARY ON_PCT ER_ID T_ID
Willia sfda@gma 15-DEC- IT_PRO
5 John 7456465 18000 1.5 110 25
ms il.com 10 G
Shash Sac@gmai 25-AUG-
7 Raj 9575673 ST_MAN 85000 1.2 - 22
i l.com 10
sas@gmail 24-JUN- ST_CLE
9 Daniel King 5423424 12000 1.2 117 23
.com 10 RK
adam@gm 16-APR- ST_CLE
10 Adam Sam 325674 53000 1.2 196 110
ail.com 07 RK
Megh Meg@gma 25-OCT- ST_CLE
11 Devraj 3453424 53000 1.2 165 24
ana il.com 08 RK
Mrudu mru@gmai 30-APR- AD_ASS
16 Kumar 322378445 19500 1.2 - 23
l l.com 10 T
Panka pap@gmai 23-APR- MD_MA
17 patel 322378445 39500 1.2 - 22
j l.com 10 N
Janar Tohn@gm 28-MAY-
18 Tohn 322378445 MD_REP 29500 1.2 - 22
dhan ail.com 11
Sardh Sar@gmail 29-APR- AC_MG
19 L 322378445 29500 1.2 - 110
ar .com 10 R
Jinnat jinn@gmail 30-APR- AC_ACC
20 Whala 322378445 9500 1.2 - 110
h .com 10 OUNT
Write a query to display department id and department name where location id is not in the range from
2400 to 2500.
select dept_id, dept_name from dept where loc_id not between 2400 and 2500;
DEPT_ID DEPT_NAME
20 Admin
21 Marketing
22 Shipping
25 Executive
110 Acc
190 Contracting
26 Admin
Write a query to display the details from job grades where high salary is not in the range of 3000 to
55000.
select * from j_grade where high_sal not between 3000 and 55000;
GRADE LOW_SAL HIGH_SAL
A 2000 60000
H 35001 89000
I 45001 99000
J 55001 199000
Write a query to display details of employees whose salary is 12000, 18000, 19000.
select * from emp where salary in(12000, 18000, 19000);
EMP F_N L_N PHONE_N HIRE_ JOB_ SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE ID ARY ON_PCT ER_ID _ID
Willia sfda@gm 15-DEC- IT_PR
5 John 7456465 18000 1.5 110 25
ms ail.com 10 OG
sas@gmai 24-JUN- ST_CL
9 Daniel King 5423424 12000 1.2 117 23
l.com 10 ERK
Savith savi@gma 23-FEB- SA_RE
15 Singh 3443333 12000 .15 - 24
a il.com 10 P
Write a query to display department id, department name whose location id is 2500,2700,2900.
select dept_id, dept_name from dept where loc_id in(2500, 2700, 2900);
DEPT_ID DEPT_NAME
24 Sales
110 Acc
26 Admin
Write a query to display low salary and high salary whose grade is not A ,B, D
select low_sal,high_sal from j_grade where grade not in('A','B','C');
LOW_SAL HIGH_SAL
1001 25000
25001 35000
35001 89000
45001 99000
55001 199000
Write a query to display the details of employees who do not take any commission.
select * from emp where commission_pct is null;
EMP F_NA L_N PHONE_N HIRE_ JOB SAL COMM ISSI M ANAG DEPT
_ID ME AM E EM AIL UM BER DATE _ID ARY ON_PCT ER_ID _ID
Pande akash@gm 29-MAR- AD_P
1 Akash 9997766 34000 - - 21
y ail.com 12 RES
Prabha Ganes pk@gmail. 25-MAY- AD_V
2 77665522 45000 - 100 22
karan han com 12 P
Write a query to display the details of employees whose first name starts with ‘A’
select * from emp where f_name like 'A%';
EMP F_N L_N PHONE_N HIRE_ JOB_ SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE ID ARY ON_PCT ER_ID _ID
Pande akash@gm 29-MAR- AD_P
1 Akash 9997766 34000 - - 21
y ail.com 12 RES
Ashwi ash@gmail 27-FEB- IT_PR
4 K 66554433 36000 .75 - 110
n .com 11 OG
And@gmail 28-AUG- ST_CL
8 Andy J 8579452 28500 .9 - 22
.com 12 ERK
adam@gm 16-APR- ST_CL
10 Adam Sam 325674 53000 1.2 196 110
ail.com 07 ERK
Write a query to display department id, department name where department name starts with ‘AC’
select dept_id, dept_name from dept where dept_name like 'AC%';
no data found
Write a query to display grades from the job grades table where low salary ends with 1.
select grade from j_grade where low_sal like '%1';
GRADE
B
D
F
H
I
J
Write a query to display details of department whose department name ends with the ‘ng’.
select * from dept where dept_name like '%ng';
DEPT_ID DEPT_NAME M ANAGER_ID LOC_ID
21 Marketing 301 2200
22 Shipping 302 2300
190 Contracting - 2800
Write a query to display department id, department name whose manager id ends with 0.
select dept_id, dept_name from dept where manager_id like '%0';
DEPT_ID DEPT_NAME
20 Admin
Write a query to display details of employee whose first name contains ‘an’.
select * from emp where f_name like '%an%';
EMP F_NA L_N PHONE_N HIRE_ JOB_ SAL COMM ISSI M ANAG DEPT
_ID ME AM E EM AIL UM BER DATE ID ARY ON_PCT ER_ID _ID
Prabha Ganes pk@gmail. 25-MAY- AD_V
2 77665522 45000 - 100 22
karan han com 12 P
sas@gmai 24-JUN- ST_CL
9 Daniel King 5423424 12000 1.2 117 23
l.com 10 ERK
Megha Meg@gma 25-OCT- ST_CL
11 Devraj 3453424 53000 1.2 165 24
na il.com 08 ERK
Madava Manis mad@gma 30-DEC- SA_M
12 4353213 25000 .3 198 23
n h il.com 08 AN
pap@gmai 23-APR- MD_M
17 Pankaj patel 322378445 39500 1.2 - 22
l.com 10 AN
Janard Tohn@gm 28-MAY- MD_R
18 Tohn 322378445 29500 1.2 - 22
han ail.com 11 EP
Write a query to display last name of an employee whose name contains ‘am’.
select * from emp where l_name like '%am%';
EMP F_N L_N PHONE_N HIRE_ JOB_ SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE ID ARY ON_PCT ER_ID _ID
Willia sfda@gmai 15-DEC- IT_PR
5 John 7456465 18000 1.5 110 25
ms l.com 10 OG
adam@gm 16-APR- ST_CL
10 Adam Sam 325674 53000 1.2 196 110
ail.com 07 ERK
Write a query to display details of employees whose f_name second character is ‘r’.
select * from emp where f_name like '_r%';
EMP F_NA L_N PHONE_N HIRE_ JOB SAL COMM ISSI M ANAG DEPT
_ID ME AM E EM AIL UM BER DATE _ID ARY ON_PCT ER_ID _ID
Prabha Ganes pk@gmail. 25-MAY- AD_V
2 77665522 45000 - 100 22
karan han com 12 P
Bhupa Brav@gm 27-SEP- SA_R
13 Braven 12342231 45500 .2 114 22
thi ail.com 08 EP
mru@gma 30-APR- AD_A
16 Mrudul Kumar 322378445 19500 1.2 - 23
il.com 10 SST
Write a query to display details of employees whose mail id third character is ‘@’.
select * from emp where email like '__@%';
EMP F_NA L_NA PHONE_N HIRE_ JOB SAL COMM ISSIO M ANAG DEPT
_ID ME ME EM AIL UM BER DATE _ID ARY N_PCT ER_ID _ID
Prabha Ganes pk@gmai 25-MAY- AD_V
2 77665522 45000 - 100 22
karan han l.com 12 P
Write a query to display the details of employees whose last name fourth character from the last is ‘n’.
select * from emp where l_name like '%n___';
EMP F_N L_N PHONE_N HIRE_ JOB SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE _ID ARY ON_PCT ER_ID _ID
Pande akash@gm 29-MAR- AD_P
1 Akash 9997766 34000 - - 21
y ail.com 12 RES
Madav Manis mad@gmai 30-DEC- SA_M
12 4353213 25000 .3 198 23
an h l.com 08 AN
Write a query to display the phone number from the employee table whose phone number third digit
from last is 3.
select phone_number from emp where phone_number like '%3__';
PHONE_NUM BER
53434334
3443333
Write a query to display the last name and salary from emp table whose last name has exactly 5
characters.
select l_name, salary from emp where l_name like '_____';
L_NAM E SALARY
Singh 12000
Kumar 19500
patel 39500
Whala 9500
WAQ to display the name from college_student table whose has _(Underscore) in there name.
Note: Before writing the query create college_student table with id and name as columns and insert
The values into the table as shown below:
id Name
Kod001 Sahana_varma
Kod002 Sindhu_sharma
Kod003 Swathi%hegde
Kod004 Shruthi
select name from college_student where name like '%?_%' escape '?';
NAM E
Sahana_varma
Sindhu_sharma
Write a query to display the name from college_student table who has %(Modulus) in there name.
Note: Take the reference of previous queries table
select name from college_student where name like '%?%%' escape '?';
NAM E
Swathi%hegde
Write a query to display details of employees whose salary is 12000 and job id is ‘ST_CLERK’.
select * from emp where salary = 12000 and job_id = 'ST_CLERK';
EMP F_NA L_NA PHONE_N HIRE_ JOB_ SAL COMM ISSI M ANAG DEPT
_ID ME ME EM AIL UM BER DATE ID ARY ON_PCT ER_ID _ID
sas@gma 24-JUN- ST_CL
9 Daniel King 5423424 12000 1.2 117 23
il.com 10 ERK
Write a query to display details of employees whose department id is 22 and manager id is 100.
select * from emp where dept_id=22 and manager_id=100;
EMP F_NA L_NA PHONE_N HIRE_ JOB SAL COMM ISSIO M ANAG DEPT
_ID ME ME EM AIL UM BER DATE _ID ARY N_PCT ER_ID _ID
Prabha Ganes pk@gmai 25-MAY- AD_V
2 77665522 45000 - 100 22
karan han l.com 12 P
Write a query to display the grade from the Job grade table where grade is ‘A’ or high salary is greater
than 80000.
select grade from j_grade where grade='A' or high_sal>80000;
GRADE
A
H
I
J
Write a query to display the details of employees whose job id is clerk(ST_CLERK) or the salary is
lesser than 19000.
select * from emp where job_id = 'ST_CLERK' or salary < 19000;
EMP F_N L_N PHONE_N HIRE_ JOB_I SAL COMM ISSI M ANAG DEP
_ID AM E AM E EM AIL UM BER DATE D ARY ON_PCT ER_ID T_ID
Willia sfda@gma 15-DEC- IT_PRO
5 John 7456465 18000 1.5 110 25
ms il.com 10 G
And@gmai 28-AUG- ST_CLE
8 Andy J 8579452 28500 .9 - 22
l.com 12 RK
sas@gmail 24-JUN- ST_CLE
9 Daniel King 5423424 12000 1.2 117 23
.com 10 RK
adam@gm 16-APR- ST_CLE
10 Adam Sam 325674 53000 1.2 196 110
ail.com 07 RK
Megh Meg@gma 25-OCT- ST_CLE
11 Devraj 3453424 53000 1.2 165 24
ana il.com 08 RK
Savith savi@gmai 23-FEB-
15 Singh 3443333 SA_REP 12000 .15 - 24
a l.com 10
Jinnat jinn@gmail 30-APR- AC_ACC
20 Whala 322378445 9500 1.2 - 110
h .com 10 OUNT
Write a Query to Display the Details of all the employees who are president or sales representatives but
they must earn more than 25000.
select * from emp where ((job_id = 'AD_PRES' or job_id = 'SA_REP') and salary > 25000);
EMP F_N L_N PHONE_N HIRE_ JOB SAL COMM ISSI M ANAG DEPT
_ID AM E AM E EM AIL UM BER DATE _ID ARY ON_PCT ER_ID _ID
Pande akash@gm 29-MAR- AD_P
1 Akash 9997766 34000 - - 21
y ail.com 12 RES
Brave Bhupa Brav@gma 27-SEP- SA_R
13 12342231 45500 .2 114 22
n thi il.com 08 EP
Mamat Mam@gma 25-JUL- SA_R
14 T 53434334 46000 .2 - 23
ha il.com 10 EP
Operator Precedence
AND 1
OR 2
Write a query to display all the f_name of employees in the order of attendance
select f_name from emp order by f_name asc;
F_NAM E
Adam
Akash
Andy
Ashwin
Braven
DEEP
Daniel
Janardhan
Jinnath
John
Madavan
Mamatha
Meghana
Mrudul
Pankaj
Prabhakaran
Sardhar
Savitha
Shashi
FUNCTIONS
In sql we have two types functions
1)single row functions
2)multiple row functions
Single row functions are such functions which will accept a single row as input (or) it accepts multiple
rows as input but produces one result per row
Multiple row functions/group functions/aggregate functions are such functions which will accept a
single row or multiple rows as input but produces one result per group
Types of single row functions:
General
Functions
Number Date
Functions Functions
Single
Row
Functions
Character Conversion
Functions Functions
Write a query to display all the FirstNames and lastnames of the employees in uppercase where
lastname is 'Pandey'.
select upper(f_name), upper(l_name) from emp where l_name = 'Pandey';
UPPER(F_NAM E) UPPER(L_NAM E)
AKASH PANDEY
Write a query to display F_name , l_names and salaries whose F_name is 'Akash' in any case.
select upper(f_name), upper(l_name), salary from emp where f_name = 'Akash';
UPPER(F_NAM E) UPPER(L_NAM E) SALARY
AKASH PANDEY 34000
Write a query to concatenate data of f_name and l_name of all the employees from EMP table.
select concat(f_name,l_name) from emp;
CONCAT(F_NAM E,L_NAM E)
AkashPandey
PrabhakaranGaneshan
DEEPNair
AshwinK
JohnWilliams
ShashiRaj
AndyJ
DanielKing
AdamSam
MeghanaDevraj
MadavanManish
BravenBhupathi
MamathaT
SavithaSingh
MrudulKumar
Pankajpatel
JanardhanTohn
SardharL
JinnathWhala
Write a query to display the substring of the string 'PRABHAKARAN' from 2nd position extract 5
characters.
select substr('PRABHAKARAN',2,5) from dual;
SUBSTR('PRABHAKARAN',2,5)
RABHA
Write a query to display the substring 'oha' from the string 'RajaRamMohanRoy'.
select substr('RajaRamMohanRoy', 9,3) from dual;
SUBSTR('RAJARAMM OHANROY',9,3)
oha
Write a query to display the position of the character 'a' in the string 'Pandey'.
select instr('Pandey', 'a') from dual;
INSTR('PANDEY','A')
2
Write a query to display the position of the character 'a' in all the firstnames.
select instr(f_name, 'a') from emp;
INSTR(F_NAM E,'A')
3
3
0
0
0
3
0
2
3
5
2
3
2
2
0
2
2
2
5
Write a query to display the substring 'bha' from the f_name where f_name is ‘Prabhakaran'(use both
substring and instring)
select substr('Prabhakaran',instr('Prabhakaran','bha'),3) from dual;
SUBSTR('PRABHAKARAN',INSTR('PRABHAKARAN','BHA'),3)
bha
Write a query to trim the trailing 'm' in the string ' Malayalam
select trim(trailing 'm' from 'malayalam') from dual;
TRIM (TRAILING'M'FROM 'M ALAYALAM')
malayala
Write a query to trim the both 'm' in the string ' malayalam '
select trim(both 'm' from 'malayalam') from dual;
TRIM (BOTH'M'FROM 'M ALAYALAM')
alayala
Write a query to display the commission_pct. If commission_pct is null replace with 0 else replace with
5.
select nvl2(commission_pct,5,0) from emp;
NVL2(COMMISSION_PCT,5,0)
0
0
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
Write a query to display the f_name , l_name , length of f_name, length of l_name for all employees . if
length of f_name is equal to length of l_name display null if length of f_name is not equal to length of
l_name display length of f_name
select f_name, l_name, length(f_name), length(l_name),case
when length(f_name)=length(l_name) then null
else length(f_name)
end
from emp;
F_NA L_NA LENGTH(F_ LENGTH(L_ CASEWHENLENGTH(F_NAME)=LENGTH(L_NAM E)THENNUL
ME ME NAM E) NAM E) LELSELENGTH(F_NAM E)END
Pande
Akash 5 6 5
y
Prabhak Ganes
11 8 11
aran han
DEEP Nair 4 4 -
Ashwin K 6 1 6
William
John 4 8 4
s
Shashi Raj 6 3 6
Andy J 4 1 4
Daniel King 6 4 6
Adam Sam 4 3 4
Meghan
Devraj 7 6 7
a
Madava
Manish 7 6 7
n
Bhupat
Braven 6 8 6
hi
Mamath
T 7 1 7
a
Savitha Singh 7 5 7
Mrudul Kumar 6 5 6
Pankaj patel 6 5 6
Janardh
Tohn 9 4 9
an
Sardhar L 7 1 7
Jinnath Whala 7 5 7
Write a query to display the number of months between the dates 14-nov-2014 and 14-feb2014
select months_between('14-nov-2014','14-feb-2014') from dual;
M ONTHS_BETWEEN('14-NOV-2014','14-FEB-2014')
9
Write a query in order to add 9 months for the date 14-feb-2014 in reverse order.
select add_months('14-feb-2014',-9) from dual;
ADD_M ONTHS('14-FEB-2014', -9)
14-MAY-13
Write a query to find the date of the next Saturday after the date 08-dec-2012
select next_day('08-dec-2012', 'Saturday') from dual;
NEXT_DAY('08-DEC-2012','SATURDAY')
15-DEC-12
Write a query to display the last day of the below specified date:
2022-06-18
select last_day('18-Jun-2022') from dual;
LAST_DAY('18-JUN-202 2')
30-JUN-22
write a query to display the l_name, hire_date where the hire_date should be displayed in the format
dd/mm.
select l_name,to_char(hire_date, 'dd/mm') from emp;
L_NAM E TO_CHAR(HIRE_DATE,'DD/MM ')
Pandey 29/03
Ganeshan 25/05
Nair 19/04
K 27/02
Williams 15/12
Raj 25/08
J 28/08
King 24/06
Sam 16/04
Devraj 25/10
Manish 30/12
Bhupathi 27/09
T 25/07
Singh 23/02
Kumar 30/04
patel 23/04
Tohn 28/05
L 29/04
Whala 30/04
Write a query to display the l_name and salary . the salary should be displayed in the format $99,999.99.
select l_name,to_char(salary, '$99,999.99') from emp;
L_NAM E TO_CHAR(SALARY,'$99,999.9 9')
Pandey $34,000.00
Ganeshan $45,000.00
Nair $55,000.00
K $36,000.00
Williams $18,000.00
Raj $85,000.00
J $28,500.00
King $12,000.00
Sam $53,000.00
Devraj $53,000.00
Manish $25,000.00
Bhupathi $45,500.00
T $46,000.00
Singh $12,000.00
Kumar $19,500.00
patel $39,500.00
Tohn $29,500.00
L $29,500.00
Whala $9,500.00
Multirow Functions:
Count()
Avg() Sum()
Multi
Row
Functions
Max() Min()
write a query to display count of all the rows present in emp table.
select count(*) from emp;
COUNT(*)
19
write a query to display the minimum of all the salaries from emp table.
select min(salary) from emp;
MIN(SALARY)
9500
write a query to display the minimum of all the salaries excluding duplicates.
select min(distinct salary) from emp;
MIN(DISTINCTSALARY)
9500
write a query to display the maximum of all the salaries from emp table.
select max(salary) from emp;
M AX(SALARY)
85000
write a query to display the maximum of all the salaries excluding duplicates.
select max(distinct salary) from emp;
M AX(DISTINCTSALARY)
85000
write a query to display the sum of all the salaries from emp table.
select sum(salary) from emp;
SUM (SALARY)
675500
write a query to display the sum of all the salaries excluding duplicates.
select sum(distinct salary) from emp;
SUM (DISTINCTSALARY)
581000
write a query to display the average of all the salaries from emp table.
select avg(salary) from emp;
AVG(SALARY)
35552.6315789473684210526315789473684211
write a query to display the average of all the salaries excluding duplicates.
select avg(distinct salary) from emp;
AVG(DISTINCTSALARY)
36312.5
write a query to display the hiredate of oldest employee in the emp table.
select min(hire_date) from emp;
MIN(HIRE_DATE)
16-APR-07
Write a query to display the department_id and the sum of the salary for all the employees in
each department
select dept_id,sum(salary) from emp group by dept_id;
DEPT_ID SUM (SALARY)
22 273000
25 18000
21 34000
24 120000
110 128000
23 102500
Display the dept_id and highest salary of each department for all departments whose department_id is
>50.
select dept_id,max(salary)
from emp
where dept_id>50
group by dept_id;
DEPT_ID M AX(SALARY)
110 53000
Write a query to display the dept_id, and count of the dept_id for all the employees whose department
Id is equal to 90.
select dept_id,count(dept_id)
from emp
where dept_id=90
group by dept_id;
no data found
write a query to display the dept_id and the maximum salary of all the employees whose maximum
salary is greater than 30000.
select dept_id,max(salary)
from emp
group by dept_id
Having max(salary) > 30000;
DEPT_ID M AX(SALARY)
22 85000
21 34000
24 55000
110 53000
23 46000
Write a query to display department id, minimum salary whose job id is ST_CLERK or IT_PROG
having the sum of salary less than 25000 group the result based on each Department and display the
result in the descending order .
select dept_id,min(salary)
from emp
where job_id='ST_CLERK' or job_id='IT_PROG'
group by dept_id
Having sum(salary) < 25000
order by dept_id desc;
DEPT_ID MIN(SALARY)
25 18000
23 12000
SUB QUERIES OR INNER QUERY OR NESTED QUERY IN SQL
A Subquery is a query within another SQL query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Properties of subqueries
1.Subqueries must be enclosed within parentheses.
2.A subquery can have only one column in the SELECT clause, unless multiple columns are in the main
query for the subquery to compare its selected columns.
3.An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The
GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
4.Subqueries that return more than one row can only be used with multiple value operators, such as the
IN operator.
Write a query to display the l_name, f_name and salary of all employees who earn more than Pandey.
select l_name, f_name, salary
from emp
where salary > (select salary from emp where l_name = 'Pandey');
L_NAM E F_NAM E SALARY
Ganeshan Prabhakaran 45000
Nair DEEP 55000
K Ashwin 36000
Raj Shashi 85000
Sam Adam 53000
Devraj Meghana 53000
Bhupathi Braven 45500
T Mamatha 46000
patel Pankaj 39500
Write a query to display the dept_id and the f_name for all employees who work in the same department
in which ‘Prabhakaran’ works.
select dept_id, f_name
from emp
where dept_id = (select dept_id from emp where f_name = 'Prabhakaran');
DEPT_ID F_NAM E
22 Prabhakaran
22 Shashi
22 Andy
22 Braven
22 Pankaj
22 Janardhan
Write a query to display the dept_id, f_name and the job_id for all employees who work in
administration department.
select dept_id, f_name, job_id
from emp
where dept_id in(select dept_id from dept where dept_name = 'Admin');
no data found
Write a query to display the emp_id of all the employees whose dept_id in employees table is equal to
dept_id in dept table.
select emp_id
from emp
where dept_id in(select dept_id from dept);
EMP_ID
1
2
3
4
5
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Write a query to display the l_name and job_id whose job_id is similar to ‘King’ and whose salary is
greater than sings salary.
select l_name, job_id
from emp
where (job_id = (select job_id from emp where l_name = 'King') and (salary > (select salary from emp where
l_name = 'singh')));
no data found
JOINS
Join (SQL) A SQL join clause combines records from two or more tables in a relational database. It
creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from
two tables (or more) by using values common to each.
• INNER JOIN: Returns all rows when there is at least one match in BOTH tables
• LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
• RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
• FULL JOIN: Return all rows when there is a match in ONE of the tables
• NATURAL JOIN: A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you
based on the common columns in the two tables being joined. Common columns are columns that have
the same name in both tables.
• CROSS JOIN: The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of
records from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join-condition is absent from the statement.
Joins:
Joins are used to combine multiple tables.
Whenever we want to fetch the data from two or more tables we should use the joins concept.
Types of Joins:
A. Inner Join
B. Equi Join
C. Natural Join
D. Outer Join If Tables are related
a. Left Outer Join
b. Right Outer Join
c. Full Outer Join
E. Cross Join Least Priority
F. Cartesian Join
G. Self Join Table alias is used compulsory
Inner Join:
Inner join will join two or more tables based on the common column between them.
It will return only the matching records.
It is also called as Simple Join.
Syntax:
select */attributes from Table1 inner join Table2 on Table1.B = Table2.B;
Example:
Table 1 Table 2 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 7 8 8 1
5 6 9 1
7 8
Equi Join:
Equi join is same as Inner Join.
In Equi join the joining condition will be given in the where clause suing explicit ‘=’ operator.
Syntax:
select */attribute from Table1, Table2 where Table1.B = Table2.B;
Example:
Table1 Table 2 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1
7 8 8 1
9 1
5 6
9 8
Natural Join:
Natural join will perform inner join and then it will remove one or more pairs of identically names
columns and keep one cop of it.
‘on’ keyword should not used and joining condition should not be given.
Syntax:
select * from Table1 natural join Table2;
Example:
Table 1 Table 2 Inner Join Output Natural Join Output
A B B C A B B C B A C
1 2 2 1 1 2 2 1 2 1 1
8 1 7 8 8 1 8 7 1
3 4
9 1
5 6
7 8
Outer Join:
a) Left Outer Join:
In left outer join returns all the rows from left table and only matching rows from the right
table.
Syntax:
select */attribute from Table1 left outer join Table2 on Table1.B = Table2.B;
or
select */attribute from Table1 left join Table2 on Table1.B = Table2.B;
Example:
Table 3 Table 4 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 3 4 - -
5 6 9 1 5 6 - -
7 8 7 8 8 1
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 7 8 8 1
5 6 9 1 - - 9 1
7 8
c) Full Outer Join:
Full Outer join is a combination of left outer join and right join outer join
It returns both matching and non matching records from both the tables.
Then the result set will be large.
It will avoid duplicate records from the table
Syntax:
select */attribute from Table1 full outer join Table2 on Table1.B = Table2.b;
Example:
Table 7 Table 8 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 3 4 - -
5 6 9 1 5 6 - -
7 8 7 8 8 1
- - 9 1
Cross Join:
Cross Join works on the principle that each and evry row of one table matches with all the rows of
another table.
It is the cross product of tables.
Syntax:
select */attribute from Table1 cross join Table2
Example:
Table 9 Table 10 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 1 2 8 1
5 6 9 1 1 2 9 1
7 8 3 4 2 1
3 4 8 1
3 4 9 1
5 6 2 1
5 6 8 1
5 6 9 1
7 8 2 1
7 8 8 1
7 8 9 1
Cartesian Join:
Syntax:
select * from Table1, Table2;
Example:
Table 11 Table 12 Output:
A B B C A B B C
1 2 2 1 1 2 2 1
3 4 8 1 1 2 8 1
5 6 9 1 1 2 9 1
7 8 3 4 2 1
3 4 8 1
3 4 9 1
5 6 2 1
5 6 8 1
5 6 9 1
7 8 2 1
7 8 8 1
7 8 9 1
Self Join:
In self join the table is join to itself.
During the runtime two copies of the same table will be present.
Self join is used is used when we want to compare the data of a column in a table with another data
present in the same column of the same table.
Syntax:
select f.F_name, f.L_name, f.Salary
from Emp e, Emp f
where f.Salary>e.Salary and e.F_name = ‘Pandey’;
Example:
Emp e Emp f
Write a query to display all the details from table1 and table2 where the value of column2 in table1 is
equal to the value of column2 in table2.
select * from Table1 inner join table2 on Table1.B = Table2.B;
Write a query to display all the details from table1 and table2 where the value of column2 in table1 is
equal to the value of column2 in table2 by using natural join keyword.
select * from Table1 natural join table2;
Display all the details from table1 and table2 by using left outer join keyword.
select * from Table1 left join table2 on Table1.B = Table2.B;
Write a Query to display all the details from table1 and table2 by using right outer join keyword.
select * from Table1 right join table2 on Table1.B = Table2.B;
Write a Query to display all the details from table1 and table2 by using full outer join keyword.
select * from Table1 full outer join table2 on Table1.B = Table2.B;
Write a Query to display all the details from table1 and table2 by using cross join keyword.
select * from Table1 cross join table2 on Table1.B = Table2.B;
Write a query to display the emp_id ,emp_name, salary and the dept_name for all the employees whose
dept_id in the emp table is equal to the dept_id in the dept table using inner join keyword.
select emp_id, f_name, salary, dept_name from emp inner join dept on emp.dept_id = dept.dept_id;
Give an example to Perform natural join.
select * from emp natural join dept;
Perform emp table cross join with Dept table.
select * from emp cross join dept;
Perform emp table left outer join with Dept table.
select * from emp left outer join dept on emp.dept_id = dept.dept_id;
Perform emp table right outer join with Dept table.
select * from emp right outer join dept on emp.dept_id = dept.dept_id;
Perform emp table full outer join with Dept table.
select * from emp full outer join dept on emp.dept_id = dept.dept_id;
Insert the missing parts in the JOIN clause to join the two tables emp and dept, using the
dept_id field in both tables as the relationship between the two tables.
SELECT *
FROM emp e
LEFT OUTER JOIN dept d
e.dept_id = d.dept_id;
Choose the correct JOIN clause to select all records from the two tables where there is a
match in both tables.
SELECT *
FROM emp e
inner join dept c
ON e.dept_id=c.dept_id;
COMMANDS
SQL Commands
Truncate Savepoint
Delete
Drop
CRUD Operation:
CRUD stands for Create Read Update Delete
Data Definition Language:
The commands of DDL are used to define the structure of the table.
The commands of DDL are Create, Alter, Truncate, Drop.
a) Create:
Create command is used to create database, tables, objects.
Syntax: Example:
create table table_name Create table Bank
( (
column_name1 datatype, bid int,
column_name2 datatype, bname varchar2(87),
column_name3 datatype, bhq varchar2(46)
. );
.
.
);
b) Alter:
Alter command is used to alter or modify the structure of the table.
Adding a column to an existing table:
Syntax: Example:
Alter table table_name Alter table Bank
Add column_name database; Add ph_no number;
Dropping a column from an existing table:
Syntax: Example:
Alter table table_name Alter table bank
drop column column_name; drop column ph_no;
Renaming a column in an existing table:
Syntax: Example:
Alter table table_name Alter table Bank
rename column old_column_name to new_column_name rename column bname to bankname;
c) Truncate:
Truncate command will delete or remove all the rows in the table in one single shot (at once).
Syntax: Example:
Truncate table table_name; Truncate table Bank_Details;
d) Drop:
Drop command is used to delete a table, database, database objects.
Syntax: Example:
Drop table table_name; Drop table Bank_Details;
Select 35 % of salary from pandey , 10% of Salary for ganeshan and for other 15 % of salary from emp
table
select case when l_name = 'Pandey' then salary*0.35 when l_name = 'ganeshan' then salary*0.35 else
salary*0.15 end
from emp;
CASEWHENL_NAM E='PANDEY'THENSALARY*0.35WHENL_NAM E='GANESHAN'THENSALARY*0.35ELSESAL
ARY* 0.15END
11900
6750
8250
5400
2700
12750
4275
1800
7950
7950
3750
6825
6900
1800
2925
5925
4425
4425
1425
If there are two tables employee1 and employee2, and both have common record. How can I fetch all
the records but common records only once?
select * from employee1 union select * from employee2;
How to fetch only common records from two tables employee1 and employee2?
select * from employee1 Intersect select * from employee2;
How can I retrieve all records of employee1 those should not present in employee2?
select * from employee1 minus select * from employee2;
DATABASE OBJECTS
Views:
Views are the virtual tables which are created on the basis of original table / actual table.
Views will make the complex query simple.
Views provide data independence.
creating the view
Syntax:
create view view_name
as
SQL Query
Example:
create view dec
as
select f_name, salary, dept_id
from emp
where dept_id=22;
Fetching the data
Syntax:
select * from view_name;
Example:
select * from emp;
Store procedure:
Store procedure is a proposed SQL statement which are based in the database and are reused again and again
when required.
The store procedure has to be called explicitly.
For creating store procedure
Syntax:
Create procedure procedure_namr(parameters)
as
Begin
SQL Query;
END;
For Deleting store procedure
Syntax:
Drop procedure procedure_name;
For calling Procedure
Syntax:
Begin
Procedure_name( procedure_values)
END
Example:
Create procedure hike_sal(sal IN Number, did IN number)
As
Begin
Update emp1
Set salary= Salary + sal
Where dept_id = did
END
Begin
hike_sal(2000,22);
END
Drop procedure hike_sal;
Triggers:
Triggers are also a kind of store procedures.
Triggers are prepared SQL statements which are saved in a database and are called autonomously.
Action and event are the two main component in triggers, when certain event taken place action
occurs in response.
There are six types of Actions and Events:
Event Action
Before Insert
After Insert
Before Update
After Update
Before Delete
After Delete
id name
Insert :new
01 Cat
Update :new 02 Rat
: old
Delete :old
Sequence:
Sequence will generate the automatic number to the specified column.
Creating the Sequence
Syntax:
Create Sequence Sequence_name
Start with start_value
Increment by inc_value;
Deleting the Sequence
Syntax:
Drop Sequence sequence_name;
Keywords:
nextval:
It will generate the next value in the Sequence
currval:
It will generate the current value in the Sequence
Example:
Create Sequence Dec
Start with 1
Increment by 1;
Drop Sequence Dec;
How to use the Sequence ?
id name
Insert into table_name values(sequence_name.nextval,'value');
1 Sachin
2 Virat
Insert into demo values(Dec.nextval,'Sachin')
Insert into demo values(dec.nextval,'virat')
Synonym:
Synonym is used to give another name to the table
Creating the synonym
Syntax:
create synonym synonym_name for table_name;
Deleting the synonym
Syntax:
Drop synonym synonym_name;
Example:
create synonym emp_details for emp;
Drop synonym emp_details;
ER DIAGRAM
ER Diagrams: Entity Relationship Diagrams are the diagrammatic representation of tables in the database.
Entity: Any thing or object which exists in the real world is called as ‘Entity’.
Entity is categorised into two types
1. Physical Entity
2. Conceptual Entity
1. Physical Entity: If an entity exists in the physical manner in the real world.
Example:
Pen, Paper, Camera, e,t,c.,
2. Conceptual Entity: If an entity exists in the conceptual manner in the real world.
Example:
Internet, Programming Languages, e.t.c.,
Entity is represented as a rectangular box
Example: student
Attribute:
The property that decides an entity is called as attribute.
Attribute is represented as eclipse
Example:
Student
Id marks age
Types of Attributes:
1. Simple attribute: Simple attribute are such attributes which cannot be further divided.
Student
address
2. Composite attribute: Composite attribute are such attributes which can be further divided.
Student
name
First
Middle
Last
1. Simple Attribute:
Single valued attribute: These attributes are such attributes which will have only & only a single
value.
Student
address
address
Derived attribute: Derived attributes which are derived from another attribute.
Derived attributes are represented as dotted ellipse.
Student
address
Student
Ph_no
Ph.n
o
Weak Entity:
If an entity is not having the key attribute of its own it becomes weak entity.
Weak entity will be dependent on strong entity.
Weak entity is represented as double rectangular box.
Example:
Employee Dependent
Strong Entity:
If an entity is having the key attribute of its own it becomes strong entity.
It is represented as single rectangular box.
Relationship:
Association between any two entities is called “Realtionship”.
Relationship is represented as Rhombus shape.
Example:
Driver Drives Car
Types of Relationship:
One-to-One (1:1)
One-to-Many (1:M)
Many-to-One (M:1)
Many-to-Many (M:M)
One-to-One (1:1):
1 1
have
Person Passport
One-to-Many (1:M):
1 M
Teachers Teacher Students
Many-to-One (M:1):
M 1
Works
Employees Company
Many-to-Many (M:M):
M M
Person have Passport
1 M Dotted
ellipse
Works Enroll
in to
M M
1 1
Professor teach Course
Ph no Cid Cfee
Pid
Cname Cdur
Pname salary
ER SCHEMA
University
Uid Uname Uloc
Student
Sid fname lname marks DOB Uid
Course
Cid Cname Cdur Cfee Pid
Professor
Pid Pname salary Uid
Ph.no
Pid Ph.no
Std_Course_Details
Sid Cid
NORMALIZATION
Normalization is the process of systematic approach on decomposing (splitting) the table in order to
overcome the problems such as,
1. Spurious tuples 2. Anomalies 3. Data Redundancy
1. Spurious tuples:
Spurious tuples are such tuples which are not present in the original table but get generated when the
table is decomposed and further joined.
Example:
A B
a1 b1
a2 b2
a3 b3
A B C A B C
a1 b1 c1
a1 b1 c1
a2 b2 c1
a2 b2 c2 a2 b2 c2
a3 b3 c3 a3 b2 c1
a3 b2 c2
B C
b1 c1
b2 c1
b2 c2
2. Anomalies:
Anomalies are the problem that occur in the table while performing the DML actions such as
insertion, updation, & deletion
There are 3 types of Anomalies;
1. Insert Anomaly 2. Update Anomaly 3. Delete Anomaly
3. Data Redundancy:
Repetition of the same data which leads to memory wastage is called Data Redundancy.
Determinant:
If an attribute is able to determine the value of another attribute it is called “Determinant”.
Functional Dependency:
If an attribute is dependent on another attribute it is called “Functional Dependency”.
Example:
Determine Determine
x y Sid Sname
F.D F.D
K K
D D D
Student(Sid, Sname, Cid, Cname, Cdur, Marks, Grade)
RELATIONAL MODEL
ASSIGNMENT QUERIES
Refer the below table for further queries.
STATION
Field Type
ID NUMBER
CITY VARCHAR2(21)
STATE VARCHAR2(21)
LAT_N NUMBER
LONG_W NUMBER
Query a list of CITY and STATE from the STATION table.
Let N be the number of CITY entries in STATION, and let N’ be the number of distinct CITY names
in STATION; query the value of N-N’ from STATION. In other words, find the difference between
the total number of CITY entries in the table and the number of distinct CITY entries in the table.
Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION.
Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as 2 nd
character.
Query the list of CITY names from STATION that do not start with vowels
Write a query that prints a list of employee names (i.e.: the name attribute) for employees in
Employee having a salary greater than 2000 per month who have been employees for less than 10
months. Sort your result by ascending employee_id.
Column Type
employee_id Integer
name String
months Integer
salary Integer
Given the CITY and COUNTRY tables, query the sum of the populations of all cities where the
CONTINENT is 'Asia'.
CITY
Field Type
ID NUMBER
NAME VARCHAR2(17)
COUNTRYCODE VARCHAR2(3)
DISTRICT VARCHAR2(20)
POPULATION NUMBER
COUNTRY
Field Type
CODE NUMBER
CONTINENT VARCHAR2(17)
REGION VARCHAR2(3)
SURFACEAREA VARCHAR2(20)
INDEPYEAR NUMBER
POPULATION NUMBER
LIFEEXPRECTANCY VARCHAR2(4)
GNP NUMBER
GNPOLD VARCHAR2(9)
LOCALNAMR VARCHAR2(44)
GOVERNMENTFORM VARCHAR2(44)
HEADOFSTATE VARCHAR2(32)
CAPITAL VARCHAR2(4)
CODE2 VARCHAR2(2)