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

03-Oracle Made Easy-Version-1.5 - SQL

This document provides an overview of Oracle SQL commands and concepts in 18 practice sheets. It covers topics such as SQL statements, SQL*Plus commands, controlling user access with privileges, creating and managing tables, and including constraints in tables. The sheets contain examples of SQL statements for creating users and roles, granting privileges, describing and querying database objects, and defining tables with constraints like primary keys, foreign keys and checks.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

03-Oracle Made Easy-Version-1.5 - SQL

This document provides an overview of Oracle SQL commands and concepts in 18 practice sheets. It covers topics such as SQL statements, SQL*Plus commands, controlling user access with privileges, creating and managing tables, and including constraints in tables. The sheets contain examples of SQL statements for creating users and roles, granting privileges, describing and querying database objects, and defining tables with constraints like primary keys, foreign keys and checks.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Oracle Made Easy (SQL)

(Version 1.5)

Oracle Made Easy


SQL

Practice Sheet
Version 1.5

W3coder.com
Web : W3coder.com, Email : [email protected]
Phone : +88 017 46044306, +88 01616044306

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 1 of 18


Oracle Made Easy (SQL)
(Version 1.5)

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 2 of 18


Oracle Made Easy (SQL)
(Version 1.5)
SQL Statements

SELECT Query
INSERT
UPDATE
Data Manipulation Language (DML)
DELETE
MERGE
CREATE
ALTER
DROP Data Definition Language (DDL)
RENAME
TRUNCATE
GRANT
Data Control Language (DCL)
REVOKE
COMMIT
ROLLBACK Transaction Control
SAVEPOINT

1. Common SQL*PLUS commands :

To describe a table

SQL> desc emp;

To re-execute a command

SQL> /

Note: the buffer can only hold one previous statement.

To save the query u have in the buffer to a file

SQL> save <filename>.sql

To execute what is in this query file

SQL> @all_emp

Assuming you have made a lot of queries during a session and you want to save
everthing at once

SQL> spool <filename>.txt

Any other command you type will be stored inside the <filename>.txt. But before
this can happen, you need to do this:

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 3 of 18


Oracle Made Easy (SQL)
(Version 1.5)
SQL> spool off

So when you do the above, you can then exit sqlplus, and cat output.txt. The result will
show you all the commands or work you have done while in sqlplus.

If you make new changes and you want to append it to <filename>.txt

SQL> spool <filename>.txt append

To make changes to sql statement in an editor

SQL> ed

To insert a variable during your sql queries in sqlplus

SQL> select empno,ename,job,sal,comm,from emp where sal > &&x and comm
> &&x

To change your password

SQL> passw

To change the password of another user

SQL> passw [username]

To find out more sqlplus commands

SQL> help index

2. Controlling User Access:

SL Use Statements
Creating Users CREATE USER scott IDENTIFIED BY tiger;
• An application developer, for example, may have the following
system privileges:
– CREATE SESSION
1 User System Privileges – CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE
CREATE ROLE manager;
Creating and Granting
2 GRANT create table, create view TO manager;
Privileges to a Role
GRANT manager TO DEHAAN, KOCHHAR;
Changing Your ALTER USER scott IDENTIFIED BY lion;
3
Password
GRANT select ON employees TO sue, rich;
Granting Object
4
Privileges GRANT update (department_name, location_id)
ON departments

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 4 of 18


Oracle Made Easy (SQL)
(Version 1.5)
TO scott, manager;
GRANT select, insert
ON departments
TO scott
Using the WITH
WITH GRANT OPTION;
5 GRANT OPTION and
PUBLIC Keywords
GRANT select
ON alice.departments
TO PUBLIC;
Data Dictionary View Description
ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on the user’s
objects
Confirming Privileges USER_TAB_PRIVS_RECD Object privileges granted to the user
6
Granted USER_COL_PRIVS_MADE Object privileges granted on the
columns of the user’s objects
USER_COL_PRIVS_RECD Object privileges granted to the
user on specific columns
USER_SYS_PRIVS Lists system privileges granted to
the user

Revoking Object REVOKE select, insert ON departments FROM scott;


7
Privileges
CREATE PUBLIC DATABASE LINK hq.acme.com
8 Create the database link
USING 'sales';
Write SQL statements SELECT * FROM [email protected];
9 that use the database
link.

3. Creating and Managing Tables:

