SlideShare a Scribd company logo
1 of 16
Download to read offline
Computer Science Department
College of Computer Studies
Ateneo de Naga University
Database Management Systems
Second Semester SY 2008-09

Handout #1 – Oracle SQL Basics
Reference: Oracle Academic Initiative - Introduction to Oracle 9i SQL

I. Basic SQL

SELECT [DISTINCT] * {column | expression [alias], …}
FROM table;

Selecting All Column Rows

SELECT *
FROM departments;

Selecting Specific Columns

SELECT department_id, location_id
FROM departments;

Using Arithmetic Operators

SELECT last_name, salary, salary+300
FROM employees;

SELECT last_name, salary, 12*salary+100
FROM employees;

SELECT last_name, salary, 12*(salary+100)
FROM employees;

Using Column Aliases

SELECT last_name AS name, commission_pct comm.
FROM employees;

SELECT last_name “Name” , salary*12 “Annual Salary”
FROM employees;

Using the Concatenation Operator

SELECT last_name || job_id AS “Employees”
FROM employees;

SELECT last_name || ‘ is a ‘ || job_id AS “Employee Details”
FROM employees;

Eliminating Duplicate Rows

SELECT DISTINCT department_id
FROM employees;
Using the WHERE Clause

SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90;

Using Comparison Conditions

SELECT last_name, salary
FROM employees
WHERE salary <= 3000;

Using the BETWEEN Condition

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

Using the IN Condition

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

Using the LIKE Condition

SELECT first_name
FROM employees
WHERE first_name LIKE ‘S%’;

SELECT last_name
FROM employees
WHERE last_name LIKE ‘ o%’;

Using the NULL condition

SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL;

Using the AND Operator

SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
AND job_id LIKE ‘%MAN%’;

Using the OR Operator

SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
OR job_id LIKE ‘%MAN%’;

Using the NOT Operator

SELECT last_name, job_id
FROM employees
WHERE job_id NOT IN (‘IT_PROG’, ‘ST_CLERK’, ‘SA_REP’);
Rules of Precedence

SELECT last_name, job_id, salary
FROM employees
WHERE job_id = ‘SA_REP’
OR job_id = ‘AD_PRES’
AND salary > 15000;

Use parentheses to force priority

SELECT last_name, job_id, salary
FROM employees
WHERE (job_id = ‘SA_REP’
OR job_id = ‘AD_PRES’)
AND salary > 15000;

ORDER BY Clause

SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date;

Sorting in Descending Order

SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC;

Sorting by Multiple Columns

SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;

II. FUNCTIONS

Character Manipulation Functions

SELECT employee_id, last_name, department_id
FROM employees
WHERE LOWER(last_name) = ‘higgins’;
SELECT employee_id, CONCAT(first_name, last_name) NAME,
LENGTH last_name, INSTR(last_name, ‘a’),
FROM employees;

Number Functions

SELECT ROUND(45.923, 2), ROUND(45.923, 0),
ROUND(45.923, -1)
FROM dual;
SELECT TRUNC(45.923, 2), TRUNC(45.923),
TRUNC(45.923, -2)
FROM dual;
Using the MOD Function

SELECT last_name, salary, MOD(salary, 5000)
FROM employees
WHERE job_id = ‘SA_REP’;


Case Manipulation Functions

LOWER – converts mixed case or uppercase character strings to lowercase.
UPPER - converts mixed case or lowercase character strings to uppercase.
INITCAP – converts the first letter of each word to uppercase and remaining letters to lowercase.

Example:

LOWER(‘SQL Course’) . sql course
UPPER(‘SQL Course’) . SQL COURSE
INITCAP(‘SQL Course’) . Sql Course
SELECT ‘The job_id for ‘ || UPPER(last_name) || ‘ is ‘
|| LOWER(job_id) AS “EMPLOYEE DETAILS”
FROM employees;

Character Manipulation Functions

CONCAT – joins values together (you are limited to using two parameters with CONCAT).
SUBSTR – extracts a string of determined length.
LENGTH – shows the length of a string as a numeric value.
INSTR – finds numeric position of a named character.
LPAD – pads the character value right-justified.
RPAD – pads the character value left justified.
TRIM – trims heading or trailing characters.

Example:

CONCAT(‘Hello’, ‘World’) . HelloWorld
SUBSTR(‘HelloWorld,1,5) . Hello
LENGTH(‘HelloWorld’) . 10
INSTR(HelloWorld’, ‘W’) . 6
LPAD(salary,10,’*’) . *****24000
RPAD(salary,10,’*’) . 24000*****
TRIM(‘H’ FROM ‘HelloWorld’) . elloWorld
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH(last_name), INSTR(last_name, ‘a’) “Lastname contains ‘a’?”
FROM employees
WHERE SUBSTR(job_id, 4) = ‘REP’;

Working with Dates

SELECT last_name, hire_date
FROM employees
WHERE last_name LIKE ‘W%’;

Using Arithmetic Operators with Dates

SELECT last_name, (SYSDATE – hiredate) / 7 AS WEEKS
FROM employees
WHERE department_id = 90;
Date Functions

