You are on page 1of 68

INTRODUCTION TO SQL

Oracle Database
A structured collection and repository of records or
data
Latest Version of Oracle database is Oracle 10g
Databases before Oracle 8i are pure Relational
Database Management Systems (RDBMS)
Databases after Oracle 8i are Object - Relational
Databases.
Oracle E-business Suite can use Oracle 8i/9i or 10g


SQL
SQL stands for Structured Query
Language
It is used to communicate with the
Oracle Database
Provides the ability to insert, update or
delete data in database

Tables
A relational database contains many
tables
Data or information for the database is
stored in these tables
Tables have one or more columns and
each column has a datatype
The table rows contain the actual data
Tables
Example of a Employees table







A Relational database uses relations or two-
dimensional tables to store data

Employee Id First Name Last Name Email
100 Steve Douglas sdoug@aa.com
101 John Doe jdoe@aa.com
Relating Multiple tables
Each row of data in a table is uniquely
identified by a Primary Key(PK).
Multiple tables can be logically related
using Foreign Keys(FK)
SQL Statements
SELECT Statement
Allows you to query the tables.
Projection, Selection, Joining
Projection: Which columns to display
Selection: which rows to select
Joining: How to join two tables

Projection, Selection, Join
We will discuss these examples in detail later on:

select employee_id, employee_name Projection
From employees
Where employee_id = 100 Selection

Select employee_name,department_name Projection
From employees e, departments d
Where e.department_id = d.department_id Joining
And d.department_id = 1001 Selection
Basic Select Statements
1. SELECT * FROM table_name
2. SELECT col1, col2, col3 FROM table_name table_alias
3. SELECT distinct col1 FROM table_name
4. SELECT col1, col2, (col3 + col4) FROM table_name

SELECT identifies which columns
FROM identifies from which tables
* indicates that all columns need to be displayed
Distinct keyword eliminates any duplicates
Col1, col2, col3 represents the columns in the table
Table_alias is an alias name given to the table. Useful in
specifying join coniditions

Expressions
We can use arithmetic expression in the SQL SELECT clause
We can create expressions with NUMBER or DATES using +, -, *,
/ operators
Select col1+ col2 SUM, col1 col2, col1*col2, col1/col2 from
table_name
Operator precedence is *, /, +, -.
Select col1 + col2 * col3 from table_name
Operators with similar precedence are evaluated from left-to-
right.
Select col1 * col2 / col3 from table_name
Parenthesis can override precedence.
Select (col1 + col2) * col3 from table_name
We can concatenate character data using || symbol
Select last_name || is a || job_id from employees
WHERE Clause
WHERE Clause restricts the rows returned by SELECT statement
SELECT col1, col2, col3
FROM table_name
WHERE {conditions}
Characters and Dates values are enclosed in single quotation
marks.
Default Date format is DD-MON-RR.
Example:
WHERE hire_date = 01-JAN-95
WHERE salary >= 6000
WHERE last_name = SMITH


Comparison Operators
Comparison Operators
Comparison Operators
Examples
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500;

SELECT employee_id, last_name, salaray, manager_id
FROM employees
WHERE manager_id IN (100,101,201);

SELECT first_name
FROM employees
WHERE first_name LIKE 'S%;
NULL Values
A NULL value means a value is unavailable,
unassigned, unknown or inapplicable
It is not equal to 0 or or or NULL. It is a
big VOID
We cannot use the regular comparison
operators. To test if a value in a particular
column is NULL we use IS NULL
Example:
SELECT last_name, first_name
FROM employees
WHERE manager_id IS NULL;

Logical Conditions
AND Operator
AND condition requires both the
conditions to be true inorder to be true
The following is the truth table for AND

OR Operator
OR Condition requires atleast one
condition to be true
Following is the truth table for OR
condition

NOT Operator
NOT operator return TRUE if the
condition returns FALSE and vice versa
Examples:

WHERE job_id NOT IN ('AC_ACCOUNT','AD_VP')
WHERE salary NOT BETWEEN 10000 AND 15000
WHERE last_name NOT LIKE '%A%'
WHERE commission_pct IS NOT NULL
SORTING rows ORDER BY
Sort the returned rows using ORDER BY
clause
Two Options: ASC(for Ascending, default) and
DESC(for Descending Sort)
Example:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date
Sort column need not be in the SELECT clause
ORDER BY options
Sorting in Descending Order
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC
Sorting by Column Alias
SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal;
Sorting by Multiple Columns
SELECT last_name, job_id, department_id, salary, hire_date
FROM employees
ORDER BY department_id, hire_date DESC;

SQL Functions
SQL functions can be used in the SQL statements
Two types: Single Row and Multiple Row Functions
Generally use a lot of character, number and date
functions
Take zero or more arguments but returns one value
or NULL
Single Row Functions operate on single rows only
and returns one result per row. Eg TO_CHAR,
TO_DATE, NVL
Multi Row Functions operate on group of rows and
returns one result per group. Eg. SUM, AVG
Functions Examples:
Character Functions
Case-Manipulation Functions:
LOWER, UPPER, INITCAP
Character Manipulation Functions:
CONCAT, SUBSTR, LENGTH, INSTR, LPAD, TRIM, REPLACED
Number Functions
ROUND, TRUNC, MOD

Dates in Oracle
Dates are stored in a numeric format internally:
century, year, month, day, hours, minutes and
seconds
Default date format is DD-MON-RR
Function SYSDATE returns the current date and time
SELECT SYSDATE FROM DUAL;
Add and subtract a number from a date to get a resultant date
Subtract two dates to get number of days between
Date Functions
Conversion Functions
Oracle performs implicit conversion within the server
For explicit conversion you have to use appropriate
functions

TO_CHAR to display Dates
Use TO_CHAR(pDate, format); to display Dates in
desired format
Assume pDate = 25-MAR-08
TO_CHAR(pDate, DD-MONTH-YYYY) => 25-MARCH-2008
TO_CHAR(pDate, DDspth of MONTH,YYYY) => Twenty Fifth of
MARCH, 2008
There are many additional formats available for date conversion

NVL Function
Conditional Expression
They give the ability to perform IF-THEN-ELSE conditions in SQL
Two Options: CASE and DECODE

CASE and DECODE Examples
SELECT last_name, job_id, salary
CASE job_id WHEN 'IT_PROG' THEN 1.10 * salary
WHEN 'ST_CLERK' THEN 1.15 * salary
WHEN 'SA_REP' THEN 1.20 * salary
ELSE salary END
FROM employees;

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)
FROM employees;
Joins: Obtaining Data from
Multiple Tables
Primary Key and Foreign Key relationships are mainly used to
query from multiple tables
Different Types of Joins. Following are mainly used
1. Equi Join
2. Non-Equi Join
3. Outer Join
4. Self Join
Many other named joins defined in Oracle 9i.
Eg: CROSS JOIN, NATURAL JOIN, LEFT OUTER JOIN
To distinguish ambiguous columns and for performance
reasons also, it is better to qualify a column by prefixing table
name or table alias. Eg: table1.columnA, t2.ColumnD.
Joins
Equi Join Involves Primary Key and Foreign Keys. Also called
Simple Joins or inner joins
Ex:SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e, departments d
WHERE e.department_id = d.department_id
Use AND or OR to add additional search conditions
SELECT e.employee_id, e.last_name, e.department_id, d.department_id,
d.location_id
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND e.last_name = 'Mallay'
To Join n number of tables you need atleast n-1 joins. Otherwise it
may lead to Cartesian product
Non Equi Join
A NonEqui Join is a join condition containing something other
that equality (=) operator
Ex:SELECT e.last_name, e.salary, j.grade_level
FROM employees e, job_grades j
WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal
We can use other comparison operators lik >=, <=, <>, NOT in
nonequi joins

Outer Join
Return records with no direct match in target table. See below:

Outer Join
Following query will not get Contracting department
SELECT d.department_id, d.department_name, e.last_name, e.first_name
FROM departments d, employees e
WHERE d.department_id = e.department_id

This is Employees tables does not have any records with
department_id = 190. Employees table is deficient in values. Put an
outer join (+ symbol) on the deficient column in the join
SELECT d.department_id, d.department_name, e.last_name, e.first_name
FROM departments d, employees e
WHERE d.department_id = e.department_id(+)
Self Joins
Joining a table to itself in order to retrieve data

Self Join
Create two different aliases to the self join table.

Group Functions
Group Functions work on set of rows to give one result per
group.
The set of rows may be entire table or table split into groups
(GROUP BY)

Common Group Functions
AVG: Calculate Average of n values excluding null value
MIN: Calculate Minimun of n values excluding null values
MAX: Calculate Maximum of n values excluding null values
SELECT AVG(salary), min(salary), max(salary)
FROM employees WHERE job_id like %IT%
COUNT: Returns the count of number of records
SELECT count(*) FROM employees WHERE department_id = 50
COUNT(EXPR) returns the count of non-NULL values of the expression
SELECT count(commission) FROM employees WHERE department_id = 80
Use the DISTINCT keyword to return count of distinct non-NULL values
SELECT count(distinct commission) FROM employees WHERE
department_id = 80
Use NVL to force the group functions to include NULL value columns
SELECT AVG(nvl(salary,0)), min(nvl(salary,0)), max(nvl(salary,0))
FROM employees WHERE job_id like %IT%


GROUP BY: Create groups of
data
Split the rows of the table into smaller groups with GROUP BY
SELECT department_id, avg(salary)
FROM employees
GROUP BY department_id
All columns in SELECT clause which are not in group function
should be in group by clause
The GROUP BY column does not need to be in SELECT clause
Can group records based on multiple columns
SELECT department_id, job_id, avg(salary)
FROM employees
GROUP BY department_id, job_id


GROUP BY restrictions
Cannot use WHERE clause to restrict groups. It can only restrict
the rows.
Cannot use GROUP functions in WHERE clause
Restrict groups using HAVING clause
Following statement gives an error Group function is not
allowed here
SELECT department_id, avg(salary) FROM employees
WHERE avg(salary) > 500
GROUP BY department_id
Following statement give not a single-group function
SELECT department_id, avg(salary) FROM employees
Restricting Group Results
Use HAVING clause to restrict or exclude group results.
Following is the sequence of operations.
1. Rows are divided into groups
2. Group functions are applied
3. The groups which satisfy the HAVING clause are selected.

SELECT department_id, max(salary)
FROM employees
GROUP BY department_id
HAVING max(salary) > 10000

Sub Queries
Used in scenarios where the result of one query is used by another
query
Ex: SELECT LAST_NAME, FIRST_NAME FROM EMPLOYEES
WHERE SALARY > (SELECT SALARY FROM EMPLOYEES
WHERE LAST_NAME = Abel)
The inner query ( in RED) is executed once. The outer query, which is
the main query uses the result from inner query
You can use single-row operators =, >, <, >=, <=, <> for inner query
returning only single row. AKA. Single-row subquery
Use multi-row operators for multi-row subqueries. Ex. IN, ANY, ALL
Group functions can be used in sub queries
If a single-row operator is used for a subquery returning multiple rows,
it would result in Single-row subquery returns more than one row
error
The subquery may not return any rows. This needs to be taken into
consideration when dealing with sub queries

Multi-Row Operators in Sub
Queries
IN
SELECT last_name, first_name, department_id
FROM employees
WHERE salary IN (select min(salary) from employess group by
department_id)
ANY
SELECT last_name, first_name, department_id
FROM employees
WHERE salary > ANY (select salary from employess where job_id = IT)
and job_id <> IT
ALL
SELECT last_name, first_name, department_id
FROM employees
WHERE salary > ALL (select salary from employess where job_id = IT)
and job_id <> IT

EXISTS Clause
The EXISTS clause tests for the existence of rows in the
resultset for SUBQUERY
If a subquery row value is found the search will stop and the
condition is flagged as TRUE
If a subquery row value is not found the condition is flagged as
FALSE and the search continues.
EXISTS clause improves performance
SELECT LAST_NAME, FIRST_NAME, EMPLOYEE_ID FROM EMPLOYEES E1
WHERE EXISTS
(SELECT 'X' FROM EMPLOYEES WHERE MANAGER_ID =
E1.EMPLOYEE_ID)

