DMS 22319 Unit 3 Notes0001
DMS 22319 Unit 3 Notes0001
DMS 22319 Unit 3 Notes0001
(14 Marks)
CO3: C3-22319-3: Create and manage database using SQL functions and
advanced SQL commands.
Institute Vision:
To provide quality technical education to rural students.
Institute Mission:
M1: To impart trainings for developing hands on skills.
M2: To develop technical skills by practicing the best teaching-learning pedagogies.
M3: To enhance career opportunities through industry connect.
1
In-Built Functions in SQL:
A. STRING FUNCTIONS:
String is a collection of characters. Ex: computer, etc.
1. Initcap:
Initcap function is used to convert first letter of each word to capital letter.
Syntax: select initcap (string) from dual;
select initcap (columname) from tablename;
Ex: select initcap ('computer department') from dual;
Output: Computer Department
Ex: select initcap (fname) from stud;
Output: Anil
Sunil
2. Concatenate:
Concat function is used to join two strings or two columns from table together.
Syntax: select concat (string1, string2) from dual;
select concat (column1, column2) from tablename;
Ex: select concat ('computer','-dept') from dual;
Output: computer-dept
Ex: select concat (fname,lname) from stud;
Output: anildighe
sunilverma
3. Replace:
Replace function is used to replace the old string with new string.
Syntax: select replace (oldstring, newstring) from dual;
2
SQL> select replace('black','bl','p') from dual;
Output: pack
4. Translate:
Translate function converts the string from one-character set to another.
It replaces the occurrences of single character with another character.
Syntax: select translate (‘string’,’char1’,’char2’) from dual;
Ex: select translate('asadaf','a','z') from dual;
Output: zszdzf
5. Lower:
Lower function converts the uppercase characters to lowercase characters.
Syntax: select lower (string) from dual;
select lower (columnname) from tablename;
Ex: select lower('COMPUTER') from dual;
Output: computer
Ex: select lower(fname) from stud;
Output: anil
sunil
6. Upper:
converts the string to all uppercase characters.
Upper function converts the lowercase characters to uppercase characters.
Syntax: select upper (string) from dual;
select upper (columnname) from tablename;
Ex: select upper (‘computer’) from dual;
Output: COMPUTER
Ex: select upper (fname) from stud;
Output: ANIL
SUNIL
7. Substring (substr):
Substring function is used to display some portion of the main string.
Syntax: select substr (string, starting_position, length) from dual;
3
select substr (columnname, starting_position, length) from tablename;
Ex: select substr ('computer',1,4) from dual;
Output: comp
Ex: select substr (fname,1,2) from dual;
Output: an
su
8. Ltrim:
Ltrim function used to trim (delete) the given left side characters.
Syntax: select ltrim (string, char) from dual;
select ltrim (columnname, char) from tablename;
Ex: select ltrim ('computer','comp') from dual;
Output: uter
Ex: select ltrim (fname,'a') from stud;
Output: nil
9. Rtrim:
Rtrim function used to trim (delete) the given right side characters.
Syntax: select rtrim (string, char) from dual;
select rtrim (columnname, char) from tablename;
Ex: select rtrim ('computer','uter') from dual;
Output: comp
Ex: select rtrim (fname,'il') from stud;
Output: an
sun
4
10. Lpad:
Lpad function used for left side padding with given symbol and convert the string in given
length.
Syntax: select lpad (string, length, symbol) from dual;
select lpad (columnname, length, symbol) from tablename;
Ex: select lpad ('computer',10,'*') from dual;
Output: **computer
Ex: select lpad (fname,10,'*') from stud;
Output: ******anil
*****sunil
11. Rpad:
Rpad function used for right side padding with given symbol and convert the string in
given length.
Syntax: select rpad (string, length, symbol) from dual;
select rpad (columnname, length, symbol) from tablename;
Ex: select rpad ('computer',10,'*') from dual;
Output: computer**
Ex: select rpad (fname,10,'*') from stud;
Output: anil******
sunil*****
12. Length:
Length function used to calculate the length of the given string.
Syntax: select length (string) from dual;
select length (columnname) from tablename;
Ex: select length('computer') from dual;
Output: 8
Ex: select length(fname) from stud;
Output: 4
5
5
B. ARITHMETIC FUNCTIONS:
1. ABS:
ABS function converts negative value in positive value (absolute).
Ex: select abs (-250) from dual;
Output: 250
2. CEIL:
CEIL function used to round off the given value to its next complete number.
Ex: select ceil (48.876) from dual;
Output: 49
Ex: select ceil (4.00001) from dual;
Output: 5
3. FLOOR:
FLOOR function used to round off the given value to its previous complete number.
Ex: select floor (48.876) from dual;
Output: 48
Ex: select floor (4.00001) from dual;
Output: 4
4. MOD:
MOD function is used to display remainder after division.
Ex: select mod (10,3) from dual;
Output: 1
Ex: select mod (19,5) from dual;
Output: 4
5. POWER:
POWER function used to calculate the power of the given value.
Ex: select power (5,2) from dual;
Output: 25
Ex: select power (4,3) from dual;
Output: 64
6
6. SQRT:
SQRT function used to calculate the square root of the given value.
Ex: select sqrt (25) from dual;
Output: 5
Ex: select sqrt (49) from dual;
Output: 7
C. AGGREGATE FUNCTIONS:
Aggregate functions are used to perform the operations on numeric values.
Aggregate functions are:
Sum
Avg
Count
Min
Max
Consider the emp table below:
EMPNO ENAME SAL
102 prathamesh patil 25000
101 ashish deshpande 20000
105 aditya adhav 15000
1. avg:
Output: 20000
2. count / count(*):
Count function is used to calculate records of table (count(*)) or given column count().
Ex: select count (*) from emp;
Output: 3
Ex: select count (ename) from emp;
Output: 2
7
3. min:
Min function used to find out the least (minimum) value in given column.
Output: 15000
4. max:
Max function used to find out the greatest (maximum) value in given column.
Output: 25000
5. sum:
Output: 60000
Miscellaneous Functions
NVL: is used with fields where instead of displaying null values we want to display zeros.
8
D. DATE FUNCTIONS:
Date functions are used to display or perform the operation on date.
1. SYSDATE:
2. ADD_MONTHS:
Ex: select add_months (sysdate,2) from dual; (add 2 months in the current date)
3. LAST_DAY:
Last_day function used to display the last day of the month as per given date.
4. MONTHS_BETWEEN:
Months_between function used to find out the difference of the months between two
dates.
5. NEXT_DAY:
Next_day function used to return the date of the given weekday after specified date.
9
6. ROUND FUNCTION:
Rounds given date to the day or month or year as per specified date.
ROUND(SYSDATE)
--------------------------
01-SEP-23
ROUND(SYSDATE)
-----------------------
01-SEP-23
ROUND(SYSDATE)
-----------------------
01-JAN-24
7. TRUNC FUNCTION:
Used to return the date with the time portion of the day truncated to unit specified in the
format.
TRUNC(SYSDATE)
-----------------------
01-SEP-23
TRUNC(SYSDATE)
----------------------
01-SEP-23
10
SQL> select trunc(sysdate,'year')from dual;
TRUNC(SYSDATE)
------------------------
01-JAN-23
8. GREATEST:
Used to find out the greatest date among the given dates.
GREATEST(sysdate,'23-aug-2013')
-------------------------------------------------
01-SEP-23
GREATEST('23-aug-2013','23-aug-2012')
--------------------------------------------------------
23-aug-2013
11
DATE CONVERSION FUNCTIONS
TO_CHAR():
SYSDATE
---------------
25-AUG-23
TO_CHAR(sysdate,'dd/mm/yy')
---------------------------------------------
25/08/23
TO_DATE():
The employee anil joined on 30/08/2022 and working in HR department having salary 2000
12
CLAUSES (where, Group by, having, order by)
SQL> create table emp_details(empno number(3) primary key,ename varchar(20),sal
number(7,2),comm number(7,2),deptno number(3),job varchar(20),hiredate date);
Table created.
SQL> select * from emp_details;
GROUP BY
Group by clause is used to collect the data as multiple records and group them to produce the
result.
AVG(SAL)
----------------
20000
AVG(SAL)
-------------------
20000
JOB COUNT(*)
-------------------- ----------
director 1
clerk 1
engineer 3
sr. clerk 1
manager 1
13
SQL> select deptno,count(*) from emp_details group by deptno;
DEPTNO COUNT(*)
---------- -------------------
1 1
6 1
2 2
4 1
5 1
3 1
6 rows selected.
HAVING CLAUSE
Having clause is used to execute the summary query. It is like the “where” clause, difference is
that it gives summary value (used with aggregate functions) instead of column value.
JOB COUNT(*)
-------------------- ----------
director 1
engineer 3
sr. clerk 1
manager 1
SQL> select deptno,sum(sal) as "Total salary" from emp_details group by deptno having
sum(sal)>15000;
SQL> select deptno,count(*) as "No. of emp" from emp_details group by deptno having
count(*)>1;
DEPTNO No. of emp
---------- ------------------------
2 2
14
SQL> select deptno,count(*) as "No. of emp" from emp_details group by deptno having
count(*)=1;
ORDER BY CLAUSE
To view the data in sorted order, order by clause is used. By default, the data is sorted in
ascending order.
EMPNO ENAME
---------- ----------------------------------
101 ashish deshpande
102 prathamesh patil
105 aditya adhav
106 priyanka pawar
107 bhakti joshi
109 aniruddha thipse
110 rajesh oak
7 rows selected.
DEPTNO
----------------
1
2
2
3
7 rows selected.
DEPTNO
----------
6
5
4
3
15
JOINS
Joins are used to join two or more tables
Table created.
Table created.
16
SIMPLE JOIN
It joins two tables based on the common fields.
12 rows selected.
17
SELF JOIN
Joining the table to itself.
OUTER JOIN
It is extension to the simple join. It joins two tables same as simple join but with + operator.
7 rows selected.
Ex: Display the records from table whose deptno belongs to city chennai.
SQL> select * from emp_details where deptno=(select deptno from dept_details where
city='chennai');
18
**For below topics use the following table
SQL> create table emp_details(empno number(3) primary key,ename varchar(20),sal
number(7,2),comm number(7,2),deptno number(3),job varchar(20),hiredate date);
Table created.
SQL> select * from emp_details;
VIEWS
Once the table is created and records are inserted, the access to that table cannot be given
partially.
i.e. if user want to access selected columns or records from the table it is not possible. For this
the number of tables with the selected columns needs to be created. But this is the lengthy
process.
Instead of creating number of new tables, a table can be made accessible to several users at a
time by using VIEWS.
View can be defined as a logical part in which the user can have selected columns or records.
View can be created with the help of SELECT statement.
Operations (insert, delete, update, select) executed on VIEW can be same as Table.
CREATE VIEW
Syntax: create view <view_name> as select <column_name1>,<column_name2>,….. from
<table_name>;
View created.
EMPNO ENAME
---------- -----------------------------------
102 prathamesh patil
106 priyanka pawar
101 ashish deshpande
105 aditya adhav
107 bhakti joshi
109 aniruddha thipse
110 rajesh oak
19
SQL> create view v2 as select sal, comm, deptno from emp_details;
View created.
SQL> create view v3 as select ename "Employee Name", job "Designation" from emp_details;
View created.
20
INSERT record into View
Views are used to insert the records in the base tables.
If new record is inserted in the view that same record can also be inserted in base table.
The same record can be inserted in other related views as well as base table. As below-
21
SQL> select * from v1;
EMPNO ENAME
---------- --------------------
102 prathamesh patil
106 priyanka pawar
101 ashish deshpande
105 aditya adhav
107 bhakti joshi
109 aniruddha thipse
110 rajesh oak
112 parag joshi
1 row deleted.
22
SQL> select * from v2;
23
SEQUENCES
A sequence generates unique and sequential integer values.
A sequence may have different orders like ascending or descending.
CREATE Sequence
Syntax: create sequence <sequence_name> incremented by <number> start with <number>
maxvalue <number> minvalue <number> cycle/nocycle cache <number>/nocache
SQL> create sequence seq1 increment by 1 start with 1 maxvalue 10 minvalue 1 cycle cache 9;
Sequence created.
NEXTVAL
---------------
1
NEXTVAL
------------------
2
nextval is used to determine the next value in the sequence.
CURRVAL
----------------
2
currval is used to determine the current value in the sequence.
24
SQL> insert into emp1 values(seq1.nextval,'avinash',24000);
1 row created.
Instead of inserting the empno value in INSERT INTO command, we use the created sequence
(seq1.nextval). It automatically assign the values to empno as per the sequence.
Sequence dropped.
25
INDEX
Indexes are used to access the records from the tables easily and fast.
SIMPLE INDEX
The index created on single column is simple index.
Syntax: create index <index_name> on <table_name>(column_name);
COMPOSITE INDEX
The index created on multiple columns is composite index.
Syntax: create index <index_name> on table_name>(column_name1,column_name2…);
UNIQUE INDEX
Unique index is created on single or multiple columns which having the unique domain values.
Syntax: create unique index <index_name> on table_name>(column_name1,column_name2…);
DROP Index
To drop the index from the datebase the DROP command is used.
Syntax: drop index <index_name>;
26
SNAPSHOTS
Snapshots are used to create the recent copy of the table.
Snapshot may contain all records from the table or selected rows and columns from the table.
Using snapshots, we can easily monitor the changes made in the table step by step.
CREATE Snapshot
Syntax: create snapshot <snapshot_name> as <select query>;
DROP Snapshot
To drop the snapshot from the database the DROP command is used.
Syntax: drop snapshot <snapshot_name>;
27
SYNONYM
Synonym is another name given to the table, view, sequence, stored procedure, function for
the user’s convenience to use it.
Instead of typing the large length name we can use synonym to give short name to the table.
CREATE Synonym
Syntax: create synonym <synonym_name> for <table_name>;
DROP Synonym
To drop the synonym the DROP command is used.
Syntax: drop synonym <synonym_name>;
28
Assignment
1. Consider the structure emp (empno, ename, job, joindate, sal, comm, deptno)
Dept (empno, ename, deptno)
Write SQL queries for the following:
a. Display the names of employee excluding ‘manager’.
b. Display average salaries of each department.
c. Display the details of employee whose names second letter is ‘a’.
d. Find the employee who belongs to deptno 10 and 30 (don’t use between operator)
e. Find out the number of employees who works as ‘manager’.
f. Change the salary of ‘rahul’ to 50000.
g. Display the output as
the employee RAHUL works as MANAGER in deptno 10 having salary 50000 rupees.
h. Display the details of employee whose salary greater than rahul’s salary.
i. Delete the records of employees whose joindate is before 10-dec-2007.
j. Display the joindate from table in the form of DECEMBER 16, 2006.
k. Display the names of employees in capital letter who have salary greater than
20000.
l. Create the user ABC and give him full access on ‘emp’ table.
m. Create the emp table as above and apply constraints as- empno primary key, ename
not null, deptno unique, sal check constraint.
n. Create dept table as above and apply foreign key.
o. Display annual salary of each employee.
p. Display the number of employees of deptno 10.
q. Display ename, empno from emp and ename, deptno from dept which having
deptno same.
r. Display the employees deptno wise.
s. Display the date and time of all employees from emp table.
2. What is the use of ‘where’ and ‘between’ clause? Explain with example.
3. Explain how aggregate function work with ‘group by’ clause.
4. Define the use of clauses in SQL. (2)
5. Explain the ‘order by’ clause in SQL with example.
6. List and explain four arithmetic operators in SQL with example.
7. Explain inner join and outer join.
8. Describe string function, date and time function.
9. What are views? Give its syntax and example.
10. What is snapshot? Explain with example.
11. Explain the importance of synonym with example.
12. Explain index with its types.
13. What are sequences? Explain with example.
29