SL Use Statements
1 CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
Creating Tables loc VARCHAR2(13));

DESCRIBE dept

2 SELECT table_name
FROM user_tables ;

Querying the Data SELECT DISTINCT object_type


Dictionary FROM user_objects ;

SELECT *
FROM user_catalog ;
3 CREATE TABLE dept80
AS
SELECT employee_id, last_name,
Creating a Table by
salary*12 ANNSAL,
Using a Subquery
hire_date
FROM employees
WHERE department_id = 80;

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 5 of 18


Oracle Made Easy (SQL)
(Version 1.5)
4 ALTER TABLE dept80
Adding a Column
ADD (job_id VARCHAR2(9));
5 Modifying a Column ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
6 ALTER TABLE dept80
Dropping a Column
DROP COLUMN job_id;
7 ALTER TABLE table
SET UNUSED (column);

The SET UNUSED ALTER TABLE table


Option SET UNUSED COLUMN column;

ALTER TABLE table


DROP UNUSED COLUMNS;
8 Dropping a Table DROP TABLE dept80;
9 Changing the Name of RENAME dept TO detail_dept;
an Object
10 Truncating a Table TRUNCATE TABLE detail_dept;

4. Including Constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK

SL Use Statements
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
1 Defining Constraints ...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
The NOT NULL salary NUMBER(8,2),
2
Constraint commission_pct NUMBER(2,2),
hire_date DATE
CONSTRAINT emp_hire_date_nn
NOT NULL,
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
The UNIQUE
3 salary NUMBER(8,2),
Constraint
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
CONSTRAINT emp_email_uk UNIQUE(email));
CREATE TABLE departments(
The PRIMARY KEY department_id NUMBER(4),
4 Constraint department_name VARCHAR2(30)
CONSTRAINT dept_name_nn NOT NULL,
manager_id NUMBER(6),

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 6 of 18


Oracle Made Easy (SQL)
(Version 1.5)
location_id NUMBER(4),
CONSTRAINT dept_id_pk PRIMARY KEY(department_id));
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
The FOREIGN KEY commission_pct NUMBER(2,2),
5
Constraint hire_date DATE NOT NULL,
...
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));
ALTER TABLE employees
ADD CONSTRAINT emp_manager_fk
6 Adding a Constraint
FOREIGN KEY(manager_id)
REFERENCES employees(employee_id);
ALTER TABLE employees
DROP CONSTRAINT emp_manager_fk;
7 Dropping a Constraint
ALTER TABLE departments
DROP PRIMARY KEY CASCADE;
ALTER TABLE employees
8 Disabling Constraints
DISABLE CONSTRAINT emp_emp_id_pk CASCADE;
ALTER TABLE employees
9 Enabling Constraints
ENABLE CONSTRAINT emp_emp_id_pk;
ALTER TABLE test1
DROP (pk) CASCADE CONSTRAINTS;
10 Cascading Constraints
ALTER TABLE test1
DROP (pk, fk, col1) CASCADE CONSTRAINTS;
SELECT constraint_name, constraint_type,
search_condition
11 Viewing Constraints
FROM user_constraints
WHEREtable_name = 'EMPLOYEES';
Viewing the Columns SELECT constraint_name, column_name
12 Associated with FROM user_cons_columns
Constraints WHEREtable_name = 'EMPLOYEES';

5. Creating Views:

SL Use Statements
CREATE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees
1 Creating Views
WHERE department_id = 80;

DESCRIBE empvu80;
CREATE VIEW salvu50
Create a view by using AS SELECT employee_id ID_NUMBER, last_name NAME,
2 column aliases in the salary*12 ANN_SALARY
subquery. FROM employees
WHERE department_id = 50;
Retrieving Data from a SELECT *
3
View FROM salvu50;

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 7 of 18


Oracle Made Easy (SQL)
(Version 1.5)
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ' ' || last_name,
4 Modifying a View
salary, department_id
FROM employees
WHERE department_id = 80;
CREATE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),
Creating a Complex
5 MAX(e.salary),AVG(e.salary)
View
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;
CREATE OR REPLACE VIEW empvu20
Using the WITH AS SELECT *
6 CHECK OPTION FROM employees
Clause WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
CREATE OR REPLACE VIEW empvu10
(employee_number, employee_name, job_title)
Denying DML AS SELECT employee_id, last_name, job_id
7
Operations FROM employees
WHERE department_id = 10
WITH READ ONLY;
8 Removing a View DROP VIEW view;
SELECT ROWNUM as RANK, last_name, salary
Example of Top-N FROM (SELECT last_name,salary FROM employees
9
Analysis ORDER BY salary DESC)
WHERE ROWNUM <= 3;