Data Manipulation
Data Manipulation Language(DML) includes statement INSERT,
UPDATE, DELETE.
A logical group of DML statements represent a transaction
Use INSERT to insert new records into a table
UPDATE statement is used to update existing records in a table
DELETE deletes rows in the table
The changes made through DML statements are not posted to
the database until a COMMIT is issued.
A ROLLBACK would backout any changes done to the data. The
state of the database would go back to last COMMIT point.
ROLLBACK TO SAVEPOINT option rollback to the last
SAVEPOINT. A Savepoint is like a mile marker on the road


INSERT
INSERT is used to insert data into a table. Typical INSERT below
INSERT INTO departments(department_id, department_name,
manager_id, location_id)
Values (101, IT_DEPT,201, 500);
Enclose Characters and Dates in Single quotes. Can use
SYSDATE function for dates.
INSERT should provide values to all NOT NULL constraint
columns. The other columns may be defaulted to NULL
Can copy rows from one table into another table using SELECT
in INSERT statement.
INSERT into department_bkup
SELECT * FROM departments
UPDATE Statement
Modify existing rows in a table using UPDATE.
WHERE clause restricts the rows updated by the UPDATE
UPDATE employees
SET department_id = 170
WHERE employee_id = 102
If WHERE clause is omitted then all rows in the table are updated
Can use single-row subquery to assign a value
UPDATE employees
SET department_id = (SELECT department_id FROM employees WHERE
employee_id = 110)
WHERE employee_id = 102;
When updating foreign key columns, the updated value should be in
the parent table. If not, an integrity constraint error occurs

DELETE statement
Delete rows in a table using DELETE.
WHERE clause restricts the rows deleted by the DELETE
DELETE FROM employees
WHERE employee_id = 102
If WHERE clause is omitted then all rows in the table are
deleted
Can use single-row subquery to assign a value in WHERE clause
DELETE FROM employees
WHERE department_id = (SELECT department_id FROM employees
WHERE employee_id = 110)
Cannot delete a row in a table where one of the columns is a
foreign key in another table. An integrity constraint error occurs

Database Transaction
Consists of SELECT statements, DML statements which modify data
AND one DCL statement(COMMIT, ROLLBACK) or one DDL statement
Generally begins when the first DML statement is issued
Ends when a DCL is issued, a DDL is issued, user exits the session or
system crashes
COMMIT and ROLLBACK are Data Control statements which ensure
data consistency and group logical transactions together
COMMIT make data changes permanent.
ROLLBACK nullifies any data changes made and rolls back the database
to the last COMMIT point
SAVEPOINT allows developer to put a marker within a transaction
We can do a ROLLBACK to a particular named SAVEPOINT

Controlling Transaction
A Typical Transaction scenario looks like below

Database Objects
A list of Database Objects below
Each of these objects has a command to CREATE, ALTER, DROP
these Objects

Creating and Managing Tables
CREATE TABLE is used to create new table in Oracle
Specify the columns and the datatype and size of the columns
CREATE is a DDL statement
Ex: CREATE TABLE HR.employees
(employee_id NUMBER NOT NULL, last_name VARCHAR2(50), first_name
VARCHAR2(50), department_id NUMBER, salary NUMBER);
HR is a schema name and employees is the table name
DESCRIBE employees will show the table columns and datatype
Can create a table using SUBQUERY. Similar to INSERT using subquery
CREATE TABLE HR.employees_bkup AS
Select * from HR.employees;


Data Dictionary
Metadata: Oracle database has separate set of table to keep
information regarding user objects created.
SELECT * FROM ALL_TABLES WHERE table_name = EMPLOYEES
This metadata is called Data Dictionary.
There are 4 categories of Data Dictionary table. Each has its
own prefix
USER_, ALL_, DBA_, V$_
Datatypes
Following datatypes are used in defining COLUMNS

