SlideShare uma empresa Scribd logo
1 de 77
Baixar para ler offline
……………………………………………………....
Teacher Assistant : Hazem A. ELRigip
DB (1) SQL
Structured Query Language
Atef D. Ahmed
What Is A Database?
• A database is a collection of data that is
organized so that its contents can easily be
accessed, managed, and updated.
2
2
SQL Statements
•
• SELECT
• INSERT
• UPDATE
• DELETE
• CREATE
• ALTER
• DROP
• RENAME
• TRUNCATE
• COMMENT
• GRANT
• REVOKE
• COMMIT
• ROLLBACK
• SAVEPOINT
Data manipulation language (DML)
Data definition language (DDL)
Transaction control
Data control language (DCL)
The Human Resources
(HR)Schema
DEPARTMENTS
department_id
department_name
manager_id
location_id
LOCATIONS
location_id
street_address
postal_code
city
state_province
country_id
COUNTRIES
country_id
country_name
region_id
REGIONS
region_id
region_name
EMPLOYEES
employee_id
first_name
last_name
email
phone_number
hire_date
job_id
salary
commission_pct
manager_id
department_id
JOBS
job_id
job_title
min_salary
max_salary
JOB_HISTORY
employee_id
start_date
end_date
job_id
department_id
5
Creating Tables
– Create the table:
– Confirm table creation:
DESCRIBE dept
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
73
Data Types
Raw binary dataRAW and LONG
RAW
Binary data (up to 4 GB)BLOB
Binary data stored in an external file (up to 4 GB)BFILE
Date and time valuesDATE
Variable-length character data (up to 2 GB)LONG
Character data (up to 4 GB)CLOB
A base-64 number system representing the unique
address of a row in its table
ROWID
Fixed-length character dataCHAR(size)
Variable-length numeric dataNUMBER(p,s)
Variable-length character dataVARCHAR2(size)
DescriptionData Type
Defining Constraints
– Example of a column-level constraint:
– Example of a table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
1
2
ALTER TABLE Statement
• Use the ALTER TABLE statement to:
– Add a new column
– Modify an existing column definition
– Define a default value for the new column
– Drop a column
– Rename a column
– Change table to read-only status
Dropping a Table
– Moves a table to the recycle bin
– Invalidates dependent objects and removes
object privileges on the table
DROP TABLE dept80;
INSERT Statement Syntax
– Add new rows to a table by using the INSERT
statement:
– With this syntax, only one row is inserted at a
time.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
Inserting New Rows
– Insert a new row containing values for each
column.
– List values in the default order of the columns
in the table.
– Optionally, list the columns in the INSERT
clause.
– Enclose character and date values within single
quotation marks.
INSERT INTO departments(department_id,
department_name, manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
Copying Rows
from Another Table
– Write your INSERT statement with a subquery:
– Do not use the VALUES clause.
– Match the number of columns in the INSERT
clause to those in the subquery.
– Inserts all the rows returned by the subquery
in the table, sales_reps.
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';
UPDATE Statement Syntax
– Modify existing values in a table with the
UPDATE statement:
– Update more than one row at a time (if
required).
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
Updating Rows in a Table
– Values for a specific row or rows are modified
if you specify the WHERE clause:
– Values for all the rows in the table are
modified if you omit the WHERE clause:
– Specify SET column_name= NULL to update a
column value to NULL.
UPDATE employees
SET department_id = 50
WHERE employee_id = 113;
UPDATE copy_emp
SET department_id = 110;
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 113;
Updating Two Columns with a
Subquery
• Update employee 113’s job and salary to
match those of employee 205.
DELETE Statement
• You can remove existing rows from a
table by using the DELETE statement:
DELETE [FROM] table
[WHERE condition];
Deleting Rows from a Table
– Specific rows are deleted if you specify the
WHERE clause:
– All rows in the table are deleted if you omit the
WHERE clause:
DELETE FROM departments
WHERE department_name = ‘Finance';
DELETE FROM copy_emp;
Basic SELECT Statement
– SELECT identifies the columns to be displayed.
– FROM identifies the table containing those
columns.
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table;
6
Writing SQL Statements
– SQL statements are not case-sensitive.
– SQL statements can be entered on one or more
lines.
– In SQL Developer, SQL statements can
optionally be terminated by a semicolon (;).
Semicolons are required when you execute
multiple SQL statements.
– In SQL*Plus, you are required to end each SQL
statement with a semicolon (;).
7
Arithmetic Expressions
• Create expressions with number and date
data by using arithmetic operators.
Multiply*
Divide/
Subtract-
Add+
DescriptionOperator
8
SELECT last_name, salary, 12*salary+100
FROM employees;
Operator Precedence
SELECT last_name, salary, 12*(salary+100)
FROM employees;
…
…
1
2
9
Using Column Aliases
SELECT last_name "Name" , salary*12 "Annual Salary"
FROM employees;
SELECT last_name AS name, commission_pct comm
FROM employees;
…
…
10
Using Literal Character Strings
…
SELECT last_name ||' is a '||job_id
AS "Employee Details"
FROM employees;
11
Duplicate Rows
• The default display of queries is all rows,
including duplicate rows.
SELECT department_id
FROM employees;
SELECT DISTINCT department_id
FROM employees;
1
2
…
…
12
Displaying the Table Structure
– Use the DESCRIBE command to display the
structure of a table.
– Or, select the table in the Connections tree
and use the Columns tab to view the table
structure.
DESC tablename
13
Using the DESCRIBE Command
DESCRIBE employees
14
Limiting the Rows that Are
Selected
– Restrict the rows that are returned by using
the WHERE clause:
– The WHERE clause follows the FROM clause.
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)];
15
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90 ;
Using the WHERE Clause
16
Comparison Operators
Not equal to<>
Between two values (inclusive)BETWEEN
...AND...
Match any of a list of valuesIN(set)
Match a character patternLIKE
Is a null valueIS NULL
Less than<
Less than or equal to<=
Greater than or equal to>=
Greater than>
Equal to=
MeaningOperator
17
SELECT last_name, salary
FROM employees
WHERE salary <= 3000 ;
Using Comparison Operators
18
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
Range Conditions Using the
BETWEEN Operator
• Use the BETWEEN operator to display rows
based on a range of values:
Lower limit Upper limit
19
Combining Wildcard Characters
– You can combine the two wildcard characters
(%, _) with literal characters for pattern
matching:
– You can use the ESCAPE identifier to search for
the actual % and _ symbols.
SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;
20
Defining Conditions Using the
Logical Operators
Returns TRUE if the condition is falseNOT
Returns TRUE if either component
condition is true
OR
Returns TRUE if both component
conditions are true
AND
MeaningOperator
21
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
AND job_id LIKE '%MAN%' ;
Using the AND Operator
• AND requires both the component
conditions to be true:
22
Using the ORDER BY Clause
– Sort retrieved rows with the ORDER BY clause:
• ASC: Ascending order, default
• DESC: Descending order
– The ORDER BY clause comes last in the SELECT
statement:SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date ;
…
23
Sorting
– Sorting in descending order:
– Sorting by column alias:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;
1
SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal ;
2
24
SQL Functions
Function
Input
arg 1
arg 2
arg n
Function performs
action
Output
Result
value
25
Case-Conversion Functions
• These functions convert the case for
character strings:
sql courseLOWER('SQL Course')
Sql CourseINITCAP('SQL Course')
SQL COURSEUPPER('SQL Course')
ResultFunction
26
SELECT employee_id, last_name, department_id
FROM employees
WHERE LOWER(last_name) = 'higgins';
Using Case-Conversion
Functions
• Display the employee number, name, and
department number for employee Higgins:
SELECT employee_id, last_name, department_id
FROM employees
WHERE last_name = 'higgins';
27
Character-Manipulation
Functions
• These functions manipulate character
strings:
BLACK and BLUEREPLACE
('JACK and JUE','J','BL')
10LENGTH('HelloWorld')
6INSTR('HelloWorld', 'W')
*****24000LPAD(salary,10,'*')
24000*****RPAD(salary, 10, '*')
HelloWorldCONCAT('Hello', 'World')
elloWorldTRIM('H' FROM 'HelloWorld')
HelloSUBSTR('HelloWorld',1,5)
ResultFunction
28
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name),
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';
Using the Character-
Manipulation Functions
2
31 2
1
3
29
Number Functions
– ROUND: Rounds value to a specified decimal
– TRUNC: Truncates value to a specified decimal
– MOD: Returns remainder of division
100MOD(1600, 300)
45.93ROUND(45.926, 2)
45.92TRUNC(45.926, 2)
ResultFunction
30
SELECT ROUND(45.923,2), ROUND(45.923,0),
ROUND(45.923,-1)
FROM DUAL;
Using the ROUND Function
DUAL is a dummy table that you can use to view results
from functions and calculations.
3
31 2
1 2
31
SELECT last_name, salary, MOD(salary, 5000)
FROM employees
WHERE job_id = 'SA_REP';
Using the MOD Function
• For all employees with the job title of
Sales Representative, calculate the
remainder of the salary after it is divided
by 5,000.
32
SELECT last_name, hire_date
FROM employees
WHERE hire_date < '01-FEB-88';
Working with Dates
– The Oracle database stores dates in an internal
numeric format: century, year, month, day,
hours, minutes, and seconds.
– The default date display format is DD-MON-RR.
• Enables you to store 21st-century dates in the 20th
century
by specifying only the last two digits of the year
• Enables you to store 20th-century dates in the
21st century in the same way
33
Using the SYSDATE Function
• SYSDATE is a function that returns:
– Date
– Time
SELECT sysdate
FROM dual;
34
SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS
FROM employees
WHERE department_id = 90;
Using Arithmetic Operators
with Dates
35
Date-Manipulation Functions
Next day of the date specifiedNEXT_DAY
Last day of the monthLAST_DAY
Number of months between two datesMONTHS_BETWEEN
Add calendar months to dateADD_MONTHS
ResultFunction
36
Using Date Functions
'08-SEP-95'NEXT_DAY ('01-SEP-95','FRIDAY')
'28-FEB-95'LAST_DAY ('01-FEB-95')
19.6774194MONTHS_BETWEEN
('01-SEP-95','11-JAN-94')
‘29-FEB-96'ADD_MONTHS (‘31-JAN-96',1)
ResultFunction
37
What Are Group Functions?
• Group functions operate on sets of rows
to give one result per group.
EMPLOYEES
Maximum salary in
EMPLOYEES table
…
38
Types of Group Functions
– AVG
– COUNT
– MAX
– MIN
– SUM
Group
functions
39
SELECT group_function(column), ...
FROM table
[WHERE condition]
[ORDER BY column];
Group Functions: Syntax
40
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';
Using the AVG and SUM Functions
• You can use AVG and SUM for numeric
data.
41
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id ;
Using the GROUP BY Clause
• All columns in the SELECT list that are not
in group functions must be in the GROUP
BY clause.
42
Illegal Queries
Using Group Functions
– You cannot use the WHERE clause to restrict
groups.
– You use the HAVING clause to restrict groups.
– You cannot use group functions in the WHERE
clause.
SELECT department_id, AVG(salary)
FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;
Cannot use the
WHERE clause to
restrict groups
43
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Restricting Group Results
with the HAVING Clause
• When you use the HAVING clause, the
Oracle server restricts groups as follows:
1. Rows are grouped.
2. The group function is applied.
3. Groups matching the HAVING clause are
displayed.
44
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;
Using the HAVING Clause
45
Obtaining Data from Multiple
Tables
EMPLOYEES DEPARTMENTS
…
…
46
SELECT department_id, department_name,
location_id, city
FROM departments
NATURAL JOIN locations ;
Retrieving Records with Natural
Joins
47
SELECT employee_id, last_name,
location_id, department_id
FROM employees JOIN departments
USING (department_id) ;
Retrieving Records with the
USING Clause
…
48
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);
Retrieving Records with the ON
Clause
…
49
Joining a Table to Itself
MANAGER_ID in the WORKER table is equal to
EMPLOYEE_ID in the MANAGER table.
EMPLOYEES (WORKER) EMPLOYEES (MANAGER)
… …
50
Self-Joins Using the ON Clause
SELECT worker.last_name emp, manager.last_name mgr
FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);
…
51
SELECT e.last_name, e.salary, j.grade_level
FROM employees e JOIN job_grades j
ON e.salary
BETWEEN j.lowest_sal AND j.highest_sal;
Retrieving Records
with Nonequijoins
…
52
Generating a Cartesian Product
Cartesian product:
20 x 8 = 160 rows
EMPLOYEES (20 rows) DEPARTMENTS (8 rows)
…
…
53
SELECT last_name, department_name
FROM employees
CROSS JOIN departments ;
Creating Cross Joins
– The CROSS JOIN clause produces the cross-
product of two tables.
– This is also called a Cartesian product between
the two tables.
…
54
Subquery Syntax
– The subquery (inner query) executes before
the main query (outer query).
– The result of the subquery is used by the main
query.
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
55
SELECT last_name, salary
FROM employees
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');
Using a Subquery
11000
56
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
The HAVING Clause with
Subqueries
– The Oracle server executes the subqueries
first.
– The Oracle server returns results into the
HAVING clause of the main query.
2500
… 57
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);
Null Values in a Subquery
58
Set Operators
UNION/UNION ALL
A B A B
A B
INTERSECT
A B
MINUS
59
TRUNCATE Statement
– Removes all rows from a table, leaving the
table empty and the table structure intact
– Is a data definition language (DDL) statement
rather than a DML statement; cannot easily be
undone
– Syntax:
– Example:
TRUNCATE TABLE table_name;
TRUNCATE TABLE copy_emp;
69
Database Transactions: Start
and End
– Begin when the first DML SQL statement is
executed.
– End with one of the following events:
• A COMMIT or ROLLBACK statement is issued.
• A DDL or DCL statement executes (automatic
commit).
• The user exits SQL Developer or SQL*Plus.
• The system crashes.
70
COMMIT;
Committing Data
– Make the changes:
– Commit the changes:
DELETE FROM employees
WHERE employee_id = 99999;
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
71
DELETE FROM copy_emp;
ROLLBACK ;
State of the Data After ROLLBACK
• Discard all pending changes by using the
ROLLBACK statement:
– Data changes are undone.
– Previous state of the data is restored.
– Locks on the affected rows are released.
72
Database Objects
Logically represents subsets of data from
one or more tables
View
Generates numeric valuesSequence
Basic unit of storage; composed of rowsTable
Gives alternative names to objectsSynonym
Improves the performance of data retrieval
queries
Index
DescriptionObject
73
……………………………………………………....
THE END

Mais conteúdo relacionado

Mais procurados

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
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data baseSalman Memon
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive dataAmrit Kaur
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Vidyasagar Mundroy
 
Sql intro
Sql introSql intro
Sql introglubox
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statementSyed Zaid Irshad
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSgaurav koriya
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting dataSyed Zaid Irshad
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functionssinhacp
 

Mais procurados (20)

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)
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Sql intro
Sql introSql intro
Sql intro
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statement
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting data
 
Module03
Module03Module03
Module03
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Les03
Les03Les03
Les03
 
Sql select
Sql select Sql select
Sql select
 
Les08
Les08Les08
Les08
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
Les18
Les18Les18
Les18
 

Destaque

Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle VersionsJeffrey Kemp
 
Why You Should Use Oracle SQL Developer
Why You Should Use Oracle SQL DeveloperWhy You Should Use Oracle SQL Developer
Why You Should Use Oracle SQL DeveloperJeffrey Kemp
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in ApexJeffrey Kemp
 
Automate Amazon S3 Storage with Alexandria
Automate Amazon S3 Storage with AlexandriaAutomate Amazon S3 Storage with Alexandria
Automate Amazon S3 Storage with AlexandriaJeffrey Kemp
 
Best Practices for running the Oracle Database on EC2 webinar
Best Practices for running the Oracle Database on EC2 webinarBest Practices for running the Oracle Database on EC2 webinar
Best Practices for running the Oracle Database on EC2 webinarTom Laszewski
 
Oracle Solutions on AWS : May 2014
Oracle Solutions on AWS : May 2014Oracle Solutions on AWS : May 2014
Oracle Solutions on AWS : May 2014Tom Laszewski
 
Using Oracle Database with Amazon Web Services
Using Oracle Database with Amazon Web ServicesUsing Oracle Database with Amazon Web Services
Using Oracle Database with Amazon Web Servicesguest484c12
 

Destaque (7)

Old Oracle Versions
Old Oracle VersionsOld Oracle Versions
Old Oracle Versions
 
Why You Should Use Oracle SQL Developer
Why You Should Use Oracle SQL DeveloperWhy You Should Use Oracle SQL Developer
Why You Should Use Oracle SQL Developer
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in Apex
 
Automate Amazon S3 Storage with Alexandria
Automate Amazon S3 Storage with AlexandriaAutomate Amazon S3 Storage with Alexandria
Automate Amazon S3 Storage with Alexandria
 
Best Practices for running the Oracle Database on EC2 webinar
Best Practices for running the Oracle Database on EC2 webinarBest Practices for running the Oracle Database on EC2 webinar
Best Practices for running the Oracle Database on EC2 webinar
 
Oracle Solutions on AWS : May 2014
Oracle Solutions on AWS : May 2014Oracle Solutions on AWS : May 2014
Oracle Solutions on AWS : May 2014
 
