SlideShare a Scribd company logo
……………………………………………………....
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

More Related Content

PPT
Chinabankppt
PPT
Les09 (using ddl statements to create and manage tables)
PPT
PPT
Les02 (restricting and sorting data)
PPT
Les08 (manipulating data)
PDF
Basic Sql Handouts
PPT
e computer notes - Manipulating data
PPT
Chinabankppt
Les09 (using ddl statements to create and manage tables)
Les02 (restricting and sorting data)
Les08 (manipulating data)
Basic Sql Handouts
e computer notes - Manipulating data

What's hot (20)

PPT
Les01 (retrieving data using the sql select statement)
PPT
Manipulating Data Oracle Data base
PPTX
1. dml select statement reterive data
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
PPTX
Sql intro
PPT
Aggregate Functions,Final
PPT
Retrieving data using the sql select statement
PPT
ALL ABOUT SQL AND RDBMS
PPT
Restricting and sorting data
PPT
Module03
PPT
SQL select statement and functions
PPT
PPT
Sql select
PPT
PPT
Advanced Sql Training
PDF
Introduction to oracle functions
PPT
Using single row functions to customize output
PPT
Aggregate functions
PPT
SQL- Introduction to MySQL
PPT
Les01 (retrieving data using the sql select statement)
Manipulating Data Oracle Data base
1. dml select statement reterive data
Database Systems - SQL - DDL Statements (Chapter 3/3)
Sql intro
Aggregate Functions,Final
Retrieving data using the sql select statement
ALL ABOUT SQL AND RDBMS
Restricting and sorting data
Module03
SQL select statement and functions
Sql select
Advanced Sql Training
Introduction to oracle functions
Using single row functions to customize output
Aggregate functions
SQL- Introduction to MySQL
Ad

Viewers also liked (7)

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

Similar to sql language (20)

PDF
0808.pdf
PDF
0808.pdf
PPTX
Data Manipulation Language.pptx
PPTX
PPTX
Basic SQL Statments
PPT
DOCX
PPT
Introduction to-sql
PPTX
Beginers guide for oracle sql
PPT
Db1 lecture4
PPTX
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
PPTX
Its about a sql topic for basic structured query language
PPTX
Interacting with Oracle Database
PPTX
lect 2.pptx
PPTX
PPTX
DOODB_LAB.pptx
PPTX
Oraclesql
PPTX
SQL Query
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
0808.pdf
0808.pdf
Data Manipulation Language.pptx
Basic SQL Statments
Introduction to-sql
Beginers guide for oracle sql
Db1 lecture4
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
Its about a sql topic for basic structured query language
Interacting with Oracle Database
lect 2.pptx
DOODB_LAB.pptx
Oraclesql
SQL Query
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx

Recently uploaded (20)

PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PDF
annual-report-2024-2025 original latest.
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PDF
Business Analytics and business intelligence.pdf
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPTX
Business Ppt On Nestle.pptx huunnnhhgfvu
PPTX
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
PPT
Quality review (1)_presentation of this 21
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PPTX
Database Infoormation System (DBIS).pptx
PPTX
Qualitative Qantitative and Mixed Methods.pptx
PPTX
Introduction to machine learning and Linear Models
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
.pdf is not working space design for the following data for the following dat...
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
annual-report-2024-2025 original latest.
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Data_Analytics_and_PowerBI_Presentation.pptx
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
Business Analytics and business intelligence.pdf
Introduction-to-Cloud-ComputingFinal.pptx
Business Ppt On Nestle.pptx huunnnhhgfvu
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
Quality review (1)_presentation of this 21
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Database Infoormation System (DBIS).pptx
Qualitative Qantitative and Mixed Methods.pptx
Introduction to machine learning and Linear Models
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
.pdf is not working space design for the following data for the following dat...
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
STUDY DESIGN details- Lt Col Maksud (21).pptx

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