Escolar Documentos
Profissional Documentos
Cultura Documentos
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction control
SAVEPOINT
Functions
Single-row Multiple-row
functions functions
Accepts
Number
different types Single-row
functions
Conversion Date
Character Functions
Character
functions
Case-manipulation Character-manipulation
functions functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE
TRANSLATE
Case Manipulation Functions
COMMAND DESCRIPTION
S% BEGIN WITH S
%S END WITH S
SECOND LETTER STARTING
_S%
WITH S
_____ EXACTLY 5 LETTERS
PRACTICE SESSIONS
1. Display the total content of dept table & salgrade
table.
2. List the employees whose names start with "S"
(not "s"):
3. List the employee names ending with an "S" :
4. List the names of employees whose names have
exactly 6 characters:
5. List the employee names having "I" as the
second character: (Write minimum 2 queries)
6. Display o/p ‘SMITH works as CLERK’ using
concat()
7. Find number of ‘A’ occurrences in each row of
dname column
PRACTICE SESSIONS
8. Write a query to perform trim operation on ename column
of emp table.
9. Write a query to perform ‘replace’ function on ename for
replacing first 3 characters of ename by numbers.
10. Left justify sal column of emp table.(use #)
11. Right justify job column of emp table (use $)
12. Write a query to find 3rd character in ename.
13. Create a query to display all the data from the
EMPLOYEES table. Separate each column by a
comma. Name the column THE_OUTPUT.
14. Write a query to find last character in ename.
15. Display all enames with only 3rd character replaced by
numbers.
16. Display all enames with last character being different case.
17. Display only those names where last character is getting
repeated.
SM2TH SMITH
AL3EN ALLEN
WA7D WARD
JO5ES JONES
MA7TIN MARTIN
BL1KE BLAKE
CL1RK CLARK
SC6TT SCOTT
KI5G KING
TU7NER TURNER
AD1MS ADAMS
JA4ES JAMES
FO7D FORD
MI3LER MILLER
18. Display only those names where second character is getting repeated
In 3rd position.
Number Functions
TRUNC( )
CEIL( )
FLOOR( )
POWER()
SQRT( )
SIGN( )
MOD( )
ABS( )
Date Functions
Function Description
• NEXT_DAY ('01-SEP-95','FRIDAY')
'08-SEP-95'
• LAST_DAY('01-FEB-95') '28-FEB-95'
• ROUND(TO_DATE('01-JUL-05'),’YYYY’)
‘01-JAN-06'
• TRUNC(TO_DATE('01-JUL-05'),’YYYY’)
‘01-JAN-05'
Useful formats while Using To_char
Functions
FORMAT DESCRIPTION EXAMPLE
MM Number of month 12
RM Roman Numerical month XII
MON Three letter abbreviation DEC
MONTH Month fully spelt out DECEMBER
DDD Number of days since Jan 1 347
DD Number of the day of month 13
D Number of days in week 2
DY Three-letter abbreviation of day WED
DAY Day fully spelt out WEDNESDAY
YYYY Full 4 digit year 1995
SYYYY Signed Year 1000,BC=1000
YYY Last three digits of year 995
YY Last 2 digits of year 95
Y Last digit of year 5
YEAR Year fully spelt out NINTEEN-NINTY-FIVE
PRACTICE SESSIONS
1. Select To-day’s date.
2. Find out the experience of each employee and arrange in the
increasing order of experience.
3. Select a query to return next Sunday.
4. Write a query to find how old are you?( express in years and
months)
5. List employees hired on Monday.
6. Show all employees who were hired in the first half of the month
(before the 16th of the month).
7. Write a Query to find out the last day of any given year.
8. Add 1 year to each employee and display as a separate column.
9. Write a query to find first Sunday of hiredate. (first Sunday in the
joining month)
10. Create an anniversary overview based on the hire date of the
employees. Sort the anniversaries in ascending order.
Aggregate Functions
The aggregate functions produce a single value for an entire
group or table
Examples
List the employees belonging to the department 20:
SELECT * FROM emp
WHERE deptno = 20;
PRACTICE SESSIONS
GREATEST(expr1 [,expr2]...)
NVL(col, value)
DECODE(C,V1,S1,V2,S2,...,D)
Order by Clause
SQL uses the ORDER BY clause to impose an order on the
result of a query.
ORDER BY clause is used with SELECT statement
The syntax is
SELECT[DISTINCT] <column list> | <expr>
FROM <table>[,<table>] [WHERE condition]
[ORDER BY <columns>] [ASC|DESC]
One or more columns and/or expressions can be specified in
ORDER BY clause.
Examples:
List the empno, ename, sal in ascending order of salary:
Examples:
SQL groups the result after it retrieves the rows from a table
2. List the department number and the total salary payable in each department:
3. List the jobs and the number of employees in each job. The result should be in
descending order of the number of employees:
4. List the total salary, maximum and minimum salary and the average salary of
employees job wise:
5. List the average salary for each job excluding managers
6. List the average monthly salary for each job type within department.
7. List average salary for all departments employing more than five people.
8. List jobs of all the employees where maximum salary is greater than or equal to
5000.
9. List the total salary, maximum and minimum salary and the average salary of
the employees job wise, for department number 20 and display only those
rows having average salary greater than 1000:
10. List the employee numbers, names, department numbers and the department
name:
joins
• Arbitrary join conditions
for outer joins
Rules to place (+) operator
EMP_NAME MGR_NAME
---------- ----------
SMITH FORD
ALLEN BLAKE
WARD BLAKE
JONES KING
Cross Joins
(Cartesian product )
SQL > SELECT * FROM EMP CROSS JOIN DEPT;
SQL > SELECT EMPNO,ENAME,JOB,EMP.DEPTNO,DNAME,LOC
FROM EMP CROSS JOIN DEPT
Cartesian Products
Cartesian
product:
20x8=160 rows
What Is a Subquery?
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list
FROM table);
ENAME
----------
SCOTT
KING
FORD
NESTED QUERIES
(SUBQUERIES)
A SUBQUERY is a SELECT statement that is
nested within another SELECT statement and
which returns intermediate results
Syntax:
SELECT col1,col2,... FROM table_name
WHERE clause operator (SELECT col FROM
table WHERE clause)
Single row subqueries
Let us take an example
MIN(SAL)
----------
800
In the above case minimum sal is retrieved. Now
let us try to retrieve the employee name who has
this minimum salary.
ENAME SAL
---------- ----------
SMITH 800
SMITH 800 20
JAMES 950 30
MILLER 1300 10
To query the department which has the avg(sal)
greater to that of department 30.
3 WHERE DEPTNO=30)
4 GROUP BY DEPTNO;
DEPTNO AVG(SAL)
---------- ----------
10 2916.66667
20 2175
To retrieve the maximum average salary for JOB
JOB AVG(SAL)
--------- ----------
UNION/UNION ALL
A B
INTERSECT
A B
MINUS
UNION
SELECT ENAME,SAL FROM EMP WHERE DEPTNO=10
UNION
SELECT ENAME,SAL FROM EMP WHERE DEPTNO=20
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=30
PRACTICE SESSIONS
1. Display the different designations in department 20 and 30:
7. List the names of the employees, who earn lowest salary in each
department:
8. List employee details who earn salary greater than the average
salary for their department.
9. List the job with highest average salary.
10. List the names of the employees, who earn lowest salary in each
department:
Creating Tables
• Create the table.
Modify clause
– Add not null constraint
– Change column data type
– Modify columnsize(width)
Drop clause
– Drop Columns
– Drop Constraints
Adding a Column
New column
DEPT80
Add a new
column to the
DEPT80 table.
DEPT80
Adding a Column
• Use the ADD clause to add columns.
TYPES OF PRIVILEGES
•SYSTEM
Create session, table etc
•OBJECT
select, insert, delete,update
What Is a Sequence?
A sequence:
• Automatically generates unique
numbers
• Is a sharable object
• Is typically used to create a primary
key value
• Replaces application code
• Speeds up the efficiency of accessing
sequence values when cached in
memory
The CREATE SEQUENCE
Statement Syntax
CREATE
CREATE SEQUENCE
SEQUENCE sequence
sequence
[INCREMENT
[INCREMENT BYBY n]
n]
[START
[START WITH
WITH n]
n]
[{MAXVALUE
[{MAXVALUE nn || NOMAXVALUE}]
NOMAXVALUE}]
[{MINVALUE
[{MINVALUE nn || NOMINVALUE}]
NOMINVALUE}]
[{CYCLE
[{CYCLE || NOCYCLE}]
NOCYCLE}]
[{CACHE
[{CACHE nn || NOCACHE}];
NOCACHE}];
Creating a Sequence
• Create a sequence named
DEPT_DEPTID_SEQ to be used for the
primary key of the DEPARTMENTS table.
• Do not use the CYCLE option.
CREATE
CREATE SEQUENCE
SEQUENCE dept_deptid_seq
dept_deptid_seq
INCREMENT
INCREMENT BY
BY 10
10
START
START WITH
WITH 120
120
MAXVALUE
MAXVALUE 9999
9999
NOCACHE
NOCACHE
NOCYCLE;
NOCYCLE;
Sequence
Sequence created.
created.
Confirming Sequences
SELECT
SELECT dept_deptid_seq.CURRVAL
dept_deptid_seq.CURRVAL
FROM
FROM dual;
dual;
• View the current value for the
DEPT_DEPTID_SEQ sequence.
Using a Sequence
• Caching sequence values in memory
gives faster access to those values.
• Gaps in sequence values can occur
when:
– A rollback occurs
– The system crashes
– A sequence is used in another table
• If the sequence was created with
NOCACHE, view the next available
value, by querying the
USER_SEQUENCES table.
Removing a Sequence
DROP
DROP SEQUENCE
SEQUENCE dept_deptid_seq;
dept_deptid_seq;
Sequence
Sequence dropped.
dropped.
SEQUENCES
1.Create a sequence to be used with the primary key column of the DEPT table. The
sequence should start at 200 and have a maximum value of 1000. Have your
sequence increment by ten numbers. Name the sequence DEPT_ID_SEQ.
2.Write a query in a script to display the following information about your sequences:
sequence name, maximum value, increment size, and last number.
3 Write a script to insert two rows into the DEPT table. Be sure to use the sequence
that you created for the ID column. Add two departments named Education and
Administration. Confirm your additions.