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

Relational Database Management System (RDBMS) : Payroll

Hired_Date DATE; • format can be changed using TO_CHAR function • date arithmetic operations like addition, subtraction are allowed • date functions like ADD_MONTHS, NEXT_DAY etc are available • SYSDATE returns current date and time • TRUNC(SYSDATE) returns current date without time

Uploaded by

aashish_918
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views

Relational Database Management System (RDBMS) : Payroll

Hired_Date DATE; • format can be changed using TO_CHAR function • date arithmetic operations like addition, subtraction are allowed • date functions like ADD_MONTHS, NEXT_DAY etc are available • SYSDATE returns current date and time • TRUNC(SYSDATE) returns current date without time

Uploaded by

aashish_918
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 114

Relational Database Management System (RDBMS)

• Able to reliably manage large data into multi-user


environment.
• Relates data in different files through the key field.

Payroll

Employee Number
Project Number

Emp_info Project
ORACLE TOOLS

1. SQL * PLUS: for writing command line SQL queries to work with
database objects.
2. PL/ SQL: oracle’s extension, It is a procedural language
3. Query: creating SQL query using graphical environment. It allow to
write the DDL, DML, and DCL statements.
4. Developer : used for developing database applications
- Form Builder: It is useful to create graphical forms and menu.
- Report Builder: To create reports in different formats, save the
reports, print the data.
- Developer – Graphics Builder – it is used to create the graphical
charts like, Bar Charts, Pie Charts etc. based on data
ORACLE TOOLS

5. Enterprise Manager : – a tool for managing uses following tools


- Storage Manager : To create and manage “ table space”
- Instance Manager: To start, stop pr tune database.
- Security Manager: To create and manage users and role

6. Oracle Web Application Server: A tool for creating a web site that
allows user to access oracle database through web pages
ORACLE DBA

• installing the oracle database, managing the day-to day needs of the
complex database, and running the system at a peal performance
• performs software maintenance, resource management, data
administration, database tuning, and troubleshooting, data security and
backup and recovery.
ORACLE DBA
Basic duties or Role or Responsibilities of the DBA:
1. Installing of new hardware and software
2. Configuration of hardware and software with the system
administration
3. Security administration
4. Performance tuning & monitoring:
5. Backup and Recovery
6. Routine schedule maintenance
7. Troubleshooting
8. Failure Recovery
9. Crate,Alter and remove database, data users and Roles
10. Grant and restrict access rights
SQL * PLUS

• ad-hoc user interface tool for the oracle RDBMS


• run SQL commands and PL / SQL programs
• most common ways to communicate interactively with the oracle
database
• can edit or save the SQL statements that are in the SQL buffer
SQL * PLUS

Feature of SQL * PLUS

     Accept adhoc entry of statements at the prompt


     Accepts SQL statement from file.
      Provides a line editor for modifying SQL Queries.
    Provides environment, editor, format, execution,
interaction, and file commands.

     Formats query results and displays reports on


the screen.
     Controls environmental settings
     Accesses local and remote database
TABLE SPACE

A database is divided into logical storage units called


table spaces
distribute the I/o load and improve performance.

Disk3
System Accounting Purchasing
Table space Table space Table space Acct.
datafile3
Disk1 Disk2 Disk3
Pur.
System Acct. Acct. datafile1
datafile1 datafile1 datafile2
SCHEMA OBJECTS
• A schema is a collection of objects

1. TABLE : which consists of a table name and rows and column of data

2. CLUSTER : is set of tables physically stored together as one table


that shares a common column.
3. INDEX : to increase the performance of data retrieval.

4. VIEW : a custom-tailored presentation of the data in one or more


tables. rather they derive their data from the table on which they are
based
5. STORED PROCEDURE: It is a predefined SQL query that is stored in
the data dictionary .
6. DATABASE TRIGGER: is a procedure that is run automatically when
an event occurs
7. SEQUENCE : used to automatically generate a unique sequence of
number in cache .
Structured Query Language (SQL)

• SQL is a very simple, yet powerful, database access language


• SQL is non-procedural language
• SQL statements: is a specific instance of a valid SQL command.
consist of SQL reserved words, which have special meaning in
SQL Emp_Info
Emp Id Name Join Dt

1 G. Gore 01-JUN-07

Select Name from Emp_info;


Insert into Emp_info
2 K. Kale 12-Aug-05
Types of SQL statements

• SELECT
• INSERT , UPDATE, DELETE,
• CREATE, ALTER, DROP, RENAME TRUNCATE

• COMMIT ROLLBACK, SAVEPOINT

• GRANT, REVOKE
Types of SQL statement

• Data Definition Language statement (DDL)


• Data Manipulation Language statement (DML)
• Transaction Control Statement

• Session Control Statements

• System Control Statements


Data Definition Language (DDL)

define or changes the structure of database


• Define and create a new table or schema objects
• Remove a table that’s no longer needed

• Change the definition of an existing table

• Define virtual table (or view) of data