6. Other Database Objects:


Sequence
Index
Synonym

SL Use Statements
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
1 Creating a Sequence
MAXVALUE 9999
NOCACHE
NOCYCLE;
SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;
2 Confirming Sequences
The LAST_NUMBER column displays the next available sequence
number if NOCACHE is specified.
INSERT INTO departments(department_id,
department_name, location_id)
3 Using a Sequence VALUES (dept_deptid_seq.NEXTVAL, 'Support', 2500);

SELECT dept_deptid_seq.CURRVAL FROM dual;


ALTER SEQUENCE dept_deptid_seq
4 Modifying a Sequence
INCREMENT BY 20

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 8 of 18


Oracle Made Easy (SQL)
(Version 1.5)
MAXVALUE 999999
NOCACHE
NOCYCLE;
5 Removing a Sequence DROP SEQUENCE dept_deptid_seq;
An index:
• Is a schema object
• Is used by the Oracle server to speed up the retrieval of rows by
using a pointer
6 What is an Index?
• Can reduce disk I/O by using a rapid path access method to
locate data quickly
• Is independent of the table it indexes
• Is used and maintained automatically by the Oracle server
CREATE INDEX emp_last_name_idx
7 Creating an Index
ON employees(last_name);
SELECT ic.index_name, ic.column_name,
ic.column_position col_pos,ix.uniqueness
8 Confirming Indexes FROM user_indexes ix, user_ind_columns ic
WHEREic.index_name = ix.index_name
AND ic.table_name = 'EMPLOYEES';
CREATE INDEX upper_dept_name_idx
9 Function-Based Indexes
ON departments(UPPER(department_name));
10 Removing an Index DROP INDEX upper_last_name_idx;
CREATE SYNONYM d_sum
Creating and Removing FOR dept_sum_vu;
11
Synonyms
DROP SYNONYM d_sum;

7. Manipulating Data:

SL Use Statements
INSERT INTO departments(department_id, department_name,
1 Inserting New Rows manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
INSERT INTO departments (department_id,
department_name )
Inserting Rows with VALUES (30, 'Purchasing');
2
Null Values
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);
INSERT INTO employees (employee_id,
first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
3 Inserting Special Values department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 100);
INSERT INTO employees
VALUES (114,
Inserting Specific Date 'Den', 'Raphealy',
4
Values 'DRAPHEAL', '515.127.4561',
TO_DATE('FEB 3, 1999', 'MON DD, YYYY'),
'AC_ACCOUNT', 11000, NULL, 100, 30);

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 9 of 18


Oracle Made Easy (SQL)
(Version 1.5)
INSERT INTO departments
5 Creating a Script (department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);
INSERT INTO sales_reps(id, name, salary, commission_pct)
Copying Rows SELECT employee_id, last_name, salary, commission_pct
6
from Another Table FROM employees
WHERE job_id LIKE '%REP%';
UPDATE employees
SET department_id = 70
Updating Rows in a WHERE employee_id = 113;
7
Table
UPDATE copy_emp
SET department_id = 110;
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
Updating Two Columns WHERE employee_id = 205),
8
with a Subquery salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;
UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
Updating Rows Based
9 WHERE employee_id = 100)
on Another Table
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);
Updating Rows: UPDATE employees
10 Integrity Constraint SET department_id = 55
Error WHERE department_id = 110;
DELETE FROM departments
Deleting Rows from a WHERE department_name = 'Finance';
11
Table
DELETE FROM copy_emp;
DELETE FROM employees
WHERE department_id =
Deleting Rows Based
12 (SELECT department_id
on Another Table
FROM departments
WHERE department_name LIKE '%Public%');
Deleting Rows: DELETE FROM departments
13 Integrity Constraint WHERE department_id = 60;
Error
INSERT INTO
(SELECT employee_id, last_name,
email, hire_date, job_id, salary,
department_id
Using a Subquery in an
14 FROM employees
INSERT Statement
WHERE department_id = 50)
VALUES (99999, 'Taylor', 'DTAYLOR',
TO_DATE('07-JUN-99', 'DD-MON-RR'),
'ST_CLERK', 5000, 50);
INSERT INTO departments
Using Explicit Default (department_id, department_name, manager_id)
15
Values VALUES (300, 'Engineering', DEFAULT);

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 10 of 18