SELECT employee_id, hire_date,
MONTHS_BETWEEN(SYSDATE, hire_date) TENURE,
ADD_MONTHS(hire_date, 6) REVIEW,
NEXT_DAY(hire_date, ‘FRIDAY’), LAST_DAY(hire_date)
FROM employees;
SELECT employee_id, hire_date,
ROUND(hire_date, ‘MONTH’), TRUNC(hire_date, ‘MONTH’)
FROM employees
WHERE hire_date LIKE ‘%97’;

CONVERSION FUNCTIONS
Elements of the Date Format Model

YYYY – full year in numbers
YEAR – year spelled out
MM – two-digit value for month
MONTH – full name of the month
MON – three-letter abbreviation of the month
DY – three-day abbreviation of the day of the week
DAY – full name of the day of the week
DD – numeric day of the month
AM or PM – meridian indicator
A.M. or P.M. – meridian indicator with periods
HH or HH12 or HH24 – hour of day, or hour(1-12), or hour(0-23)
MI – minute (0-59)
SS – second(0-59)
SSSSS – seconds past midnight(0-86399)
/ . , – punctuation is reproduced in the result
“of the” – quoted string is reproduced in the result
TH – ordinal number (for example, DDTH for 4TH)
SP – spelled out number (for example, DDSP for FOUR)
SPTH or THSP – spelled out ordinal numbers (for example, DDSPTH for FOURTH)

Using the TO_CHAR Function with Dates

SELECT last_name,
TO_CHAR(hire_date, ‘fmDD Month YYYY’) AS HIREDATE
FROM employees;
SELECT last_name,
TO_CHAR(hire_date, ‘fmDdspth “of” Month YYYY fmHH:MI:SS AM’) HIREDATE
FROM employees

Number Format Elements

9 – represents a number
0 – forces a zero to be displayed
$ – places a floating dollar sign
L – uses the floating local currency symbol
. – prints a decimal point
, – prints a thousand indicator

Using the TO_CHAR Function with Numbers

SELECT TO_CHAR(salary, ‘$99,999.00’) SALARY
FROM employees;
GENERAL FUNCTIONS

These functions work with any data type and pertain to using nulls
NVL (expr1, expr2) – converts a null value to an actual value.
NVL2(expr1, expr2, expr3) – if expr1 is not null, nvl2 returns expr2. if expr1 is null, nvl2 returns expr3.
NULLIF(expr1, expr2) – compares two expressions and returns null if they are equal, or the first expression if
they are not equal.
COALESCE(expr1, expr2, …, exprn) – returns the first non-null expression in the expression list.

Using the NVL Function

SELECT last_name,
NVL(TO_CHAR(manager_id), ‘No Manager’)
FROM employees
WHERE manager_id IS NULL;

Using the NVL2 Function

SELECT last_name, salary, commission_pct,
NVL2(commission_pct, ‘Salary+Commission’, ‘Salary’) INCOME
FROM employees;

Using the NULLIF Function

SELECT first_name, LENGTH(first_name) “expr1”,
last_name, LENGTH(last_name) “expr2”,
NULLIF(length(first_name), LENGTH(last_name)) result
FROM employees;

Using the COALESCE Function

SELECT last_name,
COALESCE(commission_pct, salary, 10) comm.
FROM employees
ORDER BY commission_pct;

CONDITIONAL EXPRESSIONS

Facilitates the conditional inquiries by doing the work of an IF-THEN-ELSE statement.

Using the CASE Expression

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 “Revised Salary”
FROM employees;

Using the DECODE Function

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;
III. DISPLAYING DATA FROM MULTIPLE TABLES

Retrieving Records with Equijoins

SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
departments.location_id
FROM employees, departments
WHERE employees.department_id = departments.department_id;

Using Table Aliases

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;

Joining More than Two Tables

SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;

Non-Equijoins

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;

Outer Joins

SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id;
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id (+) = d.department_id;

Joining a Table to Itself

SELECT w.last_name || ' works for ' || m.last_name
FROM employees w, employees m
WHERE w.manager_id = m.employee_id;

Creating Cross Joins

SELECT last_name, department_name
FROM employees
CROSS JOIN departments;

Natural Joins

It selects rows from tables that have equal values in all matched columns. It can also be written using an
equijoin.

SELECT department_id, department_name, location_id, city
FROM departments
NATURAL JOIN locations;

The USING Clause

If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be
modified with the USING clause to specify the columns that should be used for an equijoin.

SELECT e.employee_id, e.last_name, d.location_id
FROM employees e JOIN departments d
USING (department_id);

The ON Clause

The join condition for the natural join is basically an equijoin of all columns with the same name. To specify
arbitrary conditions or specify columns to join, the ON clause is used.

SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);

Three-Way Joins with the ON Clause

SELECT employee_id, city, department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;

Left Outer Join

SELECT e.last_name, e.department_id, d.department_name
FROM employees e
LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);
This query retrieves all rows in the EMPLOYEES table, which is the left table even if there is no match in the
departments table.

Right Outer Join

SELECT e.last_name, e.department_id, d.department_name
FROM employees e
RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);
This query retrieves all rows in the DEPARTMENTS table, which is the right table even if there is no match in the
EMPLOYEES table.

Full Outer Join
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
FULL OUTER JOIN departments d
ON (e.department_id = d.department_id);
This query retrieves all rows in the EMPLOYEES table, even if there is no match in the
DEPARTMENTS table. It also retrieves all rows in the DEPARTMENTS table, even if there is no
match in the EMPLOYEES table.
IV. GROUP FUNCTIONS