• Establish security controls for a database
• Build an index to make table access faster
• Control the physical structure of data by the DBMS
CREATE, ALTER DROP RENAME, GRANT, REVOKE
Data Manipulation Language (DML)

DML statements or query , manipulate data in existing schema


objects
• Remove rows from tables or views (DELETE)
        See the executing plan for a SQL statement (EXPLAINATION)

• Add new rows of data into a table or view (INSERT)

• Lock a table or views, temporarily limiting other users access to


it (LOCK TABLE).

• Retrieve data from one or more table and views (SELECT).


• Change column values in existing rows of table or view
(UPDATE).

most frequently used SQL statements i.e. SELECT, INSERT,


UPDATE, DELETE, COMMIT & ROLLBACK
Transaction Control Statements

statements manage changes made by DML statements


• Make a transaction changes permanent (COMMIT)
• Undo the changes in a transaction, either science the transaction
started or since a save point (ROLLBACK).

• Set a point to which you can ROLLBACK (SAVEPOINT)

• COMMIT, ROLLBACK, SAVEPOINT groups DML statement into


transaction
Session Control Statements

manages the properties of a particular user’s session


• Alter the current session by performing a specialized function,
such as enabling and disabling the sql trace facility (ALTER
SESSION).

• Enabling and disable roles (groups of privileges) for current


session (SET ROLE)
Oracle Data Types

A datatype is a set of data having pre defined characteristics

• The datatype specifies the type of data that will be stored in that
attribute . ,The wrong kind of data prevented from being stored in
the attribute
• help optimize storage space
VARCHAR2 Data Types

• is a character data type to store variable length string or


alphanumeric characters

• A maximum size must be specified for this type

• and minimum size is 1. the maximum allowable size is 4000


characters in oracle 8
• The size is specified within parentheses
• for example Name VARCHAR2(15), Name is G. Gore I.e. (7 char)

G . G O R E
CHAR Data Types

• type is a character data type to store fixed length character data

• minimum size is 1. the maximum allowable size is 2000


characters

• If the value smaller than the specified size is entered, trailing


spaces are added to make it’s length equal to specified length
• The size is specified within parentheses
• for example Name CHAR(15), Name is G. Gore I.e. (7 char)

G . G O R E
NUMBER Data Types

• is used to store negative, positive, integer,fixed-decimal and


floating point numbers
• its “Precision “ and “ Scale” can be specified

• Precision – is the total number of digits in the number, both to the


left and right of the decimal point.

• The scale is the total number of digits to the right side of the
decimal point
• The precision can range from 1 to 38. the scale can range from
---- 84 to 127

• 12000.50 Scale
12000.50

Precision
NUMBER Data Types

• Integer : Whole number without any decimal point


e.g employee_id NUMBER(3) : 111,222, 999

• Fixed-Point decimal : has specific number of digits to the right of


the decimal point. NUMBER(5,2) e.g. amount 125.50, 999.99

• Floating point decimal ; has variable number of decimal digits.


The decimal point may appear after any number of digits, and it
may not appear at all.
e.g. TAXRATE NUMBER;
Different precision and scale table

Actual data Specified as Stored as

7456123.89 Number 7456123.89

7456123.89 Number(9) 7456124

7456123.89 Number(9,2) 7456123.89


DATE Data Types

• Stores date and time values in a special format

• day,month,century,hour,minute,second are stored


• no need to specify size
• default format of date is DD-MON-YY

• default format of time is HH:MM:SS A.M.


• e.g JOIN_DT DATE
LONG Data Types

• Used to store variable length character data upto 2 GB

• Only one LONG data type is allowed in one table


• used to store memo, invoice etc
• no need to specify the size
• e.g Prd_Desc Long;
LONG Data Types restrictions

• Only one LONG column allowed per table

• LONG column cannot be indexed


• LONG column cannot be appear in integrity constraints
• LONG column cannot be appeared for WHERE, GROUP BY,
ORDER BY, CONNECTED BY clause.

• cannot be referenced by SQL functions


• cannot be used in sub-query
• cannot be used in expression
RAW /LONG RAW Data Types

• Variable length binary storage

• useful to store sound and graphics files


• e.g Stud_Photo LONG RAW;
Guidelines for designing the table

• Use descriptive name for tables,columns, indexes, and clusters.

• Be consistent in abbreviations and in the use of singular and


plural forms of table names and columns

• Select the proper data type for each columns


• Define columns that allows NULL values at the last, to conserve
storage space
Table Creation Rules

• Table names and column names must begin with a letter and can
be 1 to 30 character long

• Name must contain only the characters A-Z, a-z, 0-9,


_(underscore), $, and #

• Name must not be an oracle server reserved word


• Names must not duplicate

• Table name,column name is not case sensitive


Syntax for Create Table

CREATE TABLE table_name ( Column1 datatype, column2 datatype);

e.g.
CREATE TABLE EMP_INFO_00 (
EMP_ID NUMBER,
NAME varchar2(25),
ADDRESS VARCHAR2(50),
BIRTH_DATE DATE,
GENDER CHAR(1),
SALARY NUMBER(9,2) );
SQL and SQL* PLUS
SQL SQL * PLUS

A Language An environment

ANSI Standards Oracle Proprietary

Key words cannot be Keywords can be


abbreviated abbreviated

Last statement is stored Commands are not stored


Insertion of data (INSERT INTO)

• Single row insert statement

• A multi-row insert statement : extract rows of data from another


database
• Bulk load utility : add data from the file which is outside of the
database
POINTS TO BE REMEMBER

• Character data should be enclosed with quotes.

• Column values of DATE type of column is provided with single


quotes
• NULL values are given as NULL, without any quotes

• Numeric values not enclosed within quotas (‘ ‘)

• enter a character value that contains a single quote


Single row insertion

• INSERT INTO table_name (column1,column2,…)


VALUES (value1,value2,….);

• e.g. INSERT INTO DEPT (dept_name,dept_no)


VALUES (‘Marketing’,1);

• e.g. INSERT INTO EMP_00 (emp_name, emp_id, d_o_b, Salary,


gender)
VALUES (‘G. Gore’,1,’09-APR-77’,12000,’M’);
Single row insertion

• Column names are optional. But when inserting values without


column names, you must insert values with an correct column
order.

• e.g. INSERT INTO DEPT values (1,’Finance’);

• e.g. INSERT INTO EMP_00 (emp_name, emp_id, d_o_b, Salary,


gender)
VALUES (‘G. Gore’,1,’09-APR-77,’M’);
Single row insertion

• INSERT INTO table_name VALUES (column1,column2,…)

• e.g. INSERT INTO DEPT (dept_name,dept_no)


VALUES (‘Marketing’,1);

• e.g. INSERT INTO EMP_00 (emp_name, emp_id, d_o_b, Salary,


gender)
VALUES (‘G. Gore’,1,’09-APR-77,’M’);
Interactive insertion or Substitution variable

• The Syntax is
• INSERT INTO TABLE_NAME VALUES(&COLUMN1,&COLUMN2);

• e.g. INSERT INTO DEPT VALUES(&dept_name,&dept_no);

• e.g. INSERT INTO EMP_00 (emp_name, emp_id, d_o_b, Salary,


gender)
VALUES (‘G. Gore’,1,’09-APR-77,’M’);
NULL VALUES (MISSING DATA)

• missing, unknown or inapplicable data


• A missing piece of data is often said to have the value NULL.
• NULL value also plays an important role in database
• NULL values allowed in non-primary key columns, that do not
have a NOT NULL constraint
1. Implicit Method: In the implicit method, the column’s name is
omitted from the column list in an INSERT statement
In stud_info table Birth_date, and Div column is omitted
INSERT INTO STUD_INFO (ROLL_NO,STUD_NAME) VALUES
(1,’S. SAWALE’);
NULL VALUES (MISSING DATA)

2.      Explicit Method : In the explicit method, the value null is used
as a value for numeric column, and the empty string(‘ ‘) is used
for date or character column.

• INSERT INTO STUD_INFO(ROLL_NO,STUD_NAME,BIRTH_DATE)


VALUES(2,’ P. PNDHRE’,NULL);
Updating the table contents (UPDATE)

• In SQL UPDATE statement is used for such modification for data.


Only one table can be updated at one time

• NULL value also plays an important role in database


• UPDATE TABLE_NAME SET COLUMN1=NEW VALUE
,COLUMN2=NEW VALUE…] [WHERE CONDITION];

• The condition is optional, but in most cases you would need to


use it. If condition is not used with UPDATE, all rows will be
updated
• UPDATE EMPLOYEE SET SALARY=12000 WHERE FNAME=’K.
KALE’;
Deleting existing rows/records. (DELETE)

• The DELETE statement removes selected rows from a single


table
• The Syntax of delete statement is
DELETE FROM TABLE_NAME [WHERE CONDITION];

• The from clause specifies the large table containing the row

• The WHERE clause specifies which rows of the table are to be


deleted

• DELETE FROM EMPLOYEE;


• DELETE FROM EMPLOYEE WHERE EMP_ID=100;
RETRIVING DATA FROM A TABLE : (SELECT COMMAND) –
DATA QUERY LANGUAGE

• The main purpose of the SQL language is for querying the


database. Data is retrieved from the database using the SELECT
statement