Tables
Use ALTER TABLE to add new column, modify datatype of
existing column or drop a column
ALTER TABLE employees ADD (hire_date DATE)
ALTER TABLE employees MODIFY (hire_date NUMBER)
ALTER TABLE employees DROP hire_date
DROP table to remove a table from
Once a DROP is issued all the data and table structure is lost.
We cannot ROLLBACK this statement
TRUNCATE TABLE deletes all the data in the table and releases
storage.
Data once deleted using TRUNCATE cannot be recovered using
ROLLBACK
Constraints
Constraints enforce rules at the table level.
They prevent deletion on tables if they are not met.
Constraints can be added at table creation or added seperately
using ADD CONSTRAINT clause
Following are some constraints used commonly

Adding Constraints
Constraint created at Table Creation
CREATE TABLE emp(
employee_id NUMBER,
first_name VARCHAR2(50),
last_name VARCHAR2(50) NOT NULL,
department_id NUMBER,
....
CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));

Constraint created afterwards using ADD CONSTRAINT
ALTER TABLE emp
ADD CONSTRAINT emp_dept_fk
FOREIGN KEY(department_id)
REFERENCES departments(department_id);

Topics Still to be coverd
VIEWS
SEQUENCES
INDEXES
GRANTS ON TABLES,VIEWS ETC
UNION OPERATORS
EXISTS

Views
A view is a logical subset of a table or combination of tables
A view does not have data on its own. It is a window to view table data
View are created as follows:
Create view it_emps_only as
Select * from employees where department_id = 100;
The select statement to create view can contain functions and group by
clauses
Two types of views. Simple views and Complex views
Simple views are based on only one table without functions and GROUP
BY clauses. Allows DML operations
Complex views are based on multiple tables and sometimes other
views also. NO DML operations.
Views
Use SELECT to view records in a view
SELECT * FROM it_emps_only;
Modify a view using CREATE OR REPLACE VIEW
CREATE OR REPLACE VIEW it_emps_only as
Select * from employees where department_id = 100 and
hire_date > 01-JAN-1990
Use WITH READ ONLY option at the time of creation to make a
view a READ ONLY view
Drop a view as follows
DROP VIEW it_emps_only
SEQUENCE
SEQUENCE automatically generates unique numbers are is used
for PRIMARY KEY columns
CREATE SEQUENCE emp_id_seq
START WITH 100 INCREMENT BY 2

INSERT INTO employees(emp_id, last_name, first_name) values
(emp_id_seq.nextval, Wathe,Sanjay);
SEQUENCE.NEXTVAL : gets the next number in the sequence
SEQUENCE.CURRVAL: gets the current sequence number
Use ALTER SEQUENCE to alter a sequence
Use DROP SEQUENCE to drop a sequence
INDEX
INDEX is a database object created on a table to speed up the
data retrieval from a table.
It is maintained automatically by the server
Similar to an index in a book
We can create a UNIQUE index, a NON-UNIQUE index, a
composite index for a table
A UNIQUE index is automatically created when a primary key or
unique key constraint are defined for a table
Index can be created on one or more table columns
CREATE INDEX emp_last_name_idx ON EMPLOYEES(last_name)
Used DROP INDEX to drop an index

GRANTS and SYNONYMS
Other user schemas do not have access to objects you created.
Use GRANT option to grant INSERT, UPDATE, DELETE on any
object you create to other users.
GRANT INSERT UPDATE DELETE ON EMPLOYEES;
Use REVOKE command to revoke any privileges
SYNONYMS allows users to create an alias name to objects in
other schemas
We can create a synonym on an object which has a lengthy
name
CREATE SYNONYM emp FOR HR.EMPLOYEES;
Use DROP SYNONYM to remove any synonyms

SET Operators
SET operators work on 2 or more disjoint SQL queries. They
combine the results from multiple SQL queries.

SET Operators
The SQL SELECT statements operated by SET operators should
have the same number of selected columns with identical
datatypes
UNION: Union operator returns results from both SQL querys
eliminating any duplicate values
UNION ALL: It performs the same operation as UNION without
eliminating any duplicates
INTERSECT: It only returns rows which are common in both the
query results
MINUS: The operator returns rows in table A which are not at
all in table B.
Conclusion
Its just a primer
More advanced features are available in Oracle Documentation

You might also like