GROUP FUNCTIONS

SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE ‘%REP%’;

SELECT MIN(hire_date), MAX(hire_date)
FROM employees;
SELECT COUNT(*)
FROM employees
WHERE department_id = 50;

SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;

SELECT COUNT(department_id)
FROM employees;

SELECT COUNT(DISTINCT department_id)
FROM employees;

All group functions ignore null values in the column. In the example, the average is calculated based only on the
rows in the table where a valid value is stored in the COMMISSION_PCT column.

SELECT AVG(commission_pct)
FROM employees;

The NVL function forces group functions to include null values. In the example, the average is calculated based
on all rows in the table, regardless of whether null values are stored in the COMMISSION_PCT column.

SELECT AVG(NVL(commission_pct, 0))
FROM employees;

Using the GROUP BY Clause

SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY department_id, job_id;

SELECT department_id, COUNT(last_name)
FROM employees
GROUP BY department_id;

Using the HAVING Clause

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

SELECT job_id, SUM(salary) “Payroll”
FROM employees
WHERE job_id NOT LIKE ‘%rep%’
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);

Nesting Group Functions

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;

V. SUBQUERIES

Types of Subqueries:

Single-row subquery
returns
ST_CLERK

Multiple-row subquery
returns
ST_CLERK
SA_MAN

Single-Row Subqueries

SELECT last_name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE employee_id = 141);
SELECT last_name, job_id, salary
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE employee_id = 141)
AND salary >
(SELECT salary
FROM employees
WHERE employee_id = 143);

Using Group Functions in a Subquery

SELECT last_name, job_id, salary
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees);

The HAVING Clause with Subqueries

SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
Main query
Subquery

Multiple-Row Subqueries
Find the employees who earn the same salary as the minimum salary for each department.

SELECT last_name, salary, department_id
FROM employees
WHERE salary IN
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

Display the employees who are not IT programmers and whose salary is less than that of
any IT programmer.

SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = ‘IT_PROG’)
AND job_id <> ‘IT_PROG’;

Display the employees whose salary is less than the salary of all employees with a job ID
of IT_PROG and whose job is not IT_PROG.

SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = ‘IT_PROG’)
AND job_id <> ‘IT_PROG’;

VI. DATA MANIPULATION LANGUAGE

Insert a new row containing values for each column

INSERT INTO departments (department_id, department_name, manager_id, location_id)
VALUES (70, ‘Public Relations’, 100, 1700);

Inserting rows with NULL values
Implicit method: Omit the column from the column list.

INSERT INTO departments (department_id, department_name)
VALUES (30, ‘Purchasing’);

Explicit method: specify the NULL keyword in the VALUES clause.

INSERT INTO departments
VALUES (100, ‘Finance’, NULL, NULL);

Inserting special values

INSERT INTO employees (employee_id, first_name, last_name, email, phone_number,
hire_date, job_id, salary, commission_pct, manager_id,
department_id)
VALUES (113, ‘Louis’, ‘Popp’, ‘lpopp@yahoo.com’, ‘515-124-4567’, SYSDATE,
‘AC_ACCOUNT’, 6900, NULL, 205, 100)

Inserting Specific Date Values

INSERT INTO employees
VALUES (114, ‘Den’, ‘Raphaealy’, ‘draphael@yahoo.com’, ‘515-127-4561’,
TO_DATE(‘FEB 3, 1999’, ‘MON DD, YYYY’), ‘AC_ACCOUNT’, 11000,
NULL, 100, 30);

Creating a script
Use substitution in a SQL statement to prompt for values. & is a placeholder for the
variable value.

INSERT INTO departments (department_id, department_name, location_id)
VALUES (&department_id, ‘&department_name’, &location_id)

Modify existing rows
Specific row or rows are modified if you are specify the WHERE clause

UPDATE employees
SET department_id = 70
WHERE employee_id = 113;

Updating Two Columns with a subquery

UPDATE employees
SET job_id = (SELECT job_id
FROM employees
HERE employee_id = 205),
Salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;

Deleting Rows from a Table

DELETE FROM employees
WHERE employee_id = 114;
DELETE FROM departments
WHERE department_id IN (30, 40)
DELETE FROM employees
WHERE department_id =
(SELECT department_id
FROM departments
WHERE department_name LIKE ‘%Public%’);

VI. CREATING AND MANAGING TABLES
Naming Rules

Table names and column names:
• Must begin with a letter
• Must be 1-30 characters long
• Must contain only A-Z, a-z, 0-9, _, $, and #
• Must not duplicate the name of another object owned by the same user
• Must not be an Oracle server reserved word
Creating Tables

CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));

Confirm table creation

DESCRIBE dept;

Data Types:

Data Type Description

VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data up to 2 gigabytes
CLOB Character data up to 4 gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an external file; up to 4 gigabytes
ROWID A 64 base number system representing the unique address of row in its table

Creating a Table by Using a Subquery

CREATE TABLE dept80
AS SELECT employee_id, last_name, salary * 12 ANNUAL_SALARY, hire_date
FROM employees
WHERE department_id = 80;

Adding a Column

ALTER TABLE dept80
ADD (job_id VARCHAR2(9));

Modifying a Column

ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));

Dropping a Column

ALTER TABLE dept80
DROP COLUMN job_id;

Dropping a Table

DROP TABLE dept80;

Changing the name of a table

RENAME dept TO detail_dept;
VII. CONSTRAINTS

What are constraints?
• Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table if there are dependencies.

Data Integrity Constraints

Constraint Description

NOT NULL Specifies that the column cannot contain a null value
UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes and enforces a foreign key relationship between the column and a column of the
referenced table
CHECK Specifies a condition that must be true

Constraint Guidelines
• Name a constraint or the Oracle server generates a name by using the SYS_Cn format.
• Create a constraint either:
        o At the same time as the table is created, or
        o After the table has been created
• Define the constraint at the column or table level.
• View a constraint in the data dictionary

Defining Constraints
Constraint Level Description

Column References a single column and is defined within a specification for the owning column; can define any
type of integrity constraint

Table References one or more columns and is defined separately from the definitions of the columns in the
table; can define any type of constraint except NOT NULL

Column constraint level

Column [CONSTRAINT constraint_name] constraint_type,
Table constraint level
column, …
[CONSTRAINT constraint_name] constraint_type
(column, …),

The NOT NULL Constraint

CREATE TABLE employees2 (
employee_id NUMBER(6),

last_name VARCHAR2(25) NOT NULL, System named

email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),

hire_date DATE
CONSTRAINT emp_hire_date_nn User named
NOT NULL,
…
The UNIQUE Constraint

CREATE TABLE employees2 (
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE
CONSTRAINT emp_hire_date_nn
NOT NULL,
…
CONSTRAINT emp_email_uk UNIQUE(email));
The PRIMARY KEY Constraint

CREATE TABLE departments2 (
department_id NUMBER(4),
department_name VARCHAR2(30)
CONSTRAINT dept_name NOT NULL,
manager_id NUMBER(6),
location_id NUMBER(4),

CONTRSAINT dept_id_pk PRIMARY KEY(department_id));
The FOREIGN KEY Constraint

CREATE TABLE employees2 (
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE
CONSTRAINT emp_hire_date_nn
NOT NULL,
…
department_id NUMBER(4),

CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments2(department_id),

CONSTRAINT emp_email_uk UNIQUE(email));

The CHECK Constraint

CREATE TABLE employees2 (
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),

salary NUMBER(8,2)
CONSTRAINT emp_salary_min CHECK (salary > 0),

commission_pct NUMBER(2,2),
hire_date DATE
CONSTRAINT emp_hire_date_nn
NOT NULL,
…
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
` REFERENCES departments2(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));

Adding a Constraint

ALTER TABLE employees
ADD CONSTRAINT emp_manager_fk
FOREIGN KEY(manager_id)
REFERENCES employees(employee_id);

Dropping a Constraint

ALTER TABLE employees
DROP CONSTRAINT emp_manager_fk;
ALTER TABLE departments2
DROP PRIMARY KEY CASCADE;
The CASCADE option of the DROP clause causes any dependent constraints also to be
dropped.

Disabling Constraints

ALTER TABLE employees
DISABLE CONSTRAINT emp_emp_id_pk CASCADE;

Enabling Constraints

ALTER TABLE employees
DISABLE CONSTRAINT emp_emp_id_pk;

More Related Content

What's hot

Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answersvijaybusu
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sqlCharan Reddy
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankMd Mudassir
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answersMichael Belete
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Achmad Solichin
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answersNawaz Sk
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group FunctionsSalman Memon
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and OperatorsMohan Kumar.R
 

What's hot (20)

Sql task
Sql taskSql task
Sql task
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question Bank
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answers
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Ref cursor
Ref cursorRef cursor
Ref cursor
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
All questions
All questionsAll questions
All questions
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Sql queires
Sql queiresSql queires
Sql queires
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 

Viewers also liked (11)

Sql basics
Sql  basicsSql  basics
Sql basics
 
Sql basics joi ns and common commands (1)
Sql basics  joi ns and common commands (1)Sql basics  joi ns and common commands (1)
Sql basics joi ns and common commands (1)
 
Sql Basic Selects
Sql Basic SelectsSql Basic Selects
Sql Basic Selects
 
Lecture 07 - Basic SQL
Lecture 07 - Basic SQLLecture 07 - Basic SQL
Lecture 07 - Basic SQL
 
Sql basics
Sql basicsSql basics
Sql basics
 
1. SQL Basics - Introduction
1. SQL Basics - Introduction1. SQL Basics - Introduction
1. SQL Basics - Introduction
 
Les01 Writing Basic Sql Statements
Les01 Writing Basic Sql StatementsLes01 Writing Basic Sql Statements
Les01 Writing Basic Sql Statements
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
Tables And SQL basics
Tables And SQL basicsTables And SQL basics
Tables And SQL basics
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMS
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 

Similar to Basic Sql Handouts

Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Thuan Nguyen
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankpptnewrforce
 
Sql task answers
Sql task answersSql task answers
Sql task answersNawaz Sk
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Achmad Solichin
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting dataSyed Zaid Irshad
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxmetriohanzel
 
Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05Thuan Nguyen
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSgaurav koriya
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricksYanli Liu
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Achmad Solichin
 
e computer notes - Single row functions
e computer notes - Single row functionse computer notes - Single row functions
e computer notes - Single row functionsecomputernotes
 

Similar to Basic Sql Handouts (20)

Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03Oracle - Program with PL/SQL - Lession 03
Oracle - Program with PL/SQL - Lession 03
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
Sql task answers
Sql task answersSql task answers
Sql task answers
 
Les02
Les02Les02
Les02
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Les02
Les02Les02
Les02
 
Oracle SQL
Oracle SQLOracle SQL
Oracle SQL
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
Chapter08
Chapter08Chapter08
Chapter08
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting data
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Oracle
OracleOracle
Oracle
 
Les03
Les03Les03
Les03
 
Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05Oracle - Program with PL/SQL - Lession 05
Oracle - Program with PL/SQL - Lession 05
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
BIS05 Introduction to SQL
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQL
 
Les03
Les03Les03
Les03
 
e computer notes - Single row functions
e computer notes - Single row functionse computer notes - Single row functions
e computer notes - Single row functions
 

Recently uploaded

High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsHigh Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Indore Real Estate Market Trends Report.pdf
Indore Real Estate Market Trends Report.pdfIndore Real Estate Market Trends Report.pdf
Indore Real Estate Market Trends Report.pdfSaviRakhecha1
 
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...dipikadinghjn ( Why You Choose Us? ) Escorts
 
03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptxFinTech Belgium
 
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...Call Girls in Nagpur High Profile
 
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...ssifa0344
 
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure serviceWhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure servicePooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceanilsa9823
 
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Pooja Nehwal
 
The Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdfThe Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdfGale Pooley
 
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptxFinTech Belgium
 
The Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdfThe Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdfGale Pooley
 
The Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdfThe Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdfGale Pooley
 
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...ssifa0344
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfGale Pooley
 
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...Call Girls in Nagpur High Profile
 

Recently uploaded (20)

High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsHigh Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
High Class Call Girls Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Indore Real Estate Market Trends Report.pdf
Indore Real Estate Market Trends Report.pdfIndore Real Estate Market Trends Report.pdf
Indore Real Estate Market Trends Report.pdf
 
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...
VIP Call Girl in Mira Road 💧 9920725232 ( Call Me ) Get A New Crush Everyday ...
 
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
 
03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx
 
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
 
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
 
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
 
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure serviceWhatsApp 📞 Call : 9892124323  ✅Call Girls In Chembur ( Mumbai ) secure service
WhatsApp 📞 Call : 9892124323 ✅Call Girls In Chembur ( Mumbai ) secure service
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
 
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
 
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
 
The Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdfThe Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdf
 
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
 
The Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdfThe Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdf
 
The Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdfThe Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdf
 
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdf
 
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...
 

Basic Sql Handouts

  • 1. Computer Science Department College of Computer Studies Ateneo de Naga University Database Management Systems Second Semester SY 2008-09 Handout #1 – Oracle SQL Basics Reference: Oracle Academic Initiative - Introduction to Oracle 9i SQL I. Basic SQL SELECT [DISTINCT] * {column | expression [alias], …} FROM table; Selecting All Column Rows SELECT * FROM departments; Selecting Specific Columns SELECT department_id, location_id FROM departments; Using Arithmetic Operators SELECT last_name, salary, salary+300 FROM employees; SELECT last_name, salary, 12*salary+100 FROM employees; SELECT last_name, salary, 12*(salary+100) FROM employees; Using Column Aliases SELECT last_name AS name, commission_pct comm. FROM employees; SELECT last_name “Name” , salary*12 “Annual Salary” FROM employees; Using the Concatenation Operator SELECT last_name || job_id AS “Employees” FROM employees; SELECT last_name || ‘ is a ‘ || job_id AS “Employee Details” FROM employees; Eliminating Duplicate Rows SELECT DISTINCT department_id FROM employees;
  • 2. Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90; Using Comparison Conditions SELECT last_name, salary FROM employees WHERE salary <= 3000; Using the BETWEEN Condition SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500; Using the IN Condition SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN (100, 101, 201); Using the LIKE Condition SELECT first_name FROM employees WHERE first_name LIKE ‘S%’; SELECT last_name FROM employees WHERE last_name LIKE ‘ o%’; Using the NULL condition SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL; Using the AND Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 AND job_id LIKE ‘%MAN%’; Using the OR Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 OR job_id LIKE ‘%MAN%’; Using the NOT Operator SELECT last_name, job_id FROM employees WHERE job_id NOT IN (‘IT_PROG’, ‘ST_CLERK’, ‘SA_REP’);
  • 3. Rules of Precedence SELECT last_name, job_id, salary FROM employees WHERE job_id = ‘SA_REP’ OR job_id = ‘AD_PRES’ AND salary > 15000; Use parentheses to force priority SELECT last_name, job_id, salary FROM employees WHERE (job_id = ‘SA_REP’ OR job_id = ‘AD_PRES’) AND salary > 15000; ORDER BY Clause SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date; Sorting in Descending Order SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC; Sorting by Multiple Columns SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC; II. FUNCTIONS Character Manipulation Functions SELECT employee_id, last_name, department_id FROM employees WHERE LOWER(last_name) = ‘higgins’; SELECT employee_id, CONCAT(first_name, last_name) NAME, LENGTH last_name, INSTR(last_name, ‘a’), FROM employees; Number Functions SELECT ROUND(45.923, 2), ROUND(45.923, 0), ROUND(45.923, -1) FROM dual; SELECT TRUNC(45.923, 2), TRUNC(45.923), TRUNC(45.923, -2) FROM dual;
  • 4. Using the MOD Function SELECT last_name, salary, MOD(salary, 5000) FROM employees WHERE job_id = ‘SA_REP’; Case Manipulation Functions LOWER – converts mixed case or uppercase character strings to lowercase. UPPER - converts mixed case or lowercase character strings to uppercase. INITCAP – converts the first letter of each word to uppercase and remaining letters to lowercase. Example: LOWER(‘SQL Course’) . sql course UPPER(‘SQL Course’) . SQL COURSE INITCAP(‘SQL Course’) . Sql Course SELECT ‘The job_id for ‘ || UPPER(last_name) || ‘ is ‘ || LOWER(job_id) AS “EMPLOYEE DETAILS” FROM employees; Character Manipulation Functions CONCAT – joins values together (you are limited to using two parameters with CONCAT). SUBSTR – extracts a string of determined length. LENGTH – shows the length of a string as a numeric value. INSTR – finds numeric position of a named character. LPAD – pads the character value right-justified. RPAD – pads the character value left justified. TRIM – trims heading or trailing characters. Example: CONCAT(‘Hello’, ‘World’) . HelloWorld SUBSTR(‘HelloWorld,1,5) . Hello LENGTH(‘HelloWorld’) . 10 INSTR(HelloWorld’, ‘W’) . 6 LPAD(salary,10,’*’) . *****24000 RPAD(salary,10,’*’) . 24000***** TRIM(‘H’ FROM ‘HelloWorld’) . elloWorld SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH(last_name), INSTR(last_name, ‘a’) “Lastname contains ‘a’?” FROM employees WHERE SUBSTR(job_id, 4) = ‘REP’; Working with Dates SELECT last_name, hire_date FROM employees WHERE last_name LIKE ‘W%’; Using Arithmetic Operators with Dates SELECT last_name, (SYSDATE – hiredate) / 7 AS WEEKS FROM employees WHERE department_id = 90;
  • 5. Date Functions SELECT employee_id, hire_date, MONTHS_BETWEEN(SYSDATE, hire_date) TENURE, ADD_MONTHS(hire_date, 6) REVIEW, NEXT_DAY(hire_date, ‘FRIDAY’), LAST_DAY(hire_date) FROM employees; SELECT employee_id, hire_date, ROUND(hire_date, ‘MONTH’), TRUNC(hire_date, ‘MONTH’) FROM employees WHERE hire_date LIKE ‘%97’; CONVERSION FUNCTIONS Elements of the Date Format Model YYYY – full year in numbers YEAR – year spelled out MM – two-digit value for month MONTH – full name of the month MON – three-letter abbreviation of the month DY – three-day abbreviation of the day of the week DAY – full name of the day of the week DD – numeric day of the month AM or PM – meridian indicator A.M. or P.M. – meridian indicator with periods HH or HH12 or HH24 – hour of day, or hour(1-12), or hour(0-23) MI – minute (0-59) SS – second(0-59) SSSSS – seconds past midnight(0-86399) / . , – punctuation is reproduced in the result “of the” – quoted string is reproduced in the result TH – ordinal number (for example, DDTH for 4TH) SP – spelled out number (for example, DDSP for FOUR) SPTH or THSP – spelled out ordinal numbers (for example, DDSPTH for FOURTH) Using the TO_CHAR Function with Dates SELECT last_name, TO_CHAR(hire_date, ‘fmDD Month YYYY’) AS HIREDATE FROM employees; SELECT last_name, TO_CHAR(hire_date, ‘fmDdspth “of” Month YYYY fmHH:MI:SS AM’) HIREDATE FROM employees Number Format Elements 9 – represents a number 0 – forces a zero to be displayed $ – places a floating dollar sign L – uses the floating local currency symbol . – prints a decimal point , – prints a thousand indicator Using the TO_CHAR Function with Numbers SELECT TO_CHAR(salary, ‘$99,999.00’) SALARY FROM employees;
  • 6. GENERAL FUNCTIONS These functions work with any data type and pertain to using nulls NVL (expr1, expr2) – converts a null value to an actual value. NVL2(expr1, expr2, expr3) – if expr1 is not null, nvl2 returns expr2. if expr1 is null, nvl2 returns expr3. NULLIF(expr1, expr2) – compares two expressions and returns null if they are equal, or the first expression if they are not equal. COALESCE(expr1, expr2, …, exprn) – returns the first non-null expression in the expression list. Using the NVL Function SELECT last_name, NVL(TO_CHAR(manager_id), ‘No Manager’) FROM employees WHERE manager_id IS NULL; Using the NVL2 Function SELECT last_name, salary, commission_pct, NVL2(commission_pct, ‘Salary+Commission’, ‘Salary’) INCOME FROM employees; Using the NULLIF Function SELECT first_name, LENGTH(first_name) “expr1”, last_name, LENGTH(last_name) “expr2”, NULLIF(length(first_name), LENGTH(last_name)) result FROM employees; Using the COALESCE Function SELECT last_name, COALESCE(commission_pct, salary, 10) comm. FROM employees ORDER BY commission_pct; CONDITIONAL EXPRESSIONS Facilitates the conditional inquiries by doing the work of an IF-THEN-ELSE statement. Using the CASE Expression 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 “Revised Salary” FROM employees; Using the DECODE Function 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;
  • 7. III. DISPLAYING DATA FROM MULTIPLE TABLES Retrieving Records with Equijoins SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id; Using Table Aliases 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; Joining More than Two Tables SELECT e.last_name, d.department_name, l.city FROM employees e, departments d, locations l WHERE e.department_id = d.department_id AND d.location_id = l.location_id; Non-Equijoins 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; Outer Joins SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id; SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id (+) = d.department_id; Joining a Table to Itself SELECT w.last_name || ' works for ' || m.last_name FROM employees w, employees m WHERE w.manager_id = m.employee_id; Creating Cross Joins SELECT last_name, department_name FROM employees CROSS JOIN departments; Natural Joins It selects rows from tables that have equal values in all matched columns. It can also be written using an equijoin. SELECT department_id, department_name, location_id, city FROM departments
  • 8. NATURAL JOIN locations; The USING Clause If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an equijoin. SELECT e.employee_id, e.last_name, d.location_id FROM employees e JOIN departments d USING (department_id); The ON Clause The join condition for the natural join is basically an equijoin of all columns with the same name. To specify arbitrary conditions or specify columns to join, the ON clause is used. SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id); Three-Way Joins with the ON Clause SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; Left Outer Join SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id); This query retrieves all rows in the EMPLOYEES table, which is the left table even if there is no match in the departments table. Right Outer Join SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id); This query retrieves all rows in the DEPARTMENTS table, which is the right table even if there is no match in the EMPLOYEES table. Full Outer Join SELECT e.last_name, e.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id); This query retrieves all rows in the EMPLOYEES table, even if there is no match in the DEPARTMENTS table. It also retrieves all rows in the DEPARTMENTS table, even if there is no match in the EMPLOYEES table.
  • 9. IV. GROUP FUNCTIONS GROUP FUNCTIONS SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE job_id LIKE ‘%REP%’; SELECT MIN(hire_date), MAX(hire_date) FROM employees; SELECT COUNT(*) FROM employees WHERE department_id = 50; SELECT COUNT(commission_pct) FROM employees WHERE department_id = 80; SELECT COUNT(department_id) FROM employees; SELECT COUNT(DISTINCT department_id) FROM employees; All group functions ignore null values in the column. In the example, the average is calculated based only on the rows in the table where a valid value is stored in the COMMISSION_PCT column. SELECT AVG(commission_pct) FROM employees; The NVL function forces group functions to include null values. In the example, the average is calculated based on all rows in the table, regardless of whether null values are stored in the COMMISSION_PCT column. SELECT AVG(NVL(commission_pct, 0)) FROM employees; Using the GROUP BY Clause SELECT department_id, job_id, SUM(salary) FROM employees GROUP BY department_id, job_id; SELECT department_id, COUNT(last_name) FROM employees GROUP BY department_id; Using the HAVING Clause SELECT department_id, MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary) > 10000; SELECT job_id, SUM(salary) “Payroll” FROM employees WHERE job_id NOT LIKE ‘%rep%’ GROUP BY job_id
  • 10. HAVING SUM(salary) > 13000 ORDER BY SUM(salary); Nesting Group Functions SELECT MAX(AVG(salary)) FROM employees GROUP BY department_id; V. SUBQUERIES Types of Subqueries: Single-row subquery returns ST_CLERK Multiple-row subquery returns ST_CLERK SA_MAN Single-Row Subqueries SELECT last_name, job_id FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE employee_id = 141); SELECT last_name, job_id, salary FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE employee_id = 141) AND salary > (SELECT salary FROM employees WHERE employee_id = 143); Using Group Functions in a Subquery SELECT last_name, job_id, salary FROM employees WHERE salary = (SELECT MIN(salary) FROM employees); The HAVING Clause with Subqueries SELECT department_id, MIN(salary) FROM employees GROUP BY department_id HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE department_id = 50);
  • 11. Main query Subquery Multiple-Row Subqueries Find the employees who earn the same salary as the minimum salary for each department. SELECT last_name, salary, department_id FROM employees WHERE salary IN (SELECT MIN(salary) FROM employees GROUP BY department_id); Display the employees who are not IT programmers and whose salary is less than that of any IT programmer. SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < ANY (SELECT salary FROM employees WHERE job_id = ‘IT_PROG’) AND job_id <> ‘IT_PROG’; Display the employees whose salary is less than the salary of all employees with a job ID of IT_PROG and whose job is not IT_PROG. SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < ALL (SELECT salary FROM employees WHERE job_id = ‘IT_PROG’) AND job_id <> ‘IT_PROG’; VI. DATA MANIPULATION LANGUAGE Insert a new row containing values for each column INSERT INTO departments (department_id, department_name, manager_id, location_id) VALUES (70, ‘Public Relations’, 100, 1700); Inserting rows with NULL values Implicit method: Omit the column from the column list. INSERT INTO departments (department_id, department_name) VALUES (30, ‘Purchasing’); Explicit method: specify the NULL keyword in the VALUES clause. INSERT INTO departments VALUES (100, ‘Finance’, NULL, NULL); Inserting special values INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id,
  • 12. department_id) VALUES (113, ‘Louis’, ‘Popp’, ‘lpopp@yahoo.com’, ‘515-124-4567’, SYSDATE, ‘AC_ACCOUNT’, 6900, NULL, 205, 100) Inserting Specific Date Values INSERT INTO employees VALUES (114, ‘Den’, ‘Raphaealy’, ‘draphael@yahoo.com’, ‘515-127-4561’, TO_DATE(‘FEB 3, 1999’, ‘MON DD, YYYY’), ‘AC_ACCOUNT’, 11000, NULL, 100, 30); Creating a script Use substitution in a SQL statement to prompt for values. & is a placeholder for the variable value. INSERT INTO departments (department_id, department_name, location_id) VALUES (&department_id, ‘&department_name’, &location_id) Modify existing rows Specific row or rows are modified if you are specify the WHERE clause UPDATE employees SET department_id = 70 WHERE employee_id = 113; Updating Two Columns with a subquery UPDATE employees SET job_id = (SELECT job_id FROM employees HERE employee_id = 205), Salary = (SELECT salary FROM employees WHERE employee_id = 205) WHERE employee_id = 114; Deleting Rows from a Table DELETE FROM employees WHERE employee_id = 114; DELETE FROM departments WHERE department_id IN (30, 40) DELETE FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE department_name LIKE ‘%Public%’); VI. CREATING AND MANAGING TABLES Naming Rules Table names and column names: • Must begin with a letter • Must be 1-30 characters long • Must contain only A-Z, a-z, 0-9, _, $, and # • Must not duplicate the name of another object owned by the same user • Must not be an Oracle server reserved word
  • 13. Creating Tables CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13)); Confirm table creation DESCRIBE dept; Data Types: Data Type Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data up to 2 gigabytes CLOB Character data up to 4 gigabytes RAW and LONG RAW Raw binary data BLOB Binary data up to 4 gigabytes BFILE Binary data stored in an external file; up to 4 gigabytes ROWID A 64 base number system representing the unique address of row in its table Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary * 12 ANNUAL_SALARY, hire_date FROM employees WHERE department_id = 80; Adding a Column ALTER TABLE dept80 ADD (job_id VARCHAR2(9)); Modifying a Column ALTER TABLE dept80 MODIFY (last_name VARCHAR2(30)); Dropping a Column ALTER TABLE dept80 DROP COLUMN job_id; Dropping a Table DROP TABLE dept80; Changing the name of a table RENAME dept TO detail_dept;
  • 14. VII. CONSTRAINTS What are constraints? • Constraints enforce rules at the table level. • Constraints prevent the deletion of a table if there are dependencies. Data Integrity Constraints Constraint Description NOT NULL Specifies that the column cannot contain a null value UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table PRIMARY KEY Uniquely identifies each row of the table FOREIGN KEY Establishes and enforces a foreign key relationship between the column and a column of the referenced table CHECK Specifies a condition that must be true Constraint Guidelines • Name a constraint or the Oracle server generates a name by using the SYS_Cn format. • Create a constraint either: o At the same time as the table is created, or o After the table has been created • Define the constraint at the column or table level. • View a constraint in the data dictionary Defining Constraints Constraint Level Description Column References a single column and is defined within a specification for the owning column; can define any type of integrity constraint Table References one or more columns and is defined separately from the definitions of the columns in the table; can define any type of constraint except NOT NULL Column constraint level Column [CONSTRAINT constraint_name] constraint_type, Table constraint level column, … [CONSTRAINT constraint_name] constraint_type (column, …), The NOT NULL Constraint CREATE TABLE employees2 ( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, System named email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE CONSTRAINT emp_hire_date_nn User named NOT NULL, …
  • 15. The UNIQUE Constraint CREATE TABLE employees2 ( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL, … CONSTRAINT emp_email_uk UNIQUE(email)); The PRIMARY KEY Constraint CREATE TABLE departments2 ( department_id NUMBER(4), department_name VARCHAR2(30) CONSTRAINT dept_name NOT NULL, manager_id NUMBER(6), location_id NUMBER(4), CONTRSAINT dept_id_pk PRIMARY KEY(department_id)); The FOREIGN KEY Constraint CREATE TABLE employees2 ( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL, … department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments2(department_id), CONSTRAINT emp_email_uk UNIQUE(email)); The CHECK Constraint CREATE TABLE employees2 ( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2) CONSTRAINT emp_salary_min CHECK (salary > 0), commission_pct NUMBER(2,2), hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL, … department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
  • 16. ` REFERENCES departments2(department_id), CONSTRAINT emp_email_uk UNIQUE(email)); Adding a Constraint ALTER TABLE employees ADD CONSTRAINT emp_manager_fk FOREIGN KEY(manager_id) REFERENCES employees(employee_id); Dropping a Constraint ALTER TABLE employees DROP CONSTRAINT emp_manager_fk; ALTER TABLE departments2 DROP PRIMARY KEY CASCADE; The CASCADE option of the DROP clause causes any dependent constraints also to be dropped. Disabling Constraints ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk CASCADE; Enabling Constraints ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk;