SlideShare a Scribd company logo
1 of 77
www.cccdigital.io
DBMS
Agenda
 Introduction to DBMS
 Database Models
 SQL
2
Exclusive: VLITS
Data
Data may be defined as a known Raw fact that can be recorded and that
have no meaning.
Example:
101 dinesh 2000
102 mahesh 3000
In above example, there no meaningful data such data is known as Raw
facts
3
Exclusive: VLITS
Information
• It is a collection of meaningful data or processed data
• Data and information are closely related and are often used
interchangeably.
• Information is processed, organized or summarized data.
Example:
EmpID Ename Salary
101 dinesh 2000
102 mahesh 3000
4
Exclusive: VLITS
DATA STORE: It is a place where we can store data or information.
1) Books & Papers
2) Flat files
3) Database
FLAT FILES: This is a traditional mechanism which is used to store
data or information in individual unrelated files. These files are also
called as Flat Files.
Drawbacks of Flat files:
1) Data Retrieval
2) Data Redundancy
3) Data Integrity
4) Data Security
5) Data Indexing
* In many cases, all records in a file are of the same record type, i.e.,
all the records are having an identical format.
5
Exclusive: VLITS
Database
• A database is defined as a collection of logically related data stored
together that is designed to meet the information needs of an
organization.
• It is basically an electronic filing cabinet, which contain computerized
data files.
• It can contain one data file or large number of data files depending on
organizational needs.
• A database is organized in such a way that a computer program can
quickly select desired pieces of data.
6
Exclusive: VLITS
• A database management system (DBMS), is a generalized software
system for manipulating databases.
• DBMS is also a collection of programs that enables users to create
and maintain database.
Example DBS:
ORACLE, FOXPRO, DB2, TERADATA, SQLSERVER, SYBASE, MYSQL,
INGRESS, INFORMIX, SQLLITE…… etc;
• It is basically a computerized record-keeping system, which it stores
information and allows users to add, delete, retrieve and update that
information on demand.
• It provides for simultaneous use of a database by multiple users and
tool for accessing and manipulating the data in the database.
Database Management System
7
Exclusive: VLITS
OPERATIONS PERFORMED ON DATABASE SYSTEMS
 Inserting new data into existing data files
 Adding new files to the database
 Retrieving data from existing files
 Changing data in existing files
 Deleting data from existing files
 Removing existing files from the database
8
Exclusive: VLITS
Three – Level ANSI Database Architecture
The ANSI proposes a Three Level Database Architecture,
The three levels are
1.External Level 2.Conceptual Level 3.Internal Level (Physical Level)
EXTERNAL LEVEL: This level describes end user view of the database. i.e.,
in this level some group of users access only part of the database. In this
level only we are defining the view and those views given to the number of
users.
CONCEPTUAL LEVEL: It describes logical representation of the database.
Conceptual level defines type of data storing in database and also defines
what type of data does not store in database using constraints and also
specifies the relationship between data items.
INTERNAL LEVEL: Internal level describes how physically data is stored in
database. This level is handled by database administrator only. In relational
databases indexes, cluster are available in internal level.
9
Exclusive: VLITS
10
Exclusive: VLITS
A data model provides a way to describe the design of a database at
physical, logical and view level.
A data model is a mechanism that provides the abstraction for database
application.
How data is represented at the conceptual level defined by means of “Data
Model”.
DATA MODELS
11
Exclusive: VLITS
Data models can be broadly classified into the following three categories:
Record-based data models
Hierarchical data model.
Network data model.
Relational data model.
Object-based data models
Entity-relationship.
Semantic.
Functional.
Object-oriented.
Physical data models
Unifying model.
Frame memory model.
But, The most popular and most used data models are
Relational Data Model
Entity Relationship Model
DATA MODELS
12
Exclusive: VLITS
In 1970, E.F.Codd introduced Relational Data Model.
In this data model we are storing data in 2- dimensional tables
RELATIONAL DATA MODEL
13
Exclusive: VLITS
Entity -Relationship Data Model
An entity–relationship (E-R) model is a high-level conceptual data model,
which has a diagrammatic representation of data for an enterprise of
business establishment to produce a well-designed database.
ER model can be easily converted into relational model by simply
converting ER model into tables.
14
Exclusive: VLITS
Entity
An entity is an object of concern used to represent the things in the real world,
for example: car, table, book, etc.
An entity need not be a physical entity, it can also represent a concept in real world.
For example: project, loan, etc
rectangles representing entity
Entity Set or Entity Type:
A collection of a similar kind of entities is called an Entity Set or entity
type
15
Exclusive: VLITS
Attributes
An attribute is a property used to describe the specific feature of the entity.
So to describe an entity entirely, a set of attributes is used.
ellipses representing attributes.
Entity -Relationship Data Model
16
Exclusive: VLITS
Relationships
A relationship can be defined as:
• a connection or set of associations, or
• a rule for communication among entities
diamonds representing relationship sets
Entity -Relationship Data Model
17
Exclusive: VLITS
Cardinality specifies the number of instances of an entity associated with another
entity participating in a relationship. Based on the cardinality binary relationship can
be further classified into the following categories:
One-to-one: An entity in A is associated with at most one entity in B, and an
entity in B is associated with at most one entity in A.
Example: Relationship between college and principal
Relationship Cardinality
18
Exclusive: VLITS
One-to-many: An entity in A is associated with any number of entities in B.
An entity in B is associated with at the most one entity in A.
Example: Relationship between department and faculty.
Relationship Cardinality
19
Exclusive: VLITS
Many-to-one: An entity in A is associated with at most one entity in B. An
entity in B is associated with any number in A.
Example: Relationship between course and instructor. An instructor can
teach various courses but a course can be taught only by one instructor.
Relationship Cardinality
20
Exclusive: VLITS
Many-to-many: Entities in A and B are associated with any number of
entities from each other.
Example:
Taught by Relationship between course and faculty.
One faculty member can be assigned to teach many courses and one
course may be taught by many faculty members.
Relationship Cardinality
21
Exclusive: VLITS
E-R Diagram for Student, Course and Teacher Entities
22
Exclusive: VLITS
SQL
Structured Query
Language
23
Exclusive: VLITS
Structured Query Language (SQL) is used to manage data in all relational
databases like DB2,Oracle, SQL Server etc.
Majorly We can divide SQL into 4 Parts
DDL (Data Definition Language)
DML (Data Manipulation Language)
DCL (Data Control Language)
TCL (Transaction Control Language)
24
Exclusive: VLITS
Overview Of SQL Commands
25
Exclusive: VLITS
SQL Character Data Types:
SQL supports two character data types for storing printable and displayable characters. They are
used for storing information like name, address, description etc.
CHAR(n) VARCHAR2(n)
Useful for Storing characters having pre-determined length Storing characters whose length vary a lot
Storage size Size for n characters size for actual no. of characters + fixed size to store length
Storage Trailing spaces are applied if data to be stored has Trailing spaces are not applied.
smaller length than n.
Max size 2000 bytes 4000 bytes
Example A CHAR(10) field will store "Hello" as 10 bytes A VARCHAR2(10) field will store "Hello"
by appending 5 trailing spaces. as 7 bytes (assuming 2 bytes to store length).
Alte Name CHARACTER(n) CHARACTER VARYING(n)
SQL Data Types
26
Exclusive: VLITS
SQL supports SMALLINT, INTEGER and INT data types that are used for storing whole numbers. Unlike other databases Oracle
does not define different size limits for them. They are all treated internally to have 38 digits of precision.
SQL Non-Integral Data Types:
Nonintegral data types have an integer part and a fractional part. Either NUMERIC, DECIMAL or NUMBER data types can be
used to store nonintegral numbers.
Ex:
Number (3,1)
In the Above example first parameter is total number digits in the given value
Second parameter is number of digits after the Decimal point
Number (3)  555
Number (3,2)  5.55
Number (3,1)  55.5
Number (3,3)  0.555
SQL Integral Data Types:
27
Exclusive: VLITS
SQL Date & Time Data Types:
Date Data Type
• It is used to store date and time information
• The dates can be specified as literals using Gregorian Calendar
• The default format in ORACLE is DD-MM-YY
28
Exclusive: VLITS
DDL
Creating A Table:
CREATE TABLE Command
Syntax:
CREATE TABLE <table name>(
Column_name1 data type (column width) [constraints],
Column_name2 data type (column width) [constraints],
Column_name3 data type (column width) [constraints],
………………………………………..
);
Guidelines for creation of table:
• Table name should start with an alphabet.
• In table name, blank spaces and single quotes are not allowed.
• Reserve words of that DBMS cannot be used as table name.
• Proper data types and size should be specified.
• Unique column name should be specified.
29
Exclusive: VLITS
DDL
Creating A Table:
Example:
CREATE TABLE Student (
StudentId NUMBER,
FName VARCHAR2(15),
LName VARCHAR2(20),
Gender CHAR(1),
DOB DATE);
30
Exclusive: VLITS
SQL constraints are used to specify rules for data in a table.
Various constraints that can be created on database tables are:
 NOT NULL
 PRIMARY KEY
 CHECK
 UNIQUE
 FOREIGN KEY
 DEFAULT