Oracle Made Easy (SQL)
(Version 1.5)
UPDATE departments
SET manager_id = DEFAULT WHERE department_id = 10;
MERGE INTO copy_emp c
USING employees e
ON (c.employee_id = e.employee_id)
WHEN MATCHED THEN
Merging Rows
UPDATE SET
(Insert or update rows in
c.first_name = e.first_name,
the COPY_EMP table
c.last_name = e.last_name,
16 to match
...
the EMPLOYEES
c.department_id = e.department_id
table.)
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,
e.email, e.phone_number, e.hire_date, e.job_id,
e.salary, e.commission_pct, e.manager_id,
e.department_id);
DELETE FROM employees
WHERE employee_id = 99999;
1 row deleted.
Committing Data
17
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row inserted.
DELETE FROM copy_emp;
State of the Data After 22 rows deleted.
18
ROLLBACK ROLLBACK;
Rollback complete.

8. Writing Basic SQL Statements:

SL Use Statements
1 SELECT *
Selecting All Columns
FROM departments;

2 SELECT department_id, location_id


Selecting Specific Columns
FROM departments;
3 SELECT last_name, salary, salary + 300
Using Arithmetic Operators
FROM employees;
4 Operator Precedence * / + -
5 SELECT last_name, salary, 12*salary+100
Operator Precedence
FROM employees;
6 SELECT last_name, salary, 12*(salary+100)
Using Parentheses
FROM employees;
7 SELECT last_name, job_id, salary, commission_pct
Defining a Null Value
FROM employees;
8 SELECT last_name, 12*salary*commission_pct
FROM employees;
Null Values
(Arithmetic expressions containing a null value
in Arithmetic Expressions
evaluate to null.)

9 SELECT last_name AS name, commission_pct comm


Using Column Aliases FROM employees;
10 SELECT last_name "Name", salary*12 "Annual Salary"
FROM employees;
11 Using the Concatenation SELECT last_name||job_id AS "Employees"

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 11 of 18


Oracle Made Easy (SQL)
(Version 1.5)
Operator FROM employees;
12 SELECT last_name ||' is a '||job_id
Using Literal Character
AS "Employee Details"
Strings
FROM employees;
13 SELECT department_id
Duplicate Rows
FROM employees;
14 SELECT DISTINCT department_id
Eliminating Duplicate Rows
FROM employees;
15 Displaying Table Structure DESCRIBE employees

9. Restricting and Sorting Data:

SL Use Statements
SELECT employee_id, last_name, job_id, department_id
1 Using the WHERE Clause FROM employees
WHERE department_id = 90 ;
Character strings and date values are enclosed in single quotation
marks. Character values are case sensitive, and date values are format
sensitive.
2 Character Strings and Dates Example :
SELECT last_name, job_id, department_id
FROM employees
WHERE last_name = 'Whalen';
= Equal To
> Greater than
>= Greater than or equal to
3 Comparison Conditions < Less than
<= Less than or equal to
<> Not equal to.
!= Not equal to.
SELECT last_name, salary
Using Comparison
4 FROM employees
Conditions
WHERE salary <= 3000;
Between .. And … Between two values (inclusive)
Other Comparison In Match any of a list of values
5
Conditions Like Match a character pattern
Is Null Is a null value.
SELECT last_name, salary
Using the BETWEEN
6 FROM employees
Condition
WHERE salary BETWEEN 2500 AND 3500;
SELECT employee_id, last_name, salary, manager_id
7 Using the IN Condition FROM employees
WHERE manager_id IN (100, 101, 201);
SELECT first_name
8 Using the LIKE Condition FROM employees
WHEREfirst_name LIKE 'S%';
SELECT last_name, manager_id
9 Using the NULL Conditions FROM employees
WHERE manager_id IS NULL;
AND Returns TRUE if both component conditions are true
10 Logical Conditions OR Returns TRUE if either component condition is true
NOT Returns TRUE if the following condition is false
SELECT employee_id, last_name, job_id, salary
11 Using the AND Operator FROM employees
WHERE salary >=10000

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 12 of 18