Using Oracle Database with Amazon Web Services
Using Oracle Database with Amazon Web ServicesUsing Oracle Database with Amazon Web Services
Using Oracle Database with Amazon Web Services
 

Semelhante a sql language

Semelhante a sql language (20)

0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Lab
LabLab
Lab
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
Les06
Les06Les06
Les06
 
Query
QueryQuery
Query
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
SQL
SQLSQL
SQL
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
Interacting with Oracle Database
Interacting with Oracle DatabaseInteracting with Oracle Database
Interacting with Oracle Database
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
SQL Query
SQL QuerySQL Query
SQL Query
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 

Último

Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxolyaivanovalion
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...amitlee9823
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...shambhavirathore45
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxolyaivanovalion
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfadriantubila
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 

Último (20)

Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptx
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptx
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 

sql language

  • 1. …………………………………………………….... Teacher Assistant : Hazem A. ELRigip DB (1) SQL Structured Query Language Atef D. Ahmed
  • 2. What Is A Database? • A database is a collection of data that is organized so that its contents can easily be accessed, managed, and updated. 2 2
  • 3. SQL Statements • • SELECT • INSERT • UPDATE • DELETE • CREATE • ALTER • DROP • RENAME • TRUNCATE • COMMENT • GRANT • REVOKE • COMMIT • ROLLBACK • SAVEPOINT Data manipulation language (DML) Data definition language (DDL) Transaction control Data control language (DCL)
  • 5. Creating Tables – Create the table: – Confirm table creation: DESCRIBE dept CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE); 73
  • 6. Data Types Raw binary dataRAW and LONG RAW Binary data (up to 4 GB)BLOB Binary data stored in an external file (up to 4 GB)BFILE Date and time valuesDATE Variable-length character data (up to 2 GB)LONG Character data (up to 4 GB)CLOB A base-64 number system representing the unique address of a row in its table ROWID Fixed-length character dataCHAR(size) Variable-length numeric dataNUMBER(p,s) Variable-length character dataVARCHAR2(size) DescriptionData Type
  • 7. Defining Constraints – Example of a column-level constraint: – Example of a table-level constraint: CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...); CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID)); 1 2
  • 8. ALTER TABLE Statement • Use the ALTER TABLE statement to: – Add a new column – Modify an existing column definition – Define a default value for the new column – Drop a column – Rename a column – Change table to read-only status
  • 9. Dropping a Table – Moves a table to the recycle bin – Invalidates dependent objects and removes object privileges on the table DROP TABLE dept80;
  • 10. INSERT Statement Syntax – Add new rows to a table by using the INSERT statement: – With this syntax, only one row is inserted at a time. INSERT INTO table [(column [, column...])] VALUES (value [, value...]);
  • 11. Inserting New Rows – Insert a new row containing values for each column. – List values in the default order of the columns in the table. – Optionally, list the columns in the INSERT clause. – Enclose character and date values within single quotation marks. INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700);
  • 12. Copying Rows from Another Table – Write your INSERT statement with a subquery: – Do not use the VALUES clause. – Match the number of columns in the INSERT clause to those in the subquery. – Inserts all the rows returned by the subquery in the table, sales_reps. INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE job_id LIKE '%REP%';
  • 13. UPDATE Statement Syntax – Modify existing values in a table with the UPDATE statement: – Update more than one row at a time (if required). UPDATE table SET column = value [, column = value, ...] [WHERE condition];
  • 14. Updating Rows in a Table – Values for a specific row or rows are modified if you specify the WHERE clause: – Values for all the rows in the table are modified if you omit the WHERE clause: – Specify SET column_name= NULL to update a column value to NULL. UPDATE employees SET department_id = 50 WHERE employee_id = 113; UPDATE copy_emp SET department_id = 110;
  • 15. UPDATE employees SET job_id = (SELECT job_id FROM employees WHERE employee_id = 205), salary = (SELECT salary FROM employees WHERE employee_id = 205) WHERE employee_id = 113; Updating Two Columns with a Subquery • Update employee 113’s job and salary to match those of employee 205.
  • 16. DELETE Statement • You can remove existing rows from a table by using the DELETE statement: DELETE [FROM] table [WHERE condition];
  • 17. Deleting Rows from a Table – Specific rows are deleted if you specify the WHERE clause: – All rows in the table are deleted if you omit the WHERE clause: DELETE FROM departments WHERE department_name = ‘Finance'; DELETE FROM copy_emp;
  • 18. Basic SELECT Statement – SELECT identifies the columns to be displayed. – FROM identifies the table containing those columns. SELECT *|{[DISTINCT] column|expression [alias],...} FROM table; 6
  • 19. Writing SQL Statements – SQL statements are not case-sensitive. – SQL statements can be entered on one or more lines. – In SQL Developer, SQL statements can optionally be terminated by a semicolon (;). Semicolons are required when you execute multiple SQL statements. – In SQL*Plus, you are required to end each SQL statement with a semicolon (;). 7
  • 20. Arithmetic Expressions • Create expressions with number and date data by using arithmetic operators. Multiply* Divide/ Subtract- Add+ DescriptionOperator 8
  • 21. SELECT last_name, salary, 12*salary+100 FROM employees; Operator Precedence SELECT last_name, salary, 12*(salary+100) FROM employees; … … 1 2 9
  • 22. Using Column Aliases SELECT last_name "Name" , salary*12 "Annual Salary" FROM employees; SELECT last_name AS name, commission_pct comm FROM employees; … … 10
  • 23. Using Literal Character Strings … SELECT last_name ||' is a '||job_id AS "Employee Details" FROM employees; 11
  • 24. Duplicate Rows • The default display of queries is all rows, including duplicate rows. SELECT department_id FROM employees; SELECT DISTINCT department_id FROM employees; 1 2 … … 12
  • 25. Displaying the Table Structure – Use the DESCRIBE command to display the structure of a table. – Or, select the table in the Connections tree and use the Columns tab to view the table structure. DESC tablename 13
  • 26. Using the DESCRIBE Command DESCRIBE employees 14
  • 27. Limiting the Rows that Are Selected – Restrict the rows that are returned by using the WHERE clause: – The WHERE clause follows the FROM clause. SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)]; 15
  • 28. SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ; Using the WHERE Clause 16
  • 29. Comparison Operators Not equal to<> Between two values (inclusive)BETWEEN ...AND... Match any of a list of valuesIN(set) Match a character patternLIKE Is a null valueIS NULL Less than< Less than or equal to<= Greater than or equal to>= Greater than> Equal to= MeaningOperator 17
  • 30. SELECT last_name, salary FROM employees WHERE salary <= 3000 ; Using Comparison Operators 18
  • 31. SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500 ; Range Conditions Using the BETWEEN Operator • Use the BETWEEN operator to display rows based on a range of values: Lower limit Upper limit 19
  • 32. Combining Wildcard Characters – You can combine the two wildcard characters (%, _) with literal characters for pattern matching: – You can use the ESCAPE identifier to search for the actual % and _ symbols. SELECT last_name FROM employees WHERE last_name LIKE '_o%' ; 20
  • 33. Defining Conditions Using the Logical Operators Returns TRUE if the condition is falseNOT Returns TRUE if either component condition is true OR Returns TRUE if both component conditions are true AND MeaningOperator 21
  • 34. SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 AND job_id LIKE '%MAN%' ; Using the AND Operator • AND requires both the component conditions to be true: 22
  • 35. Using the ORDER BY Clause – Sort retrieved rows with the ORDER BY clause: • ASC: Ascending order, default • DESC: Descending order – The ORDER BY clause comes last in the SELECT statement:SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date ; … 23
  • 36. Sorting – Sorting in descending order: – Sorting by column alias: SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC ; 1 SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY annsal ; 2 24
  • 37. SQL Functions Function Input arg 1 arg 2 arg n Function performs action Output Result value 25
  • 38. Case-Conversion Functions • These functions convert the case for character strings: sql courseLOWER('SQL Course') Sql CourseINITCAP('SQL Course') SQL COURSEUPPER('SQL Course') ResultFunction 26
  • 39. SELECT employee_id, last_name, department_id FROM employees WHERE LOWER(last_name) = 'higgins'; Using Case-Conversion Functions • Display the employee number, name, and department number for employee Higgins: SELECT employee_id, last_name, department_id FROM employees WHERE last_name = 'higgins'; 27
  • 40. Character-Manipulation Functions • These functions manipulate character strings: BLACK and BLUEREPLACE ('JACK and JUE','J','BL') 10LENGTH('HelloWorld') 6INSTR('HelloWorld', 'W') *****24000LPAD(salary,10,'*') 24000*****RPAD(salary, 10, '*') HelloWorldCONCAT('Hello', 'World') elloWorldTRIM('H' FROM 'HelloWorld') HelloSUBSTR('HelloWorld',1,5) ResultFunction 28
  • 41. SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH (last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE SUBSTR(job_id, 4) = 'REP'; Using the Character- Manipulation Functions 2 31 2 1 3 29
  • 42. Number Functions – ROUND: Rounds value to a specified decimal – TRUNC: Truncates value to a specified decimal – MOD: Returns remainder of division 100MOD(1600, 300) 45.93ROUND(45.926, 2) 45.92TRUNC(45.926, 2) ResultFunction 30
  • 43. SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1) FROM DUAL; Using the ROUND Function DUAL is a dummy table that you can use to view results from functions and calculations. 3 31 2 1 2 31
  • 44. SELECT last_name, salary, MOD(salary, 5000) FROM employees WHERE job_id = 'SA_REP'; Using the MOD Function • For all employees with the job title of Sales Representative, calculate the remainder of the salary after it is divided by 5,000. 32
  • 45. SELECT last_name, hire_date FROM employees WHERE hire_date < '01-FEB-88'; Working with Dates – The Oracle database stores dates in an internal numeric format: century, year, month, day, hours, minutes, and seconds. – The default date display format is DD-MON-RR. • Enables you to store 21st-century dates in the 20th century by specifying only the last two digits of the year • Enables you to store 20th-century dates in the 21st century in the same way 33
  • 46. Using the SYSDATE Function • SYSDATE is a function that returns: – Date – Time SELECT sysdate FROM dual; 34
  • 47. SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM employees WHERE department_id = 90; Using Arithmetic Operators with Dates 35
  • 48. Date-Manipulation Functions Next day of the date specifiedNEXT_DAY Last day of the monthLAST_DAY Number of months between two datesMONTHS_BETWEEN Add calendar months to dateADD_MONTHS ResultFunction 36
  • 49. Using Date Functions '08-SEP-95'NEXT_DAY ('01-SEP-95','FRIDAY') '28-FEB-95'LAST_DAY ('01-FEB-95') 19.6774194MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') ‘29-FEB-96'ADD_MONTHS (‘31-JAN-96',1) ResultFunction 37
  • 50. What Are Group Functions? • Group functions operate on sets of rows to give one result per group. EMPLOYEES Maximum salary in EMPLOYEES table … 38
  • 51. Types of Group Functions – AVG – COUNT – MAX – MIN – SUM Group functions 39
  • 52. SELECT group_function(column), ... FROM table [WHERE condition] [ORDER BY column]; Group Functions: Syntax 40
  • 53. SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE job_id LIKE '%REP%'; Using the AVG and SUM Functions • You can use AVG and SUM for numeric data. 41
  • 54. SELECT department_id, AVG(salary) FROM employees GROUP BY department_id ; Using the GROUP BY Clause • All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. 42
  • 55. Illegal Queries Using Group Functions – You cannot use the WHERE clause to restrict groups. – You use the HAVING clause to restrict groups. – You cannot use group functions in the WHERE clause. SELECT department_id, AVG(salary) FROM employees WHERE AVG(salary) > 8000 GROUP BY department_id; Cannot use the WHERE clause to restrict groups 43
  • 56. SELECT column, group_function FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER BY column]; Restricting Group Results with the HAVING Clause • When you use the HAVING clause, the Oracle server restricts groups as follows: 1. Rows are grouped. 2. The group function is applied. 3. Groups matching the HAVING clause are displayed. 44
  • 57. SELECT department_id, MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary)>10000 ; Using the HAVING Clause 45
  • 58. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … … 46
  • 59. SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ; Retrieving Records with Natural Joins 47
  • 60. SELECT employee_id, last_name, location_id, department_id FROM employees JOIN departments USING (department_id) ; Retrieving Records with the USING Clause … 48
  • 61. 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); Retrieving Records with the ON Clause … 49
  • 62. Joining a Table to Itself MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … … 50
  • 63. Self-Joins Using the ON Clause SELECT worker.last_name emp, manager.last_name mgr FROM employees worker JOIN employees manager ON (worker.manager_id = manager.employee_id); … 51
  • 64. SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal; Retrieving Records with Nonequijoins … 52
  • 65. Generating a Cartesian Product Cartesian product: 20 x 8 = 160 rows EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … … 53
  • 66. SELECT last_name, department_name FROM employees CROSS JOIN departments ; Creating Cross Joins – The CROSS JOIN clause produces the cross- product of two tables. – This is also called a Cartesian product between the two tables. … 54
  • 67. Subquery Syntax – The subquery (inner query) executes before the main query (outer query). – The result of the subquery is used by the main query. SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); 55
  • 68. SELECT last_name, salary FROM employees WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel'); Using a Subquery 11000 56
  • 69. SELECT department_id, MIN(salary) FROM employees GROUP BY department_id HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE department_id = 50); The HAVING Clause with Subqueries – The Oracle server executes the subqueries first. – The Oracle server returns results into the HAVING clause of the main query. 2500 … 57
  • 70. SELECT emp.last_name FROM employees emp WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr); Null Values in a Subquery 58
  • 71. Set Operators UNION/UNION ALL A B A B A B INTERSECT A B MINUS 59
  • 72. TRUNCATE Statement – Removes all rows from a table, leaving the table empty and the table structure intact – Is a data definition language (DDL) statement rather than a DML statement; cannot easily be undone – Syntax: – Example: TRUNCATE TABLE table_name; TRUNCATE TABLE copy_emp; 69
  • 73. Database Transactions: Start and End – Begin when the first DML SQL statement is executed. – End with one of the following events: • A COMMIT or ROLLBACK statement is issued. • A DDL or DCL statement executes (automatic commit). • The user exits SQL Developer or SQL*Plus. • The system crashes. 70
  • 74. COMMIT; Committing Data – Make the changes: – Commit the changes: DELETE FROM employees WHERE employee_id = 99999; INSERT INTO departments VALUES (290, 'Corporate Tax', NULL, 1700); 71
  • 75. DELETE FROM copy_emp; ROLLBACK ; State of the Data After ROLLBACK • Discard all pending changes by using the ROLLBACK statement: – Data changes are undone. – Previous state of the data is restored. – Locks on the affected rows are released. 72
  • 76. Database Objects Logically represents subsets of data from one or more tables View Generates numeric valuesSequence Basic unit of storage; composed of rowsTable Gives alternative names to objectsSynonym Improves the performance of data retrieval queries Index DescriptionObject 73