Constraints:
31
Exclusive: VLITS
NOT NULL Constraint prevents a column from accepting NULL values.
NOT NULL can only be applied as a column level constraint. Constraint
name is optional and it can be specified by using CONSTRAINT keyword.
CREATE TABLE Student (
StudentId NUMBER CONSTRAINT Stud_SId_nn NOT NULL,
FName VARCHAR2(10) NOT NULL,
LName VARCHAR2(10));
32
Exclusive: VLITS
A column can be given the default value by using DEFAULT option. The data type of
column and default expression must be the same. DEFAULT option can be provided for
nullable as well as NOT NULL attributes. Oracle database does not consider DEFAULT as a
constraint.
CREATE TABLE Student (
StudentId NUMBER,
FName VARCHAR2(10),
DOJ DATE DEFAULT SYSDATE);
In The Above Table Definitions Whenever Input Is Not Provided Into The DOJ Field, The
Default Value SYSDATE Will Be Taken
33
Exclusive: VLITS
PRIMARY KEY constraint on a column ensures that the column cannot
contain NULL and duplicate values. We can have only one PRIMARY KEY in
a table.
CREATE TABLE Student (
StudentId NUMBER CONSTRAINT stud_sid_pk PRIMARY KEY,
FName VARCHAR2(10),
ContactNo NUMBER(10));
34
Exclusive: VLITS
CHECK constraint is used to limit the values that can be specified for a
column.
CREATE TABLE Student (
StudentId NUMBER,
FName VARCHAR2(10),
Gender CHAR (1) CONSTRAINT Stud_gender_ck1 CHECK (Gender
IN('M', 'F')));
35
Exclusive: VLITS
UNIQUE constraint on a column ensures that two rows in a table cannot
have same value in that column. Unlike Primary Key, UNIQUE constraint
allows NULL values. A table can have many UNIQUE constraints.
CREATE TABLE Student (
StudentId NUMBER,
FName VARCHAR2(10),
ContactNo NUMBER(10) CONSTRAINT Stud_cno_uk UNIQUE);
36
Exclusive: VLITS
Marks Table Without Connecting To Student
CREATE TABLE Marks(
CourseId NUMBER,
StudentId NUMBER,
MarksScored DECIMAL(5,2));
Marks Table With Connecting To Student Through Foreign Key
CREATE TABLE Marks(
CourseId NUMBER,
StudentId NUMBER CONSTRAINT marks_sid_fk REFERENCES Student(StudentId),
MarksScored DECIMAL(5,2));
37
Exclusive: VLITS
Data Definition Language is used to specify the structure i.e. schema of a relational database.
DDL provides commands for creation, modification and deletion of various database objects
like tables, views, stored procedures, indexes, constraints etc. The output of DDL is placed in
data dictionary which contains metadata i.e. data about data.
The Commands IN DDL
Create: Creates a new database objects like table,view,sequences,indexes
Alter: Modifies the existing database object
Drop: Delete exiting database object
Truncate: Deletes all rows from the database object
Rename :(oracle 9i) Rename the database object
DDL (Data Definition Language)
38
Exclusive: VLITS
ALTER TABLE Command:
This command is used for modification of existing
structure of the table in the following situation:
• When a new column is to be added to the table structure.
• When the existing column definition has to be changed, i.e., changing the
width of the data type or the data type itself.
• When integrity constraints have to be included or dropped.
• When a constraint has to be enabled or disabled.
Syntax
ALTER TABLE <table name> ADD (<column name> <data type>…);
ALTER TABLE <table name> MODIFY (<column name> <data type>…);
ALTER TABLE <table name> ADD CONSTRAINT <constraint name> <
constraint
type>(field name);
ALTER TABLE <table name> DROP<constraint name>;
ALTER TABLE <table name> ENABLE/DISABLE <constraint name>;
39
Exclusive: VLITS
ALTERING TABLE
Example:
Altering Table To Add A New Column
ALTER TABLE Student ADD Address varchar2(20)
ALTER TABLE Student ADD (Course VARCHAR2 (20), Marks NUMBER (10)); // Adding Two Columns
Altering Table To Modify The Existing Column
ALTER TABLE Student MODIFY Address varchar2 (50)
Altering Table To Rename A Column Name
Syntax:
ALTER TABLE <table name> RENAME COLUMN <old column name> TO <new column name>;
Example:
ALTER TABLE Student RENAME COLUMN Address To ResidentialAddress;
40
Exclusive: VLITS
Altering Table To Drop An Existing Column
ALTER TABLE Student Drop (ResidentialAddress)
ALTER TABLE Student DROP (GNDR, MobNo); // Dropping Two Columns
Altering Table To Add A Constraint
ALTER TABLE Student Add Constraint Studid_PK PRIMARY KEY (StudentID)
Altering Table To Drop An Existing Constraint
ALTER TABLE Student Drop constraint Studid_PK
ALTERING TABLE
41
Exclusive: VLITS
DROP TABLE Student;
Get it back from recycle bin.
Syntax: flashback table tablename to before drop;
To drop permanently:
Syntax: drop table tablename purge;
Example: (dropping a table oracle 10g Enterprise Edition)
SQL> drop table first;
Table dropped.
Get it back the table:
SQL> flashback table first to before drop;
DROP
42
Exclusive: VLITS
Truncate: Oracle 7.0 introduced truncate command , whenever we
are using “truncate” command total data permanently deleted from
table.
Syntax: truncate table tablename;
SQL> truncate table first;
Rename: It is used to rename a table and renaming a column also.
Renaming a Table:
Syntax: rename old_tablename to new_tablename;
Example: rename first to last;
Renaming a Column: (oracle 9i)
Syntax: alter table tablevname rename column old_column_name to
new_column_name;
Example: SQL> alter table emp rename column empno to sno;
43
Exclusive: VLITS
Creating a new table from another table:
Syntax: create table newtablename as select * from
existingtablename;
Example: SQL> create table test as select * from emp;
Note: In all database systems whenever we are copying a table from
another table constraints are never copied. (Primary table, Foreign
key,…..);
Creating a new table from existing table without copying data:
Syntax: create table newtablename as select * from existingtablename
where falsecondition;
Example: SQL> create table test1 as select * from emp where 1=2;
44
Exclusive: VLITS
QUESTION
You need to modify the STUDENTS table to add a primary key on the STUDENT_ID column.
The table is currently empty.
Which statement accomplishes this task?
A. ALTER TABLE students
ADD PRIMARY KEY student_id;
B. ALTER TABLE students
ADD CONSTRAINT PRIMARY KEY (student_id);
C. ALTER TABLE students
ADD CONSTRAINT stud_id_pk PRIMARY KEY student_id;
D. ALTER TABLE students
ADD CONSTRAINT stud_id_pk PRIMARY KEY (student_id);
E. ALTER TABLE students
MODIFY CONSTRAINT stud_id_pk PRIMARY KEY (student_id);
45
Exclusive: VLITS
Data Manipulation Language enables users to access or manipulate data in a relational
database. DML provides commands for retrieval, creation, deletion and modification of
information in a database.
The Commands In DML
Insert Creates new rows in the table
Update Modify data in the tables
Delete Delete the data from the tables
Select Retrieves the data from the tables
merge(oracle 9i)
Merge is an DML command which is used to transfer data from “source table”
into “target table” when table structure are same
DML (Data Manipulation Language)
46
Exclusive: VLITS
Inserting Data into Tables: - once a table is created the most natural thing
to do is load this table with data to be manipulated later.
Syntax:
insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
Example: SQL> create table first(sno number(10), name varchar(20));
Inserting data into table:
SQL> insert into first values(1, ‘abc’);
SQL> insert into first values(2, ‘sachin’);
DML commands
47
Exclusive: VLITS
Delete operations.
a) remove all rows
Syntax:
delete from <tablename>;
b) removal of a specified row/s
Syntax:
delete from <tablename> where <condition>;
48
Exclusive: VLITS
Updating the contents of a table
a) updating all rows
Syntax:
UPDATE <TABLENAME>
SET <COL>=<EXP>,<COL>=<EXP>;
b) updating selected records.
Syntax:
UPDATE<TABLENAME>
SET <COL>=<EXP>,<COL>=<EXP>
WHERE <CONDITION>;
49
Exclusive: VLITS
SELECT Statement
This statement is used for retrieving information from the databases. It can
be coupled with many clauses.
Query: It is an operation that retrieves data from one or more tables or views
Operators Used in “Select” statement:
1. Arithmetic operator(+,-,*,/)
2. Relational operator(=,<,<=,>,>=,[<> or!=]not equal).
3. Logical operator (AND,OR,NOT)
Operator Precedence
The basic operators used in SQL are * / + -
Operators of the same priority are evaluated From Left to right
Parentheses are used to force prioritized evaluation.
50
Exclusive: VLITS
SELECT Statement
This statement is used for retrieving information from the databases. It
can be coupled
with many clauses. Let us discuss these clauses in more detail:
Using Arithmetic operator
Example:
SELECT ENAME, SAL, SAL+300
FROM EMP;
Operator Precedence
The basic operators used in SQL are * / + -
Operators of the same priority are evaluated From Left to right
Parentheses are used to force prioritized evaluation.
Example:
SELECT ENAME, SAL, 12*SAL+100 FROM EMP;
51
Exclusive: VLITS
SELECT Statement
Using Column aliases
Example:
To print column names as NAME and ANNUAL SALARY
SELECT ENAME “NAME”, SAL*12 “ANNUAL SALARY”
FROM EMP;
Concatenation operator
Example:
Printing name and job as one string as column name employees:
SELECT ENAME||JOB “EMPLOYEES”
FROM EMP;
52
Exclusive: VLITS
SELECT Statement
Using Literal Character String
Example :
To print <name> IS A <job> as one string with column name employee
SELECT ENAME || ‘ IS A ’ || JOB AS “EMPLOYEE”
FROM EMP;
To eliminate duplicate rows (distinct operator)
Example:
SELECT DISTINCT DEPTNO
FROM EMP;
53
Exclusive: VLITS
DCL (DATA CONTROL LANGUAGE)
The data control basically refers to commands that allow system and
data privileges to be passed to various users.
These commands are normally available to database administrator. Let
us look into some data control language commands:
Create a new user:
CREATE USER < user name > IDENTIFIED BY < Password>
Example:
CREATE USER ABC12 IDENTIFIED BY W123
54
Exclusive: VLITS
DCL (DATA CONTROL LANGUAGE)
GRANT: It is used to provide database access permission to users. It is of
two types (1) system level permission (2) Object level permission.
Example :
GRANT CREATE SESSION TO ;
(This command provides system level permission on creating a
session)
GRANT SELECT ON EMP TO ABC12;
(Object level permission on table EMP)
GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO ABC12;
GRANT SELECT, UPDATE ON EMP TO ABC12, ABC13;
(Two users)
GRANT ALL ON EMP TO PUBLIC;
(All permission to all users, do not use it. It is very dangerous for
database)
55
Exclusive: VLITS
DCL (DATA CONTROL LANGUAGE)
REVOKE: It is used to cancel the permission granted.
Example :
REVOKE ALL ON EMP FROM ABC12;
(All permissions will be cancelled)
You can also revoke only some of the permissions.
56
Exclusive: VLITS
Transaction Control Language specifies commands for beginning and ending a transaction.
A transaction consists of a sequence of SQL statements that are applied in an atomic (all or
none) manner. A commit makes all the changes applied by the transaction permanent on the
database while a rollback undoes all the changed applied by the transaction.
The Commands In TCL
Commit
Save database changes
Rollback
Undo the changes that are not committed
TCL (Transaction Control Language)
57
Exclusive: VLITS
SQL Queries
58
Exclusive: VLITS
SELECT Statement
Special operators:
1) In opposite is not in
2) between opposite is not between
3) is null opposite is , is not null
4) Like opposite not like
59
Exclusive: VLITS
SELECT Statement
Example :
SELECT ENAME, SAL
FROM EMP
WHERE SAL BETWEEN 1000 AND 1500;
In (list): match any of a list of values
Example :
SELECT EMPNO, ENAME, SAL, MGR
FROM EMP
WHERE MGR IN (7902, 7566, 7788);
7902, 7566, and 7788 are Employee numbers
60
Exclusive: VLITS
SELECT Statement (is null, is not null)
Q) write a query to display the employees who are not getting
commission from emp table.
Ans: SQL> select * from emp where comm is null;
Q) write a query to display the employees who are getting commission
from emp table?
Ans: SQL> select * from emp where comm is not null;
Q)Find employee whose manage-id is not specified from emp table.
SELECT ENAME, MGR FROM EMP
WHERE MGR IS NULL;
61
Exclusive: VLITS
NVL()
Q) Write a query to display ename, sal, comm, sal+comm of the employee
SMITH from emp table.
Ans: SQL> select ename, sal, comm, sal+comm
from emp
where ename=‘SMITH’;
o/p: ename sal comm. Sal+comm
---------- ------- ----------- ----------------
SMITH 1100 null null
To overcome this problem oracle provided “NVL()” function.
NVL(): NVL() is a predefined function which is used to replace or
substitute user defined value in place of “null”.
62
Exclusive: VLITS
NVL()
Syntax:
NVL(exp1,exp2);
Here exp1,exp2 must belongs to same datatype. If exp1 is null then it
returns exp2. Otherwise it returns exp1.
Eg: 1) NVL(null,30) -> 30.
2) NVL(10,20) -> 10.
Solution: select ename, sal, comm, sal+NVL(comm, 0) from emp where
ename= ‘SMITH’;
63
Exclusive: VLITS
SELECT Statement
Like: match a character pattern
Like operator is used only with char and Varchar2 to match a pattern
% Denotes zero or many characters
_ Denotes one character
Combination of % and_can also be used
Example :
List the names of employees whose name starts with ‘s’
SELECT ENAME FROM EMP
WHERE ENAME LIKE ‘S%’;
(II) List the ename ending with ‘s’
SELECT ENAME FROM EMP
WHERE ENAME LIKE ‘%S’;
64
Exclusive: VLITS
SELECT Statement
Q) write a query to display the employees who are joining in the month
December from the emp table using like operator.
Ans: SQL> select * from emp where hiredate like ‘%D%’;
Q) write a query to display the employees who are joining in the year “81”
from emp table using like operator?
Ans: SQL> select * from emp where hiredate like ‘%81’;
65
Exclusive: VLITS
Order by clause
• It is used in the last portion of select statement
• By using this rows can be sorted
• By default it takes ascending order
• DESC: is used for sorting in descending order
• Sorting by column which is not in select list is possible
• Sorting by column Alias
Example 1:
SELECT EMPNO, ENAME, SAL*12 “ANNUAL”
FROM EMP
ORDER BY ANNUAL;
Example 2: Sorting by multiple columns; ascending order on department
number and descending order of salary in each department.
SELECT ENAME, DEPTNO, SAL
FROM EMP
ORDER BY DEPTNO, SAL DESC;
66
Exclusive: VLITS
Functions:
Functions are used to solve particular task and also functions must
return a value.
Oracle have two types of functions.
1. Predefined functions
2. User defined functions
1) Predefined functions: there are 4 types.
Number function
Character function
Date function
Group function(or) Aggregate function
67
Exclusive: VLITS
1) Number functions
These functions operate over “number” data.
Abs (): It is used to convert negative values into positive values.
E.g.: SQL> select abs (-50) from dual;
Mod(m,n): It will gives remainder after „m‟ divided by „n‟.
Eg: SQL> select mod(10,5) from dual;
Greatest :Greatest(exp1,exp2,…. expn), Least(exp1,exp2,…. expn):
Greatest returns maximum value among given expressions. Where as
Least returns minimum value among given expressions.
Eg: SQL> select greatest(3,5,8,9) from dual ;
SQL> select ename, sal, comm, greatest(sal,comm)from emp where comm
is not null;
SQL> select max(sal) from emp;
68
Exclusive: VLITS
2) CHARCTER FUNCTIONS:
Upper(): It is used to convert a string or column values into upper case.
E.g.: select upper (‘abc’) from dual;
ABC
Lower():
Eg: select lower(ename) from emp; Updating or modifying data within table:
SQL> update emp set ename=lower(ename);
Initcap(): It returns first letter is capital and all remaining letters are small.
Eg: SQL> select initcap(ename) from emp; Eg: SQL> select initcap(‘ab cd ef’)
from dual; Ab Cd Ef
Length(): It returns number datatype that is ., it returns total length of the
string including spaces.
Eg: select length(‘AB_CD’) from dual;
69
Exclusive: VLITS
3) DATE functions:
In oracle by default date format is DD-MON-YY. Oracle having following
date functions.
1. Sysdate
2. Add_months()
3. Last_day()
4. Next_day()
5. Months_between()
Sysdate: It returns current date of the system in the oracle date format
SQL> select sysdate from dual;
70
Exclusive: VLITS
DATE functions:
Add_months():
It is used to add or subtract number of months to the specified date based
on second parameter.
Syntax:
add_months(date, number); Number-> can be positive or negative.
Ex1: SQL> select add_months(sysdate,1)from dual;
Ex2: SQL> select add_months(sysdate,-1) from dual;
Last_day():
It returns last date of the given months based on the passed date. This
function always accepts one parameter.
Syntax:
last_day(date);
Eg: select next_day(sysdate,‟monday‟)from dual;
71
Exclusive: VLITS
DATE functions:
Months_between():
These function always returns “number” data type. i.e., it returns number of
months between two specified dates.
Syntax:
months_between(date1,date2)
Here date1 is more than date2 otherwise this function returns “negative”
sign.
Eg: SQL> select ename, round(months_between(sysdate,hiredate))from emp;
72
Exclusive: VLITS
SELECT Statement
DATE CONVERSION FUNCTIONS:
Oracle provided two date conversion function. They are:
1. To_char()
2. To_date()
to_char():
It is used to convert date time into character type i.e., it converts date
type into date string.
Eg: SQL> select to_char(sysdate,’dd/mm/yy’)from dual;
Note: Basically “to_char” character formats are case sensitive formats.
Eg: SQL> select to_char(sysdate,’DAY’)from dual;
MONDAY
73
Exclusive: VLITS
4) GROUP FUNCTION (OR) AGGREGATE FUNCTION:
Oracle having following group function
1. max()
2. min()
3. avg()
4. sum()
5. count(*)
6. count(column name)
In all databases group functions are operate over number of values
within a column and returns a single value
74
Exclusive: VLITS
Aggregate functions
Example : Find the total number of employees.
SELECT COUNT(*)
FROM EMP;
Example : Find the minimum, maximum and average salaries of
employees of department 20.
SELECT MIN(SAL), MAX(SAL), AVG(SAL)
FROM EMP
WHERE DEPTNO = 20 ;
75
Exclusive: VLITS
GROUP BY clauses
• It is used to group database tuples on the basis of certain common
attribute value such as employees of a department.
• WHERE clause still can be used, if needed.
Example : Find department number and Number of Employees working
in that department.
SELECT DEPTNO, COUNT(EMPNO)
FROM EMP
GROUP BY DEPTNO;
Note that while using group by and aggregate functions the only
attributes that can be put in select clause are the aggregated functions
and the attributes that have been used for grouping the information.
76
Exclusive: VLITS
GROUP BY clauses
Q) Write a query to display number of employees in each job from emp table
using group by?
Ans: SQL> select job, count(*) from emp group by job;
Q) Write a query to display deptno, minimum and maximum salary from emp
using group by?
Ans: SQL> select deptno, min(sal), max(sal) from emp group by deptno;
RULE:
Other than group function columns specified after select those all columns
must be used in after “group by”. Otherwise oracle server returns an error
“not a GROUP BY expression”.
Eg: SQL> select deptno, max(sal), ename from emp group by deptno,ename;
ERROR at line 1:
ORA-00979: not a GROUP BY expression
77
Exclusive: VLITS
SELECT Statement
HAVING clause
This clause is used for creating conditions on grouped information.
Example : Find department number and maximum salary of those
departments where maximum salary is more than Rs 20000/-.
SELECT DEPTNO, MAX(SAL)
FROM EMP
GROUP BY DEPTNO
HAVING MAX(SAL) > 20000;