• SELECT ALL/DISTINCT/*/COLUMN_NAMES
FROM TABLE_NAME
[WHERE CONITION]
[GROUP BY grouping columns]
[HAVING search condition]
[ORDER BY sort specification] ;
RETRIVING DATA FROM A TABLE : (SELECT COMMAND) –
DATA QUERY LANGUAGE

• Select clause lists the data items to be retrieved by the SELECT


statement
• The FROM clause lists the table that contains the data to be
retrieved by the query.

• The WHERE clause tells SQL to include only certain rows of data
in the query results. A search condition is used to specify the
desired rows.

• The GROUP BY clause specifies a summary query.


• The HAVING clause tells SQL to include only certain groups
produced by the GROUP BY clause in the query result. like
WHERE clause, it uses a search condition to specify the desired
groups.
• The ORDER BY clause sorts the query results based on the data
in one or more columns
Selecting all columns of all row (SELECT *)
Wild Card (*)

• The main purpose of the SQL language is for querying the


database. Data is retrieved from the database using the SELECT
statement

• The syntax is
SELECT * FROM TABLE_NAME;
e.g. SELECT * FROM EMP_00;

• After 80 columns, the row display wraps column heading


Selecting Specific column of all rows:

• table by specifying the column names, separated by commas.

• The syntax is
SELECT COLUMN1,COLUMN2 FROM TABLE_NAME;
e.g. SELECT emp_name,emp_id FROM EMP_00;

• List all the employee name along with the salary

• SELECT NAME, SALARY from employee;


Eliminate Duplicate Rows: (DISTINCT) Clause

• suppress duplicate values from a result .

• The syntax is
SELECT DISTINCT COLUMN1 FROM TABLE_NAME;
e.g. SELECT DISTINCT DESIGNATION FROM EMP_00;

• LIST all department number from employee table

• SELECT DISTINCT DEPTNO FROM EMP;


Defining column Alias:

• The syntax is
SELECT COLUMN [AS] ‘ALIAS NAME’ FROM TABLE_NAME;

• SELECT DEPT ‘DEPARTMENT’ FROM EMPLOYEE;

• SELECT ENAME,SALARY “Employee and his/her salary’’ FROM


EMPLOYEE;

• . SELECT ENAME “ Employee name “ SAL+1000 “TOTAL” FROM


EMP;

• SELECT ENAME,SALARY ‘Employee and his/her salary’’, FROM


EMPLOYEE;
Concatenation or literal character string

• concatenation joins a column or a character string to another


column.

• Two vertical bars or pipe symbol (||) are used as concatenation


operator. The date and character literals must be enclosed within
single quotation marks (‘ ’), number literal need not.

• SELECT COLUMN1||COLUMN2 ‘ALIAS NAME’ FROM


TABLE_NAME;

• SELECT LNAME ||” “||FNAME||” “ || SALARY AS “ Employee


AND HIS/HER SALARY” FROM employee;
ORDER BY CLAUSE: Sorting Query Result

• The rows can be sorted in ascending or descending order.

• The rows can be sorted based on one or more columns.

• The Syntax is
SELECT columnlist FROM table_name
[ WHERE condition(s) ] [ ORDER BY column/expression [ASC]/DESC;

• Display all students in alphabetical order


SELECT Name from student ORDER BY name ;
• Find out all employees with their salaries in descending order
SELECT Empname, salary from employee WHERE DEPT=’MBA’
ORDER BY salary DESC;
ORDER BY CLAUSE: Sorting Query Result

• If the column of query result to be used for sorting is a


calculated column, it has no column name to be used in a sort
specification

• SELECT empname, Anul_salary /12 From employee


WHERE DEPTID=10 ORDER BY 2 ASC
Restricting Data With A WHERE Clause
Row Selection

• To display only those rows that meet a criteria

• SELECT columnlist FROM tablename [WHERE condition(s)];

• e.g. List out only those employee’s whose salary is more than
10000
SELECT empname, salary FROM employs WHERE salary > 10000
SEARCH CONDITIONS

• conditions that allow you to specify many different kinds of queries efficiently
and naturally

• SELECT columnlist FROM tablename [WHERE condition(s)];

• Five basic search conditions ( called predictor)


        Comparison Test.
        Range Test. (BETWEEN)
        Set Member ship test (IN)

        Pattern Matching Test (LIKE)

        NULL value test (IS NULL).


COMAPRISION TEST

• Compare the value of one expression to the value of another


expression
• In this test the operator like =,<>, <, <=, >, >= are used for
compare two SQL expression

  Syntax
SELECT * from table_name
WHERE column operator value [and/or column operator value];
COMAPRISION TEST

• Find employee joined before 2000


SELECT FNAME FROM EMPLOYEE WHERE JOIN_DT <’ 01-JAN-00’;

• List the employee whose salary is below 10000


• SELECT FNAME,SALARY FROM EMPLOYEE WHERE
SALARY<10000;
• List all the male employees and his salary

• SELECT EMPNAME, SALARY FROM EMPLOYEE


WHERE GENDER=‘M’;
RANGE TEST (BETWEEN)

• Tests whether the value of an expression falls within a specified range of values.

• SELECT * FROM table_name where column_name between value1 and value2;

• Find employee name whose salaries are between 10000 to 15000


• SELECT FNAME,SALARY FROM EMPLOYEE
WHERE SALARY BETWEEN 10000 AND 12000;

• For example the employee born between ’01-JAN-75’ to ’31-DEC-


75’;
• SELECT FNAME,BIRTH_DAT FROM EMPLOYEE
WHERE BIRTH _DATE BETWEEN ’01-JAN-75’ AND ’31-DEC-75’;
NOT BETWEEN, AND OPERATOR

• NOT operator are used to negate the result of any criteria check mode. The
negate version of the range test (NOT BETWEEN) checks for values that fall
outside the range.

• SELECT * FROM table_name where column_name not between


value1 and value2;
• Find employee name whose salaries are not lies between 10000 to 15000

• SELECT EMP_NAME,SALARY FROM EMPLOYEE


WHERE SALARY NOT BETWEEN 10000 AND 12000;

• Find employees who are not working in Finance and Marketing


department
• SELECT EMP_NAME FROM EMPLOYEE
WHERE DEPT NOT IN(‘FINANCE’,’MARKETING’);
SET MEMBER SHIP (IN) TEST :

• used to check whether a data value matches one of a list target values.

• SELECT columnlist FROM TABLE_NAME


WHERE COLUMN [NOT] IN(VALUE1,VALUE2…);

• List all the employee residing the cities CHENNAI, BANGLORE


and DELHI.

• SELECT FNAME,CITY FROM EMPLOYEE


WHERE CITY IN (‘CHENNAI’, ‘BANGLORE’, ‘DELHI’) ;

• List all the employee name whose salaries are not exactly 8000, 10000, and 12000;
PATTERN MATCHING TEST (LIKE operator)

• When character data are to be matched with some pattern, the LIKE operator is
used

• The pattern matching test LIKE , checks to se whether the data value in a column
matches a specified pattern.

• WILDCARD % : The % wildcard character matches any sequence of 0 or


more characters.

• SELECT * FROM table_name WHERE column_name LIKE ‘%value’;

• List all the employee name whose salaries are not exactly 8000, 10000, and 12000;
PATTERN MATCHING TEST (LIKE operator)

• we want to see the employees name whose name ends with RAM
characters

• SELECT FNAME FROM EMP WHERE FANME LIKE ‘%RAM’;

• WILDCARD % : The % wildcard character matches any sequence of


0 or more characters.

• SELECT * FROM table_name WHERE column_name LIKE ‘%value’;

• If you forgot whether the company names was SMITH, SMITHESON,


SMITHSEN, SMITHSONIC then

• SELECT COMPANY FROM CUSTOMERS WHERE COMPANY LIKE ‘SMITH


% CORP’
PATTERN MATCHING TEST (LIKE operator)

• WILDCARD ( _ ) [UNDERSCORE] : The _ wild card character matches only one


characters. It represents any individual character

• For example “T_M” represents the letter “T” followed by any single character,
followed by the letter “M”, and would retrieve the records that include the words
TIM, TOM, or T3M.

• Find out the name of employees joining during 1960’s

• SELECT FNAME, JOIN_DT FROM EMPLOYEE WHERE JOIN_DT LIKE ‘%6_’;


ESCAPE CHARACTER :

• How do you look for a value that has a wild card character
embedded in it?

• e.g. Find product whose product id’s start with the four letters “A
%BC”

• SELECT ORDER_NUM,PRODUCT FROM ORDERS


WHERE PRODUCT LIKE ‘A$%BC%’ ESCAPE ‘$’;

• SELECT ORDER_NUM,PRODUCT FROM ORDERS


WHERE PRODUCT LIKE ‘A$%BC%’ ESCAPE ‘$’;
ESCAPE CHARACTER :

• e.g. WHERE column_name LIKE ‘%/_ %’ ESCAPE ‘/’;

• The first % means the column value starts with any characters in
the beginning. The second % means that the value ends with any
character. The character /_ means that there is a _character in the
value. The / is used as the escape character which changes the
meanings of _ from a wild card to the underscore
NULL VALUE TEST (IS NULL) :

• The IS NULL operator checks for a NULL value. It returns TRUE


for the NULL value and FALSE for NOT NULL.

• Is there any employee who dose not have salary


• SELECT FNAME FROM EMPLOYEE WHER SALARY IS NULL;

• finds rows that do not contain a NULL value


• SELECT FNAME, SALARY FROM EMPLOYEE
WHER SALARY IS NOT NULL;
GROUPPING DATA: (GROUP BY CLAUSE)

• It is used create group of rows in a table

• . The query that uses a GROUP BY clause is called as grouped


query

• the column on which the grouping is done are called as


grouping column

• the select clause in grouped query can fetch only the grouping
columns & aggregate function.
GROUPPING DATA: (GROUP BY CLAUSE)

ENAME DEPTNO SAL JOB

RAHUL 10 1000 CLERK

SANDIP 20 2000 MANAGER

SACHIN 20 1000 SUPERVISOR


GROUPPING DATA: (GROUP BY CLAUSE)

• SELECT COLUMN,GROUPFUNCTION(COLUMN)
FROM TABLE_NAME
[WHERE Condition]
GROUP BY column/expression
[ORDER BY column/expression [ASC]/DESC];

• e.g. display the total number of employees working on each


department

• SELECT DEPT,COUNT(*) “TOTAL EMPLOYEES” FROM


EMPLOYEE GROUP BY DEPT;
GROUPPING DATA: (GROUP BY CLAUSE)

• e.g. display the total number of working on each department

• SELECT DEPT,COUNT(*) “TOTAL EMPLOYEES” FROM


EMPLOYEE GROUP BY DEPT;

DEPTNO TOTAL EMPLOYEES

10 2
20 3
30 4
GROUP SEARCH CONDITION: HAVING CLAUSE

• The HAVING clause can be used to select and reject row groups.
The GROUP function works on each group. and HAVING clause
keeps the group that match the group function.

• . List out the departments where number of employees working


are more than four.
• SELECT DEPT,COUNT(*) FROM EMPLOYEE
GROUP BY DEPT
HAVING COUNT(*) > 4;
GROUP SEARCH CONDITION: HAVING CLAUSE

• To return the minimum and maximum salaries for the employees


in each department. Whose lowest salary is below 5000

• SELECT DEPT MIN(SALARY),MAX(SALARY) FROM EMPLOYEES


GROUP BY DEPT
HAVING MIN(SALARY) < 5000;
JOINS (Multi-Table-Queries) :

• A query, which retrieves data from more than one table using a
single select statement, is called as a Multi – Table Query or JOIN
query.

• . the join condition combines a row in one table with a row from
another table based on the same value in the common attributes
• Following types of join are available in oracle
         Equi – Join
         Non equi –Join
         Outer – Join
         Self – Join.
Equi – Join or inner join

• The equi-join is a join with a join condition involving common


column from two tables. . In equi- join two tables are joined based
on equality condition specified with WHERE clause in SELECT
statement
• . the join condition combines a row in one table with a row from
another table based on the same value in the common attributes

• The syntax is
  SELECT columnlist FROM table_names WHERE join condition;
• e.g. display employee name and corresponding departments of
all employees ;
• SELECT employee.emp_name,dept.dept_name
FROM employee,dept
WHERE employee.dept_no = dept.dept_no;
Equi – Join

• 1.   Qualifying column should be of similar type and width


• but need not have the same name.
2. The column names not the same, then the table name need not
be prefixed

e.g. display the name and job of each employee and the number
and name of the department in which the employee works

SELECT emp_name,job,,dept.dep_no,dept_name FROM


employee,dept WHERE employee.dept_no = dept.dept_no;

SELECT e.emp_name,d.dept_name,s.desg_name
FROM employee e, dept d, desgn_mst s
WHERE e.dept_no=d.dept_no and e.desg_code=s.des_code;
NON EQUI – JOIN

• When a relationship between two tables is obtained by using an


operator other than equal(=), it is called as non-equi join

Often non –equi joins are combined with self join


Consider the two table EMPLOYEE and SALARY_LEVEL table.
EMPLOYEE SALARY_LEVEL
EMP_ID ENAME SALARY LEVEL_NO LOWER UPPER_L
_LIMIT IMIT

1 G. GORE 4000

2 K. KALE 12000
NON EQUI – JOIN

• SELECT e.emp_name,s.level_no FROM employee e,salary_level s


Where e.salary between s.lower_limit and s.upper_limit

EMP_NAME LEVEL_NO

G. GORE 1

K. KALE 3

S. SAWLE 2

P. PANDHRE 2
SELF JOIN :

• A self join is joining a table to itself

EMPNO ENAME DEPTNO MGR SALARY

1 G GORE 10 15000

2 K KALE 20 1 16000
Self – Join

• 1.   When a table joined to itself, two copies of the same table are
• create

e.g. display employee and his manager name

SELECT e.ename, s.ename


FROM employee e, employee s WHERE e.empno=s.mgr;
SET OPERATOR

• UNION
• INTERSECT
• MINUS

The set operator combine the rows returned by two SELECT


statement into a single result. the number and data type of the
column selected b each component query must be the same , but
the column length can be different

The general syntax is:


SELECT columnlist FROM table_name1
SET OPERATOR
SELECT columnlist FROM table_name2
UNION

• When the result set from ons select statement is to be merged


with the result set from other select statements, union opeator
can be used.It return all the rows from both queries, but duplicate
rows are not displayed.

The general syntax is:


SELECT columnlist FROM table_name1
UNION
SELECT columnlist FROM table_name2
UNION

• there are two table

STUDENT WORKER
STUD_ID STUD_NAME WORKER_ID WORKER_NAME

1 R. RAM 1 R RAM

2 S SHYAM 2 C CHAVAN

3 P PANDURANG 3 P PANDURANG
UNION

• SELECT STUDENT_ID,STUDENT_NAME FROM STUDENT


UNION
SELECT WORKER_ID,WORKER_NAME FROM WORKER;

STUD_ID STUD_NAME

1 R. RAM

2 S SHYAM

2 C. CHAVAN
UNION Restriction

         The number of columns in all queries should be same


         The datatype of the column in each query must be same.
         Union cannot be used in subquery.
         You cannot use aggregate functions in union
UNION ALL

     The only difference is that UNION ALL operation displays


duplicate
STUD_ID STUD_NAME
Rows also

1 R. RAM

1 R RAM

2 S. SHYAM

2 C. CHAVAN
INTERSECT

• Intersect operator is used to fetch rows that are common to the


result set obtained from one or two different SELECT statement
• Display students who are also workers in the collage

• SELECT student_id,student_name FROM student


INTERSECT
SELECT worker_id,worker_name FROM worker;

STUD_ID STUD_NAME

1 R. RAM

2 P PANDURANG
MINUS (DIFFERENCE)

• Minus operation fetch only those records that are available in the
first SELECT statement and are not available in the second
SELECT statement

• SELECT student_id,student_name FROM student


MINUS
SELECT worker_id,worker_name FROM worker;
• DISPAY STUDENTS WHO ARE NOT WORKER

STUD_ID STUD_NAME

3 S SHYAM
SUBQUERIES

• Subqueries are nested queries in which the result from one query
is utilized in another query.
• Subquery combines two query statements into a single query
statement, where the result of one query depends on the result
of other query

The subqueries are of two types.


• Single-row subquery : a subuery that return only row of data
• Multi-row subquery: a subquery that returns more than one
row of data.

• The syntax of subquery: 


SELECT column1,column2 FROM Table_name1, table_name2
WHERE column1=(SELECT column3 FROM table_name);
SINGLE ROW SUBQUERIES

• A single row subquery is one that returns one row from the inner
select statement.

• The syntax is
SELECT columnlist
FROM table_name
WHERE column_name operator
(SELECT columnlist from tablename WHERE condition);
Rules for SUBQUERIES

• The subquery must be enclosed within a parenthesis

• The ORDER BY clause cannot be used in a subquery

• The subquery is used on the right-hand-side of the condition


Rules for SUBQUERIES

• e.g. To determine who works in the same department as


employee ‘G GORE’

• SELECT emp_name,Dept_no FROM employee


WHERE dept_no=(SELECT dept_no FROM employee
WHERE emp_name=’G GORE’);

• e.g. display the employees whose designation is same as that of


employee 2

• SELECT emp_name,desg_code FROM employee


WHERE desg_code=
(SELECT desg_code FROM employee WHERE emp_id=2);
Creating a table using a sub-query

• CREATE TABLE TABLE_NAME


AS
SELECT QUERY;

• CREATE TABLE dept20


AS
SELECT emp_id,emp_name,salary FROM employee
WHERE dept_no=20;
Using group function in a subquery

• To display the employee name, designation code and salary of all


employees whose salary is equal to the minimum salary

• SELECT emp_name,desg_code,salary FROM EMPLOYEE


WHERE SALARY = (SELECT MIN(salary) FROM EMPLOYEES);
INSERT using a sub-query :

• An existing table can be populated with a sub-query. The table


must be already exists to insert rows into it

• INSERT INTO tablename [(COLUMN ALISES)]


SELECT columnlist FROM tablename WHERE condition;

• e.g. INSERT INTO dept20(emp_name,emp_id)


SELECT emp_name,emp_id FROM employee
where dept_no=20;
UPDATE using a sub-query

• An existing table can be populated with a sub-query. The table


must be already exists to insert rows into it

• UPDATE tablename
SET (columnnames)=
(SELECT columnlist FROM tablename WHERE sub-uery) WHERE
condition;
• e,g, Increase the salary of all employees by 1000 whose
designation is same as employee P PATIL designation

UPDATE employee
SET SALARY =SALARY+1000 WHERE desg_code=
(SELECT desg_code FROM employee WHERE emp_name=’P PATIL’)
DELETE using a sub-query.

• A row or rows from a table can be deleted based on a value


returned by a sub-query

DELETE FROM employee


WHERE dept_no=
(SELECT dept_no from dept WHERE UPPER(dept_name)=’Marketing)’);

• e,g, Increase the salary of all employees by 1000 whose


designation is same as employee P PATIL designation

UPDATE employee
SET SALARY =SALARY+1000 WHERE desg_code=
(SELECT desg_code FROM employee WHERE emp_name=’P PATIL’)
Manipualtion of date (Date functions)

• MONTHS_BETWEEN ( DATE1,DATE2) :
If you want to know how many months fall between month x and
month y
Consider in PROJECT table there are START_DATE and END_DATE
columns
SELECT TASK, START_DATE, END_DATE,
MOTHS_BETWEEN(END_DATE,START_DATE) “Duration” FROM
PROJECT;
ADD_MONTHS(DATE , NUMBER) :

• This function adds a number of months to specified date

SELECT TASK, START_DATE,END_DATE,


ADD_MONTHS(END_DATE,2) FROM PROJECT;

TASK START_DATE END_DATE ADD_MONTHS

Survey 25-MAR-00 01-APR-00 01-JUN-00


LAST_DAY(date1) :

• returns the date of the last day of the month that contains date

SELECT END_DATE, LAST_DAY(END_DATE) FROM EMPLOYEE;

END_DATE LAST_DAY
(END_DATE)

01-APR-05 30-APR-05
NEXT_DAY( DATE, CAHRACTER)

• Finds the name of the first week that is equal to or later than
another specified date

For example, to send a report on the Friday following day of each


event

SELECT START_DATE,NEXT_DAY(START_DATE,’FRIDAY’) FROM


PROJECT ;

START_DATE LAST_DAY
(END_DATE)
SYSDATE ( )

• SYSDATE return the current date and time. Requires no


arguments.

SELECT SYSDATE FROM DUAL;

SYSDATE

28-MAR-06
CHARACTER FUNCTIONS

• The character functions perform case conversion or character


manipulation
CONCAT( string 1, string 2) :

• CONCAT function concatenates string 1 and string 2 and returns


a single string

SELECT CONCAT(‘Audit’, ‘Trials’) FROM DUAL;


The result AUDIT TRIAL as a single string

SELECT CONCAT ( FNAME,LNAME) “Employee Name” FROM


Employee;
INITCAP ( ) :

INITCAP returns char, with the first letter of each word in uppercase,
all other letters in lower case

e.g.the following example capitalize each word in the string


SELECT INITCAP(‘the soap’) “capital” FROM DUAL;
The result is
capital
---------------------------------
The Soap

SELECT INITCAP(ename) “capital” FROM employee;


UPPER(CHAR) :

Converts each letter to upper case.


SELECT UPPER (‘large’) “Upper case” FROM DUAL;
The result is
Upper case
---------------------------------
LARGE
LOWER(CHAR) :

Converts each letter to lower case.


SELECT LOWER (‘large’) “lower case” FROM DUAL;
The result is
Lower case
---------------------------------
large
LENGTH(COLUMN) :

The length function returns the length of the character


SELECT LENGTH (FNAME) from employee;
The result is
LENGTH(FNAME)
---------------------------------
6
LTRIM (string1, string2) :

Removes all the characters present to the left of string1, which are
mentioned in string2
SELECT LTRIM(‘XXXORACLE’,’X’) FROM DUAL;
The result is

---------------------------------
ORACLE
RTRIM (string1, string2) :

Removes all the characters present to the right of string1 which are
mentioned in string 2
SELECT RTRIM(‘ORACLEXXX’,’X’) FROM DUAL;
The result is

---------------------------------
ORACLE
NUMERIC FUNCTIONS
ABS(NUMBER)
• Numeric function takes numeric value input and return numeric
values.

ABS ( ) function returns the absolute value of the number passed .


ABS changes all the negative numbers to positive and leaves
positive number alone.
SELECT ABS(-9) FROM DUAL;

Returns the value 9


POWER( Num1, Num2 ):

• Returns the value, which is equivalent to the number 1 raised to


the power of number 2.

SELECT POWER(3,2) FROM DUAL;

return 9
MOD (Num1, Num2 ) :

• Return the reminder when number1 is divided by Number 2.

SELECT MOD(9,4) FROM DUAL;

return 1
ROUND( Num1, Num2) :

• The number 1 rounded to the decimal places mentioned by the


number 2.

SELECT ROUND(10.2745,2) FROM DUAL;

return 1027
SQRT ( Number ) :

• Returns the square root of the number passed as the argument

SELECT SQRT(16) FROM DUAL;


CONCURRENCY CONTROL IN ORACLE LOCK

• In multi-user system, when user share access to a database and


one or more users is updating data, there is a chance of data
corruption.

SQL uses its transaction mechanism that eliminates the data


corruption.

LOCKING MECHANISM : Oracle provides concurrency and


integrity between transaction using locking mechanism.

Oracle locking is fully automatic and doesn't require user action

Two locking mode


Exclusive mode : prevents sharing until lock is released.
Share mode : allows sharing for reading purpose.
CONCURRENCY CONTROL IN ORACLE LOCK

• In multi-user system, when user share access to a database and


one or more users is updating data, there is a chance of data
corruption.

SQL uses its transaction mechanism that eliminates the data


corruption.

LOCKING MECHANISM : Oracle provides concurrency and


integrity between transaction using locking mechanism.

Oracle locking is fully automatic and doesn't require user action


CONCURRENCY CONTROL IN ORACLE LOCK

• EXPLICIT LOCK (LOCK TABLE)

It eliminates the overhead of row-y-row locking.


it eliminates the possibility that other transaction will lock part of
the table .

Two locking mode

Share Mode Lock : used when transaction wants to read data from
database. The updation is not allowed.

Exclusive Lock : prevents sharing resources until lock is released

LOCK TABLE table_name IN SHARE / EXCLUSIVE mode;

LOCK TABLE employee IN SHARE MODE;


Transaction A Transaction B

ORDER OFFICE PRODUCT

Unlocked Unlocked Unlocked

Update OK
OK Update
Orders Locked for B Products
Locked for A

Select from Locked for A Select from


wait
office office

Update OK
order

Commit unlocked unlocked

You might also like