Oracle Made Easy (SQL)
(Version 1.5)
AND job_id LIKE '%MAN%';
SELECT employee_id, last_name, job_id, salary
FROM employees
12 Using the OR Operator
WHERE salary >= 10000
OR job_id LIKE '%MAN%';
SELECT last_name, job_id
Using the NOT Operator FROM employees
13
WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');
Sort rows with the ORDER BY clause
ASC: ascending order, default
14 ORDER BY Clause
DESC: descending order
The ORDER BY clause comes last in the SELECT statement.
SELECT last_name, job_id, department_id, hire_date
15 ORDER BY Clause FROM employees
ORDER BY hire_date ;
SELECT last_name, job_id, department_id, hire_date
Sorting in Descending
16 FROM employees
Order
ORDER BY hire_date DESC;
SELECT employee_id, last_name, salary*12 annsal
17 Sorting by Column Alias FROM employees
ORDER BY annsal;
SELECT last_name, department_id, salary
Sorting by Multiple
18 FROM employees
Columns
ORDER BY department_id, salary DESC;

10. Single-Row Functions :

SL Use Statements
LOWER
Case-manipulation
1 UPPER
functions
INITCAP
CONCAT
SUBSTR
Character-manipulation LENGTH
2 INSTR
functions
LPAD | RPAD
TRIM
REPLACE
LOWER('SQL Course') sql course
Case Manipulation
3 UPPER('SQL Course') SQL COURSE
Functions
INITCAP('SQL Course') Sql Course
SELECT employee_id, last_name, department_id
FROM employees
WHERE last_name = 'higgins';
Using Case
4 no rows selected
Manipulation Functions
SELECT employee_id, last_name, department_id
FROM employees
WHERE LOWER(last_name) = 'higgins';
5 Character-Manipulation CONCAT('Hello', 'World') HelloWorld
Functions SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 13 of 18


Oracle Made Easy (SQL)
(Version 1.5)
TRIM('H' FROM elloWorld
'HelloWorld')
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name),
Using the Character-
6 INSTR(last_name, 'a') "Contains 'a'?"
Manipulation Functions
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';
ROUND: Rounds value to specified decimal
ROUND(45.926, 2) 45.93
TRUNC: Truncates value to specified decimal
7 Number Functions
TRUNC(45.926, 2) 45.92
MOD: Returns remainder of division
MOD(1600, 300) 100
SELECT ROUND(45.923,2), ROUND(45.923,0),
Using the ROUND
8 ROUND(45.923,-1)
Function
FROM DUAL;
SELECT TRUNC(45.923,2), TRUNC(45.923),
Using the TRUNC
9 TRUNC(45.923,-2)
Function
FROM DUAL;
SELECT last_name, salary, MOD(salary, 5000)
Using the MOD
10 FROM employees
Function
WHERE job_id = 'SA_REP';
Number of months
MONTHS_BETWEEN
between two dates
ADD_MONTHS Add calendar months to date
11 Date Functions NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date
MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
ADD_MONTHS ('11-JAN-94',6)
12 Use of Date Functions
NEXT_DAY ('01-SEP-95','FRIDAY')
LAST_DAY('01-FEB-95')
SELECT last_name,
Using the TO_CHAR TO_CHAR(hire_date, 'fmDD Month YYYY')
13
Function with Dates AS HIREDATE
FROM employees;
SELECT TO_CHAR(salary, '$99,999.00') SALARY
Using the TO_CHAR
14 FROM employees
Function with Numbers
WHERE last_name = 'Ernst';
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')
15 RRRR Format FROM employees
WHERE hire_date < TO_DATE('01-Jan-90', 'DD-Mon-RR');
SELECT last_name,
Nesting Functions NVL(TO_CHAR(manager_id), 'No Manager')
16
FROM employees
WHERE manager_id IS NULL;
SELECT last_name, salary, NVL(commission_pct, 0),
Using the NVL
17 (salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL
Function
FROM employees;

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 14 of 18


Oracle Made Easy (SQL)
(Version 1.5)

SELECT last_name, job_id, salary,


DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary)
REVISED_SALARY
FROM employees;
SELECT last_name, salary,
Using the DECODE DECODE (TRUNC(salary/2000, 0),
18 0, 0.00,
Function
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
5, 0.42,
6, 0.44,
0.45) TAX_RATE
FROM employees
WHERE department_id = 80;

11. Subqueries :