More Related Content

Similar to PP DBMS - 1 (2).pptx

Data Mining And Data Warehousing Laboratory File Manual
Data Mining And Data Warehousing Laboratory File ManualData Mining And Data Warehousing Laboratory File Manual
Data Mining And Data Warehousing Laboratory File ManualNitin Bhasin
 
Introduction to DBMS and SQL Overview
Introduction to DBMS and SQL OverviewIntroduction to DBMS and SQL Overview
Introduction to DBMS and SQL OverviewPrabu U
 
Dbms Lec Uog 02
Dbms Lec Uog 02Dbms Lec Uog 02
Dbms Lec Uog 02smelltulip
 
Kskv kutch university DBMS unit 1 basic concepts, data,information,database,...
Kskv kutch university DBMS unit 1  basic concepts, data,information,database,...Kskv kutch university DBMS unit 1  basic concepts, data,information,database,...
Kskv kutch university DBMS unit 1 basic concepts, data,information,database,...Dipen Parmar
 
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvy
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvyppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvy
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvyvk5985399
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfSameerKhanPathan7
 
Chapter – 2 Data Models.pdf
Chapter – 2 Data Models.pdfChapter – 2 Data Models.pdf
Chapter – 2 Data Models.pdfTamiratDejene1
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-convertedgayaramesh
 
Database Management System, Lecture-1
Database Management System, Lecture-1Database Management System, Lecture-1
Database Management System, Lecture-1Sonia Mim
 
Database management system
Database management systemDatabase management system
Database management systemkhagendrabasnet4
 

Similar to PP DBMS - 1 (2).pptx (20)

Database Systems Concepts, 5th Ed
Database Systems Concepts, 5th EdDatabase Systems Concepts, 5th Ed
Database Systems Concepts, 5th Ed
 
RDBMS_Concept.ppt
RDBMS_Concept.pptRDBMS_Concept.ppt
RDBMS_Concept.ppt
 
Data Mining And Data Warehousing Laboratory File Manual
Data Mining And Data Warehousing Laboratory File ManualData Mining And Data Warehousing Laboratory File Manual
Data Mining And Data Warehousing Laboratory File Manual
 
Introduction to DBMS and SQL Overview
Introduction to DBMS and SQL OverviewIntroduction to DBMS and SQL Overview
Introduction to DBMS and SQL Overview
 
Dbms Lec Uog 02
Dbms Lec Uog 02Dbms Lec Uog 02
Dbms Lec Uog 02
 
Kskv kutch university DBMS unit 1 basic concepts, data,information,database,...
Kskv kutch university DBMS unit 1  basic concepts, data,information,database,...Kskv kutch university DBMS unit 1  basic concepts, data,information,database,...
Kskv kutch university DBMS unit 1 basic concepts, data,information,database,...
 
Unit01 dbms
Unit01 dbmsUnit01 dbms
Unit01 dbms
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvy
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvyppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvy
ppt_rdbms.pdfuvuguvuvugycycyctcucuvyvvuvuvy
 
DBMS Notes.pdf
DBMS Notes.pdfDBMS Notes.pdf
DBMS Notes.pdf
 
DBMS
DBMS DBMS
DBMS
 
Database Management System ppt
Database Management System pptDatabase Management System ppt
Database Management System ppt
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdf
 
Chapter – 2 Data Models.pdf
Chapter – 2 Data Models.pdfChapter – 2 Data Models.pdf
Chapter – 2 Data Models.pdf
 
WEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptxWEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptx
 
Week 1
Week 1Week 1
Week 1
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-converted
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Database Management System, Lecture-1
Database Management System, Lecture-1Database Management System, Lecture-1
Database Management System, Lecture-1
 
Database management system
Database management systemDatabase management system
Database management system
 

More from skilljiolms

VCE - UNIT-II.pptx
VCE - UNIT-II.pptxVCE - UNIT-II.pptx
VCE - UNIT-II.pptxskilljiolms
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxskilljiolms
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
VCE Unit 04vv.pptx
VCE Unit 04vv.pptxVCE Unit 04vv.pptx
VCE Unit 04vv.pptxskilljiolms
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptxskilljiolms
 
VCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxVCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxskilljiolms
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxskilljiolms
 
PP DBMS - 2 (1) (1).pptx
PP DBMS - 2 (1) (1).pptxPP DBMS - 2 (1) (1).pptx
PP DBMS - 2 (1) (1).pptxskilljiolms
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxskilljiolms
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxskilljiolms
 

More from skilljiolms (10)

VCE - UNIT-II.pptx
VCE - UNIT-II.pptxVCE - UNIT-II.pptx
VCE - UNIT-II.pptx
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
VCE Unit 04vv.pptx
VCE Unit 04vv.pptxVCE Unit 04vv.pptx
VCE Unit 04vv.pptx
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
VCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxVCE Unit 02 (1).pptx
VCE Unit 02 (1).pptx
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
 
PP DBMS - 2 (1) (1).pptx
PP DBMS - 2 (1) (1).pptxPP DBMS - 2 (1) (1).pptx
PP DBMS - 2 (1) (1).pptx
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptx
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptx
 

Recently uploaded

Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africaictsugar
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...lizamodels9
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfJos Voskuil
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...lizamodels9
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessAggregage
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
Marketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet CreationsMarketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet Creationsnakalysalcedo61
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCRsoniya singh
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 

Recently uploaded (20)

Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africa
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdf
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for Success
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
Marketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet CreationsMarketing Management Business Plan_My Sweet Creations
Marketing Management Business Plan_My Sweet Creations
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Mahipalpur 🔝 Delhi NCR
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 

PP DBMS - 1 (2).pptx

  • 1. www.cccdigital.io DBMS Agenda  Introduction to DBMS  Database Models  SQL
  • 2. 2 Exclusive: VLITS Data Data may be defined as a known Raw fact that can be recorded and that have no meaning. Example: 101 dinesh 2000 102 mahesh 3000 In above example, there no meaningful data such data is known as Raw facts
  • 3. 3 Exclusive: VLITS Information • It is a collection of meaningful data or processed data • Data and information are closely related and are often used interchangeably. • Information is processed, organized or summarized data. Example: EmpID Ename Salary 101 dinesh 2000 102 mahesh 3000
  • 4. 4 Exclusive: VLITS DATA STORE: It is a place where we can store data or information. 1) Books & Papers 2) Flat files 3) Database FLAT FILES: This is a traditional mechanism which is used to store data or information in individual unrelated files. These files are also called as Flat Files. Drawbacks of Flat files: 1) Data Retrieval 2) Data Redundancy 3) Data Integrity 4) Data Security 5) Data Indexing * In many cases, all records in a file are of the same record type, i.e., all the records are having an identical format.
  • 5. 5 Exclusive: VLITS Database • A database is defined as a collection of logically related data stored together that is designed to meet the information needs of an organization. • It is basically an electronic filing cabinet, which contain computerized data files. • It can contain one data file or large number of data files depending on organizational needs. • A database is organized in such a way that a computer program can quickly select desired pieces of data.
  • 6. 6 Exclusive: VLITS • A database management system (DBMS), is a generalized software system for manipulating databases. • DBMS is also a collection of programs that enables users to create and maintain database. Example DBS: ORACLE, FOXPRO, DB2, TERADATA, SQLSERVER, SYBASE, MYSQL, INGRESS, INFORMIX, SQLLITE…… etc; • It is basically a computerized record-keeping system, which it stores information and allows users to add, delete, retrieve and update that information on demand. • It provides for simultaneous use of a database by multiple users and tool for accessing and manipulating the data in the database. Database Management System
  • 7. 7 Exclusive: VLITS OPERATIONS PERFORMED ON DATABASE SYSTEMS  Inserting new data into existing data files  Adding new files to the database  Retrieving data from existing files  Changing data in existing files  Deleting data from existing files  Removing existing files from the database
  • 8. 8 Exclusive: VLITS Three – Level ANSI Database Architecture The ANSI proposes a Three Level Database Architecture, The three levels are 1.External Level 2.Conceptual Level 3.Internal Level (Physical Level) EXTERNAL LEVEL: This level describes end user view of the database. i.e., in this level some group of users access only part of the database. In this level only we are defining the view and those views given to the number of users. CONCEPTUAL LEVEL: It describes logical representation of the database. Conceptual level defines type of data storing in database and also defines what type of data does not store in database using constraints and also specifies the relationship between data items. INTERNAL LEVEL: Internal level describes how physically data is stored in database. This level is handled by database administrator only. In relational databases indexes, cluster are available in internal level.
  • 10. 10 Exclusive: VLITS A data model provides a way to describe the design of a database at physical, logical and view level. A data model is a mechanism that provides the abstraction for database application. How data is represented at the conceptual level defined by means of “Data Model”. DATA MODELS
  • 11. 11 Exclusive: VLITS Data models can be broadly classified into the following three categories: Record-based data models Hierarchical data model. Network data model. Relational data model. Object-based data models Entity-relationship. Semantic. Functional. Object-oriented. Physical data models Unifying model. Frame memory model. But, The most popular and most used data models are Relational Data Model Entity Relationship Model DATA MODELS
  • 12. 12 Exclusive: VLITS In 1970, E.F.Codd introduced Relational Data Model. In this data model we are storing data in 2- dimensional tables RELATIONAL DATA MODEL
  • 13. 13 Exclusive: VLITS Entity -Relationship Data Model An entity–relationship (E-R) model is a high-level conceptual data model, which has a diagrammatic representation of data for an enterprise of business establishment to produce a well-designed database. ER model can be easily converted into relational model by simply converting ER model into tables.
  • 14. 14 Exclusive: VLITS Entity An entity is an object of concern used to represent the things in the real world, for example: car, table, book, etc. An entity need not be a physical entity, it can also represent a concept in real world. For example: project, loan, etc rectangles representing entity Entity Set or Entity Type: A collection of a similar kind of entities is called an Entity Set or entity type
  • 15. 15 Exclusive: VLITS Attributes An attribute is a property used to describe the specific feature of the entity. So to describe an entity entirely, a set of attributes is used. ellipses representing attributes. Entity -Relationship Data Model
  • 16. 16 Exclusive: VLITS Relationships A relationship can be defined as: • a connection or set of associations, or • a rule for communication among entities diamonds representing relationship sets Entity -Relationship Data Model
  • 17. 17 Exclusive: VLITS Cardinality specifies the number of instances of an entity associated with another entity participating in a relationship. Based on the cardinality binary relationship can be further classified into the following categories: One-to-one: An entity in A is associated with at most one entity in B, and an entity in B is associated with at most one entity in A. Example: Relationship between college and principal Relationship Cardinality
  • 18. 18 Exclusive: VLITS One-to-many: An entity in A is associated with any number of entities in B. An entity in B is associated with at the most one entity in A. Example: Relationship between department and faculty. Relationship Cardinality
  • 19. 19 Exclusive: VLITS Many-to-one: An entity in A is associated with at most one entity in B. An entity in B is associated with any number in A. Example: Relationship between course and instructor. An instructor can teach various courses but a course can be taught only by one instructor. Relationship Cardinality
  • 20. 20 Exclusive: VLITS Many-to-many: Entities in A and B are associated with any number of entities from each other. Example: Taught by Relationship between course and faculty. One faculty member can be assigned to teach many courses and one course may be taught by many faculty members. Relationship Cardinality
  • 21. 21 Exclusive: VLITS E-R Diagram for Student, Course and Teacher Entities
  • 23. 23 Exclusive: VLITS Structured Query Language (SQL) is used to manage data in all relational databases like DB2,Oracle, SQL Server etc. Majorly We can divide SQL into 4 Parts DDL (Data Definition Language) DML (Data Manipulation Language) DCL (Data Control Language) TCL (Transaction Control Language)
  • 25. 25 Exclusive: VLITS SQL Character Data Types: SQL supports two character data types for storing printable and displayable characters. They are used for storing information like name, address, description etc. CHAR(n) VARCHAR2(n) Useful for Storing characters having pre-determined length Storing characters whose length vary a lot Storage size Size for n characters size for actual no. of characters + fixed size to store length Storage Trailing spaces are applied if data to be stored has Trailing spaces are not applied. smaller length than n. Max size 2000 bytes 4000 bytes Example A CHAR(10) field will store "Hello" as 10 bytes A VARCHAR2(10) field will store "Hello" by appending 5 trailing spaces. as 7 bytes (assuming 2 bytes to store length). Alte Name CHARACTER(n) CHARACTER VARYING(n) SQL Data Types
  • 26. 26 Exclusive: VLITS SQL supports SMALLINT, INTEGER and INT data types that are used for storing whole numbers. Unlike other databases Oracle does not define different size limits for them. They are all treated internally to have 38 digits of precision. SQL Non-Integral Data Types: Nonintegral data types have an integer part and a fractional part. Either NUMERIC, DECIMAL or NUMBER data types can be used to store nonintegral numbers. Ex: Number (3,1) In the Above example first parameter is total number digits in the given value Second parameter is number of digits after the Decimal point Number (3)  555 Number (3,2)  5.55 Number (3,1)  55.5 Number (3,3)  0.555 SQL Integral Data Types:
  • 27. 27 Exclusive: VLITS SQL Date & Time Data Types: Date Data Type • It is used to store date and time information • The dates can be specified as literals using Gregorian Calendar • The default format in ORACLE is DD-MM-YY
  • 28. 28 Exclusive: VLITS DDL Creating A Table: CREATE TABLE Command Syntax: CREATE TABLE <table name>( Column_name1 data type (column width) [constraints], Column_name2 data type (column width) [constraints], Column_name3 data type (column width) [constraints], ……………………………………….. ); Guidelines for creation of table: • Table name should start with an alphabet. • In table name, blank spaces and single quotes are not allowed. • Reserve words of that DBMS cannot be used as table name. • Proper data types and size should be specified. • Unique column name should be specified.
  • 29. 29 Exclusive: VLITS DDL Creating A Table: Example: CREATE TABLE Student ( StudentId NUMBER, FName VARCHAR2(15), LName VARCHAR2(20), Gender CHAR(1), DOB DATE);
  • 30. 30 Exclusive: VLITS SQL constraints are used to specify rules for data in a table. Various constraints that can be created on database tables are:  NOT NULL  PRIMARY KEY  CHECK  UNIQUE  FOREIGN KEY  DEFAULT Constraints:
  • 31. 31 Exclusive: VLITS NOT NULL Constraint prevents a column from accepting NULL values. NOT NULL can only be applied as a column level constraint. Constraint name is optional and it can be specified by using CONSTRAINT keyword. CREATE TABLE Student ( StudentId NUMBER CONSTRAINT Stud_SId_nn NOT NULL, FName VARCHAR2(10) NOT NULL, LName VARCHAR2(10));
  • 32. 32 Exclusive: VLITS A column can be given the default value by using DEFAULT option. The data type of column and default expression must be the same. DEFAULT option can be provided for nullable as well as NOT NULL attributes. Oracle database does not consider DEFAULT as a constraint. CREATE TABLE Student ( StudentId NUMBER, FName VARCHAR2(10), DOJ DATE DEFAULT SYSDATE); In The Above Table Definitions Whenever Input Is Not Provided Into The DOJ Field, The Default Value SYSDATE Will Be Taken
  • 33. 33 Exclusive: VLITS PRIMARY KEY constraint on a column ensures that the column cannot contain NULL and duplicate values. We can have only one PRIMARY KEY in a table. CREATE TABLE Student ( StudentId NUMBER CONSTRAINT stud_sid_pk PRIMARY KEY, FName VARCHAR2(10), ContactNo NUMBER(10));
  • 34. 34 Exclusive: VLITS CHECK constraint is used to limit the values that can be specified for a column. CREATE TABLE Student ( StudentId NUMBER, FName VARCHAR2(10), Gender CHAR (1) CONSTRAINT Stud_gender_ck1 CHECK (Gender IN('M', 'F')));
  • 35. 35 Exclusive: VLITS UNIQUE constraint on a column ensures that two rows in a table cannot have same value in that column. Unlike Primary Key, UNIQUE constraint allows NULL values. A table can have many UNIQUE constraints. CREATE TABLE Student ( StudentId NUMBER, FName VARCHAR2(10), ContactNo NUMBER(10) CONSTRAINT Stud_cno_uk UNIQUE);
  • 36. 36 Exclusive: VLITS Marks Table Without Connecting To Student CREATE TABLE Marks( CourseId NUMBER, StudentId NUMBER, MarksScored DECIMAL(5,2)); Marks Table With Connecting To Student Through Foreign Key CREATE TABLE Marks( CourseId NUMBER, StudentId NUMBER CONSTRAINT marks_sid_fk REFERENCES Student(StudentId), MarksScored DECIMAL(5,2));
  • 37. 37 Exclusive: VLITS Data Definition Language is used to specify the structure i.e. schema of a relational database. DDL provides commands for creation, modification and deletion of various database objects like tables, views, stored procedures, indexes, constraints etc. The output of DDL is placed in data dictionary which contains metadata i.e. data about data. The Commands IN DDL Create: Creates a new database objects like table,view,sequences,indexes Alter: Modifies the existing database object Drop: Delete exiting database object Truncate: Deletes all rows from the database object Rename :(oracle 9i) Rename the database object DDL (Data Definition Language)
  • 38. 38 Exclusive: VLITS ALTER TABLE Command: This command is used for modification of existing structure of the table in the following situation: • When a new column is to be added to the table structure. • When the existing column definition has to be changed, i.e., changing the width of the data type or the data type itself. • When integrity constraints have to be included or dropped. • When a constraint has to be enabled or disabled. Syntax ALTER TABLE <table name> ADD (<column name> <data type>…); ALTER TABLE <table name> MODIFY (<column name> <data type>…); ALTER TABLE <table name> ADD CONSTRAINT <constraint name> < constraint type>(field name); ALTER TABLE <table name> DROP<constraint name>; ALTER TABLE <table name> ENABLE/DISABLE <constraint name>;
  • 39. 39 Exclusive: VLITS ALTERING TABLE Example: Altering Table To Add A New Column ALTER TABLE Student ADD Address varchar2(20) ALTER TABLE Student ADD (Course VARCHAR2 (20), Marks NUMBER (10)); // Adding Two Columns Altering Table To Modify The Existing Column ALTER TABLE Student MODIFY Address varchar2 (50) Altering Table To Rename A Column Name Syntax: ALTER TABLE <table name> RENAME COLUMN <old column name> TO <new column name>; Example: ALTER TABLE Student RENAME COLUMN Address To ResidentialAddress;
  • 40. 40 Exclusive: VLITS Altering Table To Drop An Existing Column ALTER TABLE Student Drop (ResidentialAddress) ALTER TABLE Student DROP (GNDR, MobNo); // Dropping Two Columns Altering Table To Add A Constraint ALTER TABLE Student Add Constraint Studid_PK PRIMARY KEY (StudentID) Altering Table To Drop An Existing Constraint ALTER TABLE Student Drop constraint Studid_PK ALTERING TABLE
  • 41. 41 Exclusive: VLITS DROP TABLE Student; Get it back from recycle bin. Syntax: flashback table tablename to before drop; To drop permanently: Syntax: drop table tablename purge; Example: (dropping a table oracle 10g Enterprise Edition) SQL> drop table first; Table dropped. Get it back the table: SQL> flashback table first to before drop; DROP
  • 42. 42 Exclusive: VLITS Truncate: Oracle 7.0 introduced truncate command , whenever we are using “truncate” command total data permanently deleted from table. Syntax: truncate table tablename; SQL> truncate table first; Rename: It is used to rename a table and renaming a column also. Renaming a Table: Syntax: rename old_tablename to new_tablename; Example: rename first to last; Renaming a Column: (oracle 9i) Syntax: alter table tablevname rename column old_column_name to new_column_name; Example: SQL> alter table emp rename column empno to sno;
  • 43. 43 Exclusive: VLITS Creating a new table from another table: Syntax: create table newtablename as select * from existingtablename; Example: SQL> create table test as select * from emp; Note: In all database systems whenever we are copying a table from another table constraints are never copied. (Primary table, Foreign key,…..); Creating a new table from existing table without copying data: Syntax: create table newtablename as select * from existingtablename where falsecondition; Example: SQL> create table test1 as select * from emp where 1=2;
  • 44. 44 Exclusive: VLITS QUESTION You need to modify the STUDENTS table to add a primary key on the STUDENT_ID column. The table is currently empty. Which statement accomplishes this task? A. ALTER TABLE students ADD PRIMARY KEY student_id; B. ALTER TABLE students ADD CONSTRAINT PRIMARY KEY (student_id); C. ALTER TABLE students ADD CONSTRAINT stud_id_pk PRIMARY KEY student_id; D. ALTER TABLE students ADD CONSTRAINT stud_id_pk PRIMARY KEY (student_id); E. ALTER TABLE students MODIFY CONSTRAINT stud_id_pk PRIMARY KEY (student_id);
  • 45. 45 Exclusive: VLITS Data Manipulation Language enables users to access or manipulate data in a relational database. DML provides commands for retrieval, creation, deletion and modification of information in a database. The Commands In DML Insert Creates new rows in the table Update Modify data in the tables Delete Delete the data from the tables Select Retrieves the data from the tables merge(oracle 9i) Merge is an DML command which is used to transfer data from “source table” into “target table” when table structure are same DML (Data Manipulation Language)
  • 46. 46 Exclusive: VLITS Inserting Data into Tables: - once a table is created the most natural thing to do is load this table with data to be manipulated later. Syntax: insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>); Example: SQL> create table first(sno number(10), name varchar(20)); Inserting data into table: SQL> insert into first values(1, ‘abc’); SQL> insert into first values(2, ‘sachin’); DML commands
  • 47. 47 Exclusive: VLITS Delete operations. a) remove all rows Syntax: delete from <tablename>; b) removal of a specified row/s Syntax: delete from <tablename> where <condition>;
  • 48. 48 Exclusive: VLITS Updating the contents of a table a) updating all rows Syntax: UPDATE <TABLENAME> SET <COL>=<EXP>,<COL>=<EXP>; b) updating selected records. Syntax: UPDATE<TABLENAME> SET <COL>=<EXP>,<COL>=<EXP> WHERE <CONDITION>;
  • 49. 49 Exclusive: VLITS SELECT Statement This statement is used for retrieving information from the databases. It can be coupled with many clauses. Query: It is an operation that retrieves data from one or more tables or views Operators Used in “Select” statement: 1. Arithmetic operator(+,-,*,/) 2. Relational operator(=,<,<=,>,>=,[<> or!=]not equal). 3. Logical operator (AND,OR,NOT) Operator Precedence The basic operators used in SQL are * / + - Operators of the same priority are evaluated From Left to right Parentheses are used to force prioritized evaluation.
  • 50. 50 Exclusive: VLITS SELECT Statement This statement is used for retrieving information from the databases. It can be coupled with many clauses. Let us discuss these clauses in more detail: Using Arithmetic operator Example: SELECT ENAME, SAL, SAL+300 FROM EMP; Operator Precedence The basic operators used in SQL are * / + - Operators of the same priority are evaluated From Left to right Parentheses are used to force prioritized evaluation. Example: SELECT ENAME, SAL, 12*SAL+100 FROM EMP;
  • 51. 51 Exclusive: VLITS SELECT Statement Using Column aliases Example: To print column names as NAME and ANNUAL SALARY SELECT ENAME “NAME”, SAL*12 “ANNUAL SALARY” FROM EMP; Concatenation operator Example: Printing name and job as one string as column name employees: SELECT ENAME||JOB “EMPLOYEES” FROM EMP;
  • 52. 52 Exclusive: VLITS SELECT Statement Using Literal Character String Example : To print <name> IS A <job> as one string with column name employee SELECT ENAME || ‘ IS A ’ || JOB AS “EMPLOYEE” FROM EMP; To eliminate duplicate rows (distinct operator) Example: SELECT DISTINCT DEPTNO FROM EMP;
  • 53. 53 Exclusive: VLITS DCL (DATA CONTROL LANGUAGE) The data control basically refers to commands that allow system and data privileges to be passed to various users. These commands are normally available to database administrator. Let us look into some data control language commands: Create a new user: CREATE USER < user name > IDENTIFIED BY < Password> Example: CREATE USER ABC12 IDENTIFIED BY W123
  • 54. 54 Exclusive: VLITS DCL (DATA CONTROL LANGUAGE) GRANT: It is used to provide database access permission to users. It is of two types (1) system level permission (2) Object level permission. Example : GRANT CREATE SESSION TO ; (This command provides system level permission on creating a session) GRANT SELECT ON EMP TO ABC12; (Object level permission on table EMP) GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO ABC12; GRANT SELECT, UPDATE ON EMP TO ABC12, ABC13; (Two users) GRANT ALL ON EMP TO PUBLIC; (All permission to all users, do not use it. It is very dangerous for database)
  • 55. 55 Exclusive: VLITS DCL (DATA CONTROL LANGUAGE) REVOKE: It is used to cancel the permission granted. Example : REVOKE ALL ON EMP FROM ABC12; (All permissions will be cancelled) You can also revoke only some of the permissions.
  • 56. 56 Exclusive: VLITS Transaction Control Language specifies commands for beginning and ending a transaction. A transaction consists of a sequence of SQL statements that are applied in an atomic (all or none) manner. A commit makes all the changes applied by the transaction permanent on the database while a rollback undoes all the changed applied by the transaction. The Commands In TCL Commit Save database changes Rollback Undo the changes that are not committed TCL (Transaction Control Language)
  • 58. 58 Exclusive: VLITS SELECT Statement Special operators: 1) In opposite is not in 2) between opposite is not between 3) is null opposite is , is not null 4) Like opposite not like
  • 59. 59 Exclusive: VLITS SELECT Statement Example : SELECT ENAME, SAL FROM EMP WHERE SAL BETWEEN 1000 AND 1500; In (list): match any of a list of values Example : SELECT EMPNO, ENAME, SAL, MGR FROM EMP WHERE MGR IN (7902, 7566, 7788); 7902, 7566, and 7788 are Employee numbers
  • 60. 60 Exclusive: VLITS SELECT Statement (is null, is not null) Q) write a query to display the employees who are not getting commission from emp table. Ans: SQL> select * from emp where comm is null; Q) write a query to display the employees who are getting commission from emp table? Ans: SQL> select * from emp where comm is not null; Q)Find employee whose manage-id is not specified from emp table. SELECT ENAME, MGR FROM EMP WHERE MGR IS NULL;
  • 61. 61 Exclusive: VLITS NVL() Q) Write a query to display ename, sal, comm, sal+comm of the employee SMITH from emp table. Ans: SQL> select ename, sal, comm, sal+comm from emp where ename=‘SMITH’; o/p: ename sal comm. Sal+comm ---------- ------- ----------- ---------------- SMITH 1100 null null To overcome this problem oracle provided “NVL()” function. NVL(): NVL() is a predefined function which is used to replace or substitute user defined value in place of “null”.
  • 62. 62 Exclusive: VLITS NVL() Syntax: NVL(exp1,exp2); Here exp1,exp2 must belongs to same datatype. If exp1 is null then it returns exp2. Otherwise it returns exp1. Eg: 1) NVL(null,30) -> 30. 2) NVL(10,20) -> 10. Solution: select ename, sal, comm, sal+NVL(comm, 0) from emp where ename= ‘SMITH’;
  • 63. 63 Exclusive: VLITS SELECT Statement Like: match a character pattern Like operator is used only with char and Varchar2 to match a pattern % Denotes zero or many characters _ Denotes one character Combination of % and_can also be used Example : List the names of employees whose name starts with ‘s’ SELECT ENAME FROM EMP WHERE ENAME LIKE ‘S%’; (II) List the ename ending with ‘s’ SELECT ENAME FROM EMP WHERE ENAME LIKE ‘%S’;
  • 64. 64 Exclusive: VLITS SELECT Statement Q) write a query to display the employees who are joining in the month December from the emp table using like operator. Ans: SQL> select * from emp where hiredate like ‘%D%’; Q) write a query to display the employees who are joining in the year “81” from emp table using like operator? Ans: SQL> select * from emp where hiredate like ‘%81’;
  • 65. 65 Exclusive: VLITS Order by clause • It is used in the last portion of select statement • By using this rows can be sorted • By default it takes ascending order • DESC: is used for sorting in descending order • Sorting by column which is not in select list is possible • Sorting by column Alias Example 1: SELECT EMPNO, ENAME, SAL*12 “ANNUAL” FROM EMP ORDER BY ANNUAL; Example 2: Sorting by multiple columns; ascending order on department number and descending order of salary in each department. SELECT ENAME, DEPTNO, SAL FROM EMP ORDER BY DEPTNO, SAL DESC;
  • 66. 66 Exclusive: VLITS Functions: Functions are used to solve particular task and also functions must return a value. Oracle have two types of functions. 1. Predefined functions 2. User defined functions 1) Predefined functions: there are 4 types. Number function Character function Date function Group function(or) Aggregate function
  • 67. 67 Exclusive: VLITS 1) Number functions These functions operate over “number” data. Abs (): It is used to convert negative values into positive values. E.g.: SQL> select abs (-50) from dual; Mod(m,n): It will gives remainder after „m‟ divided by „n‟. Eg: SQL> select mod(10,5) from dual; Greatest :Greatest(exp1,exp2,…. expn), Least(exp1,exp2,…. expn): Greatest returns maximum value among given expressions. Where as Least returns minimum value among given expressions. Eg: SQL> select greatest(3,5,8,9) from dual ; SQL> select ename, sal, comm, greatest(sal,comm)from emp where comm is not null; SQL> select max(sal) from emp;
  • 68. 68 Exclusive: VLITS 2) CHARCTER FUNCTIONS: Upper(): It is used to convert a string or column values into upper case. E.g.: select upper (‘abc’) from dual; ABC Lower(): Eg: select lower(ename) from emp; Updating or modifying data within table: SQL> update emp set ename=lower(ename); Initcap(): It returns first letter is capital and all remaining letters are small. Eg: SQL> select initcap(ename) from emp; Eg: SQL> select initcap(‘ab cd ef’) from dual; Ab Cd Ef Length(): It returns number datatype that is ., it returns total length of the string including spaces. Eg: select length(‘AB_CD’) from dual;
  • 69. 69 Exclusive: VLITS 3) DATE functions: In oracle by default date format is DD-MON-YY. Oracle having following date functions. 1. Sysdate 2. Add_months() 3. Last_day() 4. Next_day() 5. Months_between() Sysdate: It returns current date of the system in the oracle date format SQL> select sysdate from dual;
  • 70. 70 Exclusive: VLITS DATE functions: Add_months(): It is used to add or subtract number of months to the specified date based on second parameter. Syntax: add_months(date, number); Number-> can be positive or negative. Ex1: SQL> select add_months(sysdate,1)from dual; Ex2: SQL> select add_months(sysdate,-1) from dual; Last_day(): It returns last date of the given months based on the passed date. This function always accepts one parameter. Syntax: last_day(date); Eg: select next_day(sysdate,‟monday‟)from dual;
  • 71. 71 Exclusive: VLITS DATE functions: Months_between(): These function always returns “number” data type. i.e., it returns number of months between two specified dates. Syntax: months_between(date1,date2) Here date1 is more than date2 otherwise this function returns “negative” sign. Eg: SQL> select ename, round(months_between(sysdate,hiredate))from emp;
  • 72. 72 Exclusive: VLITS SELECT Statement DATE CONVERSION FUNCTIONS: Oracle provided two date conversion function. They are: 1. To_char() 2. To_date() to_char(): It is used to convert date time into character type i.e., it converts date type into date string. Eg: SQL> select to_char(sysdate,’dd/mm/yy’)from dual; Note: Basically “to_char” character formats are case sensitive formats. Eg: SQL> select to_char(sysdate,’DAY’)from dual; MONDAY
  • 73. 73 Exclusive: VLITS 4) GROUP FUNCTION (OR) AGGREGATE FUNCTION: Oracle having following group function 1. max() 2. min() 3. avg() 4. sum() 5. count(*) 6. count(column name) In all databases group functions are operate over number of values within a column and returns a single value
  • 74. 74 Exclusive: VLITS Aggregate functions Example : Find the total number of employees. SELECT COUNT(*) FROM EMP; Example : Find the minimum, maximum and average salaries of employees of department 20. SELECT MIN(SAL), MAX(SAL), AVG(SAL) FROM EMP WHERE DEPTNO = 20 ;
  • 75. 75 Exclusive: VLITS GROUP BY clauses • It is used to group database tuples on the basis of certain common attribute value such as employees of a department. • WHERE clause still can be used, if needed. Example : Find department number and Number of Employees working in that department. SELECT DEPTNO, COUNT(EMPNO) FROM EMP GROUP BY DEPTNO; Note that while using group by and aggregate functions the only attributes that can be put in select clause are the aggregated functions and the attributes that have been used for grouping the information.
  • 76. 76 Exclusive: VLITS GROUP BY clauses Q) Write a query to display number of employees in each job from emp table using group by? Ans: SQL> select job, count(*) from emp group by job; Q) Write a query to display deptno, minimum and maximum salary from emp using group by? Ans: SQL> select deptno, min(sal), max(sal) from emp group by deptno; RULE: Other than group function columns specified after select those all columns must be used in after “group by”. Otherwise oracle server returns an error “not a GROUP BY expression”. Eg: SQL> select deptno, max(sal), ename from emp group by deptno,ename; ERROR at line 1: ORA-00979: not a GROUP BY expression
  • 77. 77 Exclusive: VLITS SELECT Statement HAVING clause This clause is used for creating conditions on grouped information. Example : Find department number and maximum salary of those departments where maximum salary is more than Rs 20000/-. SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO HAVING MAX(SAL) > 20000;