SL Use Statements
SELECT last_name
FROM employees
Using a Subquery WHERE salary >
1
(SELECT salary
FROM employees
WHERE last_name = 'Abel');
SELECT last_name, job_id, salary
FROM employees
WHERE job_id =
(SELECT job_id
Executing Single-Row
2 Subqueries FROM employees
WHERE employee_id = 141)
AND salary >
(SELECT salary
FROM employees
WHERE employee_id = 143);
SELECT last_name, job_id, salary
FROM employees
Using Group Functions
WHERE salary =
3 in a Subquery
(SELECT MIN(salary)
FROM employees);

SELECT department_id, MIN(salary)


FROM employees
GROUP BY department_id
The HAVING Clause
HAVING MIN(salary) >
4 with Subqueries
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

5 Using the ANY SELECT employee_id, last_name, job_id, salary

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 15 of 18


Oracle Made Easy (SQL)
(Version 1.5)
Operator FROM employees
in Multiple-Row WHERE salary < ANY
Subqueries (SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
SELECT employee_id, last_name, job_id, salary
FROM employees
Using the ALL Operator
WHERE salary < ALL
in Multiple-Row
6 (SELECT salary
Subqueries
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
SELECT emp.last_name
Null Values in a FROM employees emp
7 Subquery WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);

12. Displaying Data from Multiple Tables:

SL Use Statements
A Cartesian product is formed when:
– A join condition is omitted
– A join condition is invalid
1 Cartesian Products – All rows in the first table are joined to all rows in the
second table
To avoid a Cartesian product, always include a valid join condition in a
WHERE clause.
Equijoin
Oracle Proprietary Non-equijoin
2
Joins (8i and prior): Outer join
Self join
Cross joins
SQL: 1999 Natural joins
3 Compliant Joins: Using clause
Full or two sided outer joins
Arbitrary join conditions for outer joins
SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
Retrieving Records
4 departments.location_id
with Equijoins
FROM employees, departments
WHERE employees.department_id = departments.department_id;
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
5 Using Table Aliases
FROM employees e , departments d
WHERE e.department_id = d.department_id;
SELECT e.last_name, e.salary, j.grade_level
FROM employees e, job_grades j
Retrieving Records
6 WHERE e.salary
with Non-Equijoins
BETWEEN j.lowest_sal AND j.highest_sal;

SELECT e.last_name, e.department_id, d.department_name


7 Using Outer Joins FROM employees e, departments d
WHERE e.department_id(+) = d.department_id ;
8 Joining a Table to Itself SELECT worker.last_name || ' works for '

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 16 of 18


Oracle Made Easy (SQL)
(Version 1.5)
– Self Join || manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;

13. Aggregating Data Using Group Functions:

SL Use Statements
• AVG
• COUNT
Types of Group
1 • MAX
Functions
• MIN
• SUM
SELECT AVG(salary), MAX(salary),
Using the AVG and MIN(salary), SUM(salary)
2
SUM Functions FROM employees
WHERE job_id LIKE '%REP%';
Using the MIN and SELECT MIN(hire_date), MAX(hire_date)
3
MAX Functions FROM employees;
SELECT COUNT(*)
FROM employees
WHERE department_id = 50;

Using the COUNT SELECT COUNT(commission_pct)


4
Function FROM employees
WHERE department_id = 80;

SELECT COUNT(DISTINCT department_id)


FROM employees;
(Group functions ignore
SELECT AVG(commission_pct)
5 null values in the
FROM employees;
column.)
SELECT department_id, AVG(salary)
Using the GROUP BY
6 FROM employees
Clause
GROUP BY department_id ;
Using the GROUP BY SELECT department_id dept_id, job_id, SUM(salary)
7 Clause FROM employees
on Multiple Columns GROUP BY department_id, job_id ;
SELECT department_id, COUNT(last_name)
FROM employees;
Illegal Queries
8 SELECT department_id, AVG(salary)
Using Group Functions
FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;
Using the HAVING
9 SELECT job_id, SUM(salary) PAYROLL
Clause
FROM employees
WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);
10 Nesting Group SELECT MAX(AVG(salary))

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 17 of 18


Oracle Made Easy (SQL)
(Version 1.5)
Functions FROM employees
GROUP BY department_id;

Enlightened Software, www.w3coder.com, 01746044306

Oracle Made Easy Practice Sheet 18 of 18

You might also like