171
Writing basic SQL statements Restricting and Sorting Data Single-Row Functions Multiple-Row Functions (Group functions) Manipulating Data (DML) (Insert, Update and Delete) (Insert, Update and Delete) CH3 Part1 CH3 Part1

Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Embed Size (px)

Citation preview

Page 1: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Writing basic SQL statements Restricting and Sorting Data Single-Row Functions Multiple-Row Functions

(Group functions) Manipulating Data (DML)

(Insert, Update and Delete)(Insert, Update and Delete)

Writing basic SQL statements Restricting and Sorting Data Single-Row Functions Multiple-Row Functions

(Group functions) Manipulating Data (DML)

(Insert, Update and Delete)(Insert, Update and Delete)

CH3 Part1CH3 Part1CH3 Part1CH3 Part1

Page 2: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Writing Basic Writing Basic SQL StatementsSQL StatementsWriting Basic Writing Basic

SQL StatementsSQL Statements

Page 3: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL ScriptsSQL Scripts

Script: text file that contains a Script: text file that contains a sequence of SQL commandssequence of SQL commands

Usually have .sql extensionUsually have .sql extension To run from SQL*Plus:To run from SQL*Plus:

Start full file path Start full file path SQL> START path_to_script_file;SQL> START path_to_script_file;

@ full file path @ full file path ((SQL>SQL> @ @ path_to_script_file;)path_to_script_file;)

Extension can be omitted if it is .sqlExtension can be omitted if it is .sql Path cannot contain any blank spacesPath cannot contain any blank spaces

Page 4: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: List the capabilities of SQL List the capabilities of SQL

SELECT statementsSELECT statements Execute a basic SELECT statementExecute a basic SELECT statement Differentiate between SQL Differentiate between SQL

statements and SQL*Plus statements and SQL*Plus commandscommands

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: List the capabilities of SQL List the capabilities of SQL

SELECT statementsSELECT statements Execute a basic SELECT statementExecute a basic SELECT statement Differentiate between SQL Differentiate between SQL

statements and SQL*Plus statements and SQL*Plus commandscommands

Page 5: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Capabilities of SQL Capabilities of SQL SELECT StatementsSELECT StatementsCapabilities of SQL Capabilities of SQL SELECT StatementsSELECT StatementsSelectionSelection ProjectionProjection

Table 1Table 1 Table 2Table 2

Table 1Table 1 Table 1Table 1JoinJoin

Page 6: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Basic SELECT StatementBasic SELECT StatementBasic SELECT StatementBasic SELECT Statement

SELECT [DISTINCT] {*, column [alias],...}FROM table;

SELECT [DISTINCT] {*, column [alias],...}FROM table;

SELECT identifies SELECT identifies whatwhat columns. columns. FROM identifies FROM identifies whichwhich table. table.

SELECT identifies SELECT identifies whatwhat columns. columns. FROM identifies FROM identifies whichwhich table. table.

Page 7: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Writing SQL StatementsWriting SQL StatementsWriting SQL StatementsWriting SQL Statements

SQL statements are not case SQL statements are not case sensitive. sensitive.

SQL statements can be on one orSQL statements can be on one ormore lines.more lines.

Keywords cannot be abbreviated or Keywords cannot be abbreviated or split across lines.split across lines.

Clauses are usually placed on Clauses are usually placed on separate lines.separate lines.

Tabs and indents are used to Tabs and indents are used to enhance readability.enhance readability.

SQL statements are not case SQL statements are not case sensitive. sensitive.

SQL statements can be on one orSQL statements can be on one ormore lines.more lines.

Keywords cannot be abbreviated or Keywords cannot be abbreviated or split across lines.split across lines.

Clauses are usually placed on Clauses are usually placed on separate lines.separate lines.

Tabs and indents are used to Tabs and indents are used to enhance readability.enhance readability.

Page 8: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Selecting All ColumnsSelecting All ColumnsSelecting All ColumnsSelecting All Columns

DEPTNO DNAME LOC--------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

SQL> SELECT * 2 FROM dept;

Page 9: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Selecting Specific Selecting Specific ColumnsColumns

Selecting Specific Selecting Specific ColumnsColumns

DEPTNO LOC--------- ------------- 10 NEW YORK 20 DALLAS 30 CHICAGO 40 BOSTON

SQL> SELECT deptno, loc 2 FROM dept;

Page 10: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Column Heading Column Heading DefaultsDefaults

Column Heading Column Heading DefaultsDefaults

Default justificationDefault justification Left: Date and character dataLeft: Date and character data Right: Numeric dataRight: Numeric data

Default display: UppercaseDefault display: Uppercase

Default justificationDefault justification Left: Date and character dataLeft: Date and character data Right: Numeric dataRight: Numeric data

Default display: UppercaseDefault display: Uppercase

Page 11: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Arithmetic ExpressionsArithmetic ExpressionsArithmetic ExpressionsArithmetic Expressions

Create expressions on NUMBER Create expressions on NUMBER and DATE data by using arithmetic and DATE data by using arithmetic operators.operators.

Create expressions on NUMBER Create expressions on NUMBER and DATE data by using arithmetic and DATE data by using arithmetic operators.operators.

Operator

+

-

*

/

Description

Add

Subtract

Multiply

Divide

Page 12: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Arithmetic Using Arithmetic OperatorsOperators

Using Arithmetic Using Arithmetic OperatorsOperators

SQL> SELECT ename, sal, sal+300 2 FROM emp;

ENAME SAL SAL+300---------- --------- ---------KING 5000 5300BLAKE 2850 3150CLARK 2450 2750JONES 2975 3275MARTIN 1250 1550ALLEN 1600 1900...14 rows selected.

Page 13: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Operator PrecedenceOperator PrecedenceOperator PrecedenceOperator Precedence

Multiplication and division take Multiplication and division take priority over addition and priority over addition and subtraction.subtraction.

Operators of the same priority are Operators of the same priority are evaluated from left to right.evaluated from left to right.

Parentheses are used to force Parentheses are used to force prioritized evaluation and to clarify prioritized evaluation and to clarify statements.statements.

Multiplication and division take Multiplication and division take priority over addition and priority over addition and subtraction.subtraction.

Operators of the same priority are Operators of the same priority are evaluated from left to right.evaluated from left to right.

Parentheses are used to force Parentheses are used to force prioritized evaluation and to clarify prioritized evaluation and to clarify statements.statements.

**** //// ++++ ____

Page 14: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Operator PrecedenceOperator PrecedenceOperator PrecedenceOperator Precedence

SQL> SELECT ename, sal, 12*sal+100 2 FROM emp;

ENAME SAL 12*SAL+100---------- --------- ----------KING 5000 60100BLAKE 2850 34300CLARK 2450 29500JONES 2975 35800MARTIN 1250 15100ALLEN 1600 19300...14 rows selected.

Page 15: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using ParenthesesUsing ParenthesesUsing ParenthesesUsing Parentheses

SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp;

ENAME SAL 12*(SAL+100)---------- --------- -----------KING 5000 61200BLAKE 2850 35400CLARK 2450 30600JONES 2975 36900MARTIN 1250 16200...14 rows selected.

Page 16: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Defining a Null ValueDefining a Null ValueDefining a Null ValueDefining a Null Value A null is a value that is unavailable, A null is a value that is unavailable,

unassigned, unknown, or unassigned, unknown, or inapplicable.inapplicable.

A null is not the same as zero or a A null is not the same as zero or a blank space.blank space.

A null is a value that is unavailable, A null is a value that is unavailable, unassigned, unknown, or unassigned, unknown, or inapplicable.inapplicable.

A null is not the same as zero or a A null is not the same as zero or a blank space.blank space.

ENAME JOB SAL COMM---------- --------- --------- ---------KING PRESIDENT 5000BLAKE MANAGER 2850...TURNER SALESMAN 1500 0...14 rows selected.

SQL> SELECT ename, job, sal, comm 2 FROM emp;

Page 17: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Null Values Null Values in Arithmetic in Arithmetic ExpressionsExpressions

Null Values Null Values in Arithmetic in Arithmetic ExpressionsExpressions

Arithmetic expressions Arithmetic expressions containing a null value evaluate containing a null value evaluate to null.to null.

Arithmetic expressions Arithmetic expressions containing a null value evaluate containing a null value evaluate to null.to null.SQL> select ename, 12*sal+comm

2 from emp 3 WHERE ename='KING';

ENAME 12*SAL+COMM ---------- -----------KING

Page 18: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Defining a Column AliasDefining a Column AliasDefining a Column AliasDefining a Column Alias

Renames a column headingRenames a column heading Is useful with calculationsIs useful with calculations Immediately follows column name; Immediately follows column name;

optional AS keyword between optional AS keyword between column name and aliascolumn name and alias

Requires double quotation marks if Requires double quotation marks if it contains spaces or special it contains spaces or special characters or is case sensitivecharacters or is case sensitive

Renames a column headingRenames a column heading Is useful with calculationsIs useful with calculations Immediately follows column name; Immediately follows column name;

optional AS keyword between optional AS keyword between column name and aliascolumn name and alias

Requires double quotation marks if Requires double quotation marks if it contains spaces or special it contains spaces or special characters or is case sensitivecharacters or is case sensitive

Page 19: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Column AliasesUsing Column AliasesUsing Column AliasesUsing Column Aliases

SQL> SELECT ename AS name, sal salary 2 FROM emp;

NAME SALARY

------------- ---------

...

SQL> SELECT ename "Name", 2 sal*12 "Annual Salary" 3 FROM emp;

Name Annual Salary

------------- -------------

...

Page 20: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Concatenation OperatorConcatenation OperatorConcatenation OperatorConcatenation Operator

Concatenates columns or character Concatenates columns or character strings to other columns strings to other columns

Is represented by two vertical bars Is represented by two vertical bars (||)(||)

Creates a resultant column that is Creates a resultant column that is a character expressiona character expression

Concatenates columns or character Concatenates columns or character strings to other columns strings to other columns

Is represented by two vertical bars Is represented by two vertical bars (||)(||)

Creates a resultant column that is Creates a resultant column that is a character expressiona character expression

Page 21: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the Concatenation Using the Concatenation OperatorOperator

Using the Concatenation Using the Concatenation OperatorOperator

SQL> SELECT ename||job AS "Employees" 2 FROM emp;

Employees-------------------KINGPRESIDENTBLAKEMANAGERCLARKMANAGERJONESMANAGERMARTINSALESMANALLENSALESMAN...14 rows selected.

Page 22: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Literal Character StringsLiteral Character StringsLiteral Character StringsLiteral Character Strings

A literal is a character, a number, A literal is a character, a number, or a date included in the SELECT or a date included in the SELECT list.list.

Date and character literal values Date and character literal values must be enclosed within single must be enclosed within single quotation marks.quotation marks.

Each character string is output Each character string is output once for each row returned.once for each row returned.

A literal is a character, a number, A literal is a character, a number, or a date included in the SELECT or a date included in the SELECT list.list.

Date and character literal values Date and character literal values must be enclosed within single must be enclosed within single quotation marks.quotation marks.

Each character string is output Each character string is output once for each row returned.once for each row returned.

Page 23: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Literal Character Using Literal Character StringsStrings

Using Literal Character Using Literal Character StringsStrings

Employee Details-------------------------KING is a PRESIDENTBLAKE is a MANAGERCLARK is a MANAGERJONES is a MANAGERMARTIN is a SALESMAN...14 rows selected.

Employee Details-------------------------KING is a PRESIDENTBLAKE is a MANAGERCLARK is a MANAGERJONES is a MANAGERMARTIN is a SALESMAN...14 rows selected.

SQL> SELECT ename ||' is a '||job 2 AS "Employee Details" 3 FROM emp;

Page 24: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Duplicate RowsDuplicate RowsDuplicate RowsDuplicate Rows The default display of queries is The default display of queries is

all rows, including duplicate all rows, including duplicate rows.rows.

The default display of queries is The default display of queries is all rows, including duplicate all rows, including duplicate rows.rows.SQL> SELECT deptno 2 FROM emp;

SQL> SELECT deptno 2 FROM emp;

DEPTNO--------- 10 30 10 20...14 rows selected.

Page 25: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Eliminating Duplicate Eliminating Duplicate RowsRows

Eliminating Duplicate Eliminating Duplicate RowsRowsEliminate duplicate rows by using the Eliminate duplicate rows by using the

DISTINCT keyword in the SELECT clause.DISTINCT keyword in the SELECT clause.

SQL> SELECT DISTINCT deptno 2 FROM emp;

DEPTNO--------- 10 20 30

Page 26: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL and SQL*Plus SQL and SQL*Plus InteractionInteraction

SQL and SQL*Plus SQL and SQL*Plus InteractionInteraction

SQL*PlusSQL*Plus

SQL StatementsSQL StatementsBufferBuffer

SQL StatementsSQL Statements

Server

Query ResultsQuery ResultsSQL*PlusSQL*Plus CommandsCommands

Formatted ReportFormatted Report

Page 27: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL Statements Versus SQL Statements Versus SQL*Plus Commands SQL*Plus Commands

SQL Statements Versus SQL Statements Versus SQL*Plus Commands SQL*Plus Commands

SQLSQLstatementsstatements

SQL SQL

• A languageA language

• ANSI standardANSI standard

• Keyword cannot be Keyword cannot be abbreviatedabbreviated

• Statements manipulate Statements manipulate data and table data and table definitions in the definitions in the databasedatabase

SQL*PlusSQL*Plus

• An environmentAn environment

• Oracle proprietaryOracle proprietary

• Keywords can be Keywords can be abbreviatedabbreviated

• Commands do not Commands do not allow manipulation of allow manipulation of values in the databasevalues in the database

SQLSQLbufferbuffer

SQL*PlusSQL*Pluscommandscommands

SQL*PlusSQL*Plusbufferbuffer

Page 28: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Log in to SQL*Plus.Log in to SQL*Plus. Describe the table structure.Describe the table structure. Edit your SQL statement.Edit your SQL statement. Execute SQL from SQL*Plus.Execute SQL from SQL*Plus. Save SQL statements to files and Save SQL statements to files and

append SQL statements to files.append SQL statements to files. Execute saved files.Execute saved files. Load commands from file to bufferLoad commands from file to buffer

to edit.to edit.

Log in to SQL*Plus.Log in to SQL*Plus. Describe the table structure.Describe the table structure. Edit your SQL statement.Edit your SQL statement. Execute SQL from SQL*Plus.Execute SQL from SQL*Plus. Save SQL statements to files and Save SQL statements to files and

append SQL statements to files.append SQL statements to files. Execute saved files.Execute saved files. Load commands from file to bufferLoad commands from file to buffer

to edit.to edit.

Overview of SQL*PlusOverview of SQL*PlusOverview of SQL*PlusOverview of SQL*Plus

Page 29: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Logging In to SQL*PlusLogging In to SQL*PlusLogging In to SQL*PlusLogging In to SQL*Plus From Windows environment:From Windows environment:

From command line:From command line: sqlplus [sqlplus [usernameusername[/[/password password [@[@databasedatabase]]]]]]

Page 30: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Displaying Table Displaying Table StructureStructure

Displaying Table Displaying Table StructureStructure

Use the SQL*Plus DESCRIBE Use the SQL*Plus DESCRIBE command to display the structure of command to display the structure of a table.a table.

Use the SQL*Plus DESCRIBE Use the SQL*Plus DESCRIBE command to display the structure of command to display the structure of a table.a table.DESC[RIBE] tablenameDESC[RIBE] tablename

Page 31: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Displaying Table Displaying Table StructureStructure

Displaying Table Displaying Table StructureStructure

SQL> DESCRIBE deptSQL> DESCRIBE dept

Name Null? Type----------------- -------- ------------DEPTNO NOT NULL NUMBER(2)DNAME VARCHAR2(14)LOC VARCHAR2(13)

Name Null? Type----------------- -------- ------------DEPTNO NOT NULL NUMBER(2)DNAME VARCHAR2(14)LOC VARCHAR2(13)

Page 32: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL*Plus Editing SQL*Plus Editing CommandsCommands

SQL*Plus Editing SQL*Plus Editing CommandsCommands

A[PPEND] A[PPEND] texttext C[HANGE] / C[HANGE] / old old / / newnew C[HANGE] / C[HANGE] / texttext / / CL[EAR] BUFF[ER]CL[EAR] BUFF[ER] DELDEL DEL DEL nn DEL DEL m nm n

A[PPEND] A[PPEND] texttext C[HANGE] / C[HANGE] / old old / / newnew C[HANGE] / C[HANGE] / texttext / / CL[EAR] BUFF[ER]CL[EAR] BUFF[ER] DELDEL DEL DEL nn DEL DEL m nm n

Page 33: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL*Plus Editing SQL*Plus Editing CommandsCommands

SQL*Plus Editing SQL*Plus Editing CommandsCommands I[NPUT]I[NPUT]

I[NPUT] I[NPUT] texttext L[IST]L[IST] L[IST] L[IST] nn L[IST]L[IST] m n m n R[UN]R[UN] nn nn texttext 0 0 texttext

I[NPUT]I[NPUT] I[NPUT] I[NPUT] texttext L[IST]L[IST] L[IST] L[IST] nn L[IST]L[IST] m n m n R[UN]R[UN] nn nn texttext 0 0 texttext

Page 34: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL*Plus File CommandsSQL*Plus File CommandsSQL*Plus File CommandsSQL*Plus File Commands

SAVE SAVE filenamefilename GET GET filenamefilename START START filenamefilename @ @ filenamefilename EDIT EDIT filenamefilename SPOOL SPOOL filenamefilename EXITEXIT

SAVE SAVE filenamefilename GET GET filenamefilename START START filenamefilename @ @ filenamefilename EDIT EDIT filenamefilename SPOOL SPOOL filenamefilename EXITEXIT

Page 35: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SummarySummarySummarySummary

Use SQL*Plus as an environment Use SQL*Plus as an environment to:to: Execute SQL statementsExecute SQL statements Edit SQL statementsEdit SQL statements

Use SQL*Plus as an environment Use SQL*Plus as an environment to:to: Execute SQL statementsExecute SQL statements Edit SQL statementsEdit SQL statements

SELECT [DISTINCT] {*,column [alias],...}FROM table;

SELECT [DISTINCT] {*,column [alias],...}FROM table;

Page 36: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting
Page 37: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Restricting and Sorting Restricting and Sorting DataData

Restricting and Sorting Restricting and Sorting DataData

Page 38: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you After completing this lesson, you should be able to do the following:should be able to do the following: Limit the rows retrieved by a queryLimit the rows retrieved by a query Sort the rows retrieved by a querySort the rows retrieved by a query

After completing this lesson, you After completing this lesson, you should be able to do the following:should be able to do the following: Limit the rows retrieved by a queryLimit the rows retrieved by a query Sort the rows retrieved by a querySort the rows retrieved by a query

Page 39: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Limiting Rows Using a Limiting Rows Using a SelectionSelection

Limiting Rows Using a Limiting Rows Using a SelectionSelection

"…retrieve all"…retrieve allemployeesemployees

in department 10"in department 10"

EMPEMP

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ...

EMPEMP

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10 7782 CLARK MANAGER 10 7934 MILLER CLERK 10

Page 40: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Limiting Rows SelectedLimiting Rows SelectedLimiting Rows SelectedLimiting Rows Selected

Restrict the rows returned by using Restrict the rows returned by using the WHERE clause.the WHERE clause.

The WHERE clause follows the The WHERE clause follows the FROM clause.FROM clause.

Restrict the rows returned by using Restrict the rows returned by using the WHERE clause.the WHERE clause.

The WHERE clause follows the The WHERE clause follows the FROM clause.FROM clause.

SELECT [DISTINCT] {*| column [alias], ...}FROM table[WHERE condition(s)];

Page 41: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the WHERE ClauseUsing the WHERE ClauseUsing the WHERE ClauseUsing the WHERE Clause

SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE job='CLERK';

ENAME JOB DEPTNO---------- --------- ---------JAMES CLERK 30SMITH CLERK 20ADAMS CLERK 20MILLER CLERK 10

Page 42: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Character Strings and Character Strings and DatesDates

Character Strings and Character Strings and DatesDates

Character strings and date values are Character strings and date values are enclosed in single quotation marks.enclosed in single quotation marks.

Character values are case sensitive Character values are case sensitive and date values are format sensitive.and date values are format sensitive.

The default date format is DD-MON-The default date format is DD-MON-YYYY..

Character strings and date values are Character strings and date values are enclosed in single quotation marks.enclosed in single quotation marks.

Character values are case sensitive Character values are case sensitive and date values are format sensitive.and date values are format sensitive.

The default date format is DD-MON-The default date format is DD-MON-YYYY..

SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE ename = ;

SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE ename = ;'JAMES'

Page 43: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Comparison OperatorsComparison OperatorsComparison OperatorsComparison Operators

Operator

=

>

>=

<

<=

<>, !=, ^=

Meaning

Equal to

Greater than

Greater than or equal to

Less than

Less than or equal to

Not equal to

Page 44: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the Comparison Using the Comparison OperatorsOperators

Using the Comparison Using the Comparison OperatorsOperators

SQL> SELECT ename, sal, comm 2 FROM emp 3 WHERE sal<=comm;

ENAME SAL COMM---------- --------- ---------MARTIN 1250 1400

Page 45: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Other Comparison Other Comparison OperatorsOperators

Other Comparison Other Comparison OperatorsOperators

Operator

BETWEEN

...AND...

IN(list)

LIKE

IS NULL

Meaning

Between two values (inclusive)

Match any of a list of values

Match a character pattern

Is a null value

Page 46: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the BETWEEN Using the BETWEEN OperatorOperator

Using the BETWEEN Using the BETWEEN OperatorOperator

ENAME SAL---------- ---------MARTIN 1250TURNER 1500WARD 1250ADAMS 1100MILLER 1300

SQL> SELECT ename, sal 2 FROM emp 3 WHERE sal BETWEEN 1000 AND 1500;

Lowerlimit

Higherlimit

Use the BETWEEN operator to Use the BETWEEN operator to display rows based on a range of display rows based on a range of values.values.

Use the BETWEEN operator to Use the BETWEEN operator to display rows based on a range of display rows based on a range of values.values.

Page 47: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the IN OperatorUsing the IN OperatorUsing the IN OperatorUsing the IN Operator

Use the IN operator to test for Use the IN operator to test for values in a list.values in a list.

Use the IN operator to test for Use the IN operator to test for values in a list.values in a list.

SQL> SELECT empno, ename, sal, mgr 2 FROM emp 3 WHERE mgr IN (7902, 7566, 7788);

EMPNO ENAME SAL MGR--------- ---------- --------- --------- 7902 FORD 3000 7566 7369 SMITH 800 7902 7788 SCOTT 3000 7566 7876 ADAMS 1100 7788

Page 48: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the LIKE OperatorUsing the LIKE OperatorUsing the LIKE OperatorUsing the LIKE Operator• Use the LIKE operator to perform

wildcard searches of valid search string values.

• Search conditions can contain either literal characters or numbers.

– % denotes zero or many characters.

– _ denotes one character.

• Use the LIKE operator to perform wildcard searches of valid search string values.

• Search conditions can contain either literal characters or numbers.

– % denotes zero or many characters.

– _ denotes one character.

SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE 'S%';

Page 49: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the LIKE OperatorUsing the LIKE OperatorUsing the LIKE OperatorUsing the LIKE Operator

You can combine pattern-matching You can combine pattern-matching characters.characters.

You can use the ESCAPE identifier You can use the ESCAPE identifier to search for "%" or "_".to search for "%" or "_".

You can combine pattern-matching You can combine pattern-matching characters.characters.

You can use the ESCAPE identifier You can use the ESCAPE identifier to search for "%" or "_".to search for "%" or "_".

SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE '_A%';

ENAME---------- MARTINJAMES WARD

Page 50: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the IS NULL Using the IS NULL OperatorOperator

Using the IS NULL Using the IS NULL OperatorOperator

Test for null values with the IS Test for null values with the IS NULL operator.NULL operator.

Test for null values with the IS Test for null values with the IS NULL operator.NULL operator.

SQL> SELECT ename, mgr 2 FROM emp 3 WHERE mgr IS NULL;

ENAME MGR---------- ---------KING

Page 51: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Logical OperatorsLogical OperatorsLogical OperatorsLogical Operators

Operator

AND

OR

NOT

Meaning

Returns TRUE if both component

conditions are TRUE

Returns TRUE if either component

condition is TRUE

Returns TRUE if the following condition is FALSE

Page 52: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the AND OperatorUsing the AND OperatorUsing the AND OperatorUsing the AND Operator

AND requires both conditions to be TRUE.AND requires both conditions to be TRUE.

SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=1100 4 AND job='CLERK';

EMPNO ENAME JOB SAL--------- ---------- --------- --------- 7876 ADAMS CLERK 1100 7934 MILLER CLERK 1300

Page 53: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the OR OperatorUsing the OR OperatorUsing the OR OperatorUsing the OR Operator

OR requires either condition to be TRUE.OR requires either condition to be TRUE.OR requires either condition to be TRUE.OR requires either condition to be TRUE.SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=1100 4 OR job='CLERK';

EMPNO ENAME JOB SAL--------- ---------- --------- --------- 7839 KING PRESIDENT 5000 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7566 JONES MANAGER 2975 7654 MARTIN SALESMAN 1250 ... 7900 JAMES CLERK 950 ...14 rows selected.

Page 54: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the NOT OperatorUsing the NOT OperatorUsing the NOT OperatorUsing the NOT Operator

SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');

ENAME JOB---------- ---------KING PRESIDENTMARTIN SALESMANALLEN SALESMANTURNER SALESMANWARD SALESMAN

Page 55: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Rules of PrecedenceRules of PrecedenceRules of PrecedenceRules of Precedence

Override rules of precedence by Override rules of precedence by using parentheses.using parentheses.

Override rules of precedence by Override rules of precedence by using parentheses.using parentheses.

Order Evaluated Operator

1 All comparison operators

2 NOT

3 AND

4 OR

Page 56: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Rules of PrecedenceRules of PrecedenceRules of PrecedenceRules of Precedence

ENAME JOB SAL---------- --------- ---------KING PRESIDENT 5000MARTIN SALESMAN 1250ALLEN SALESMAN 1600TURNER SALESMAN 1500WARD SALESMAN 1250

ENAME JOB SAL---------- --------- ---------KING PRESIDENT 5000MARTIN SALESMAN 1250ALLEN SALESMAN 1600TURNER SALESMAN 1500WARD SALESMAN 1250

SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE job='SALESMAN' 4 OR job='PRESIDENT' 5 AND sal>1500;

Page 57: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Rules of PrecedenceRules of PrecedenceRules of PrecedenceRules of Precedence

ENAME JOB SAL---------- --------- ---------KING PRESIDENT 5000ALLEN SALESMAN 1600

ENAME JOB SAL---------- --------- ---------KING PRESIDENT 5000ALLEN SALESMAN 1600

Use parentheses to force priority.Use parentheses to force priority.Use parentheses to force priority.Use parentheses to force priority.

SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE (job='SALESMAN' 4 OR job='PRESIDENT') 5 AND sal>1500;

Page 58: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ORDER BY ClauseORDER BY ClauseORDER BY ClauseORDER BY Clause Sort rows with the ORDER BY Sort rows with the ORDER BY

clauseclause ASC: ascending order, defaultASC: ascending order, default DESC: descending orderDESC: descending order

The ORDER BY clause comes last The ORDER BY clause comes last in the SELECT statement.in the SELECT statement.

Sort rows with the ORDER BY Sort rows with the ORDER BY clauseclause ASC: ascending order, defaultASC: ascending order, default DESC: descending orderDESC: descending order

The ORDER BY clause comes last The ORDER BY clause comes last in the SELECT statement.in the SELECT statement.

SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 ORDER BY hiredate;

ENAME JOB DEPTNO HIREDATE---------- --------- --------- ---------SMITH CLERK 20 17-DEC-80ALLEN SALESMAN 30 20-FEB-81...14 rows selected.

Page 59: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Sorting in Descending Sorting in Descending OrderOrder

Sorting in Descending Sorting in Descending OrderOrder

SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIREDATE---------- --------- --------- ---------ADAMS CLERK 20 12-JAN-83SCOTT ANALYST 20 09-DEC-82MILLER CLERK 10 23-JAN-82JAMES CLERK 30 03-DEC-81FORD ANALYST 20 03-DEC-81KING PRESIDENT 10 17-NOV-81MARTIN SALESMAN 30 28-SEP-81...14 rows selected.

Page 60: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Sorting by Column AliasSorting by Column AliasSorting by Column AliasSorting by Column Alias

SQL> SELECT empno, ename, sal*12 annsal 2 FROM emp 3 ORDER BY annsal;

EMPNO ENAME ANNSAL--------- ---------- --------- 7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 15600 7844 TURNER 18000...14 rows selected.

Page 61: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Sorting by Multiple Sorting by Multiple ColumnsColumns

Sorting by Multiple Sorting by Multiple ColumnsColumns The order of ORDER BY list is the The order of ORDER BY list is the

order of sort.order of sort.

The order of ORDER BY list is the The order of ORDER BY list is the order of sort.order of sort.

• You can sort by a column that is not in the SELECT list.• You can sort by a column that is not in the

SELECT list.

SQL> SELECT ename, deptno, sal 2 FROM emp 3 ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL---------- --------- ---------KING 10 5000CLARK 10 2450MILLER 10 1300FORD 20 3000...14 rows selected.

Page 62: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SummarySummarySummarySummary

SELECT [DISTINCT] {*| column [alias], ...}FROM table[WHERE condition(s)][ORDER BY {column, expr, alias} [ASC|DESC]];

Page 63: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Practice OverviewPractice OverviewPractice OverviewPractice Overview

Selecting data and changing the order of rows displayedSelecting data and changing the order of rows displayed Restricting rows by using the WHERE clauseRestricting rows by using the WHERE clause Using the double quotation marks in column aliasesUsing the double quotation marks in column aliases

Selecting data and changing the order of rows displayedSelecting data and changing the order of rows displayed Restricting rows by using the WHERE clauseRestricting rows by using the WHERE clause Using the double quotation marks in column aliasesUsing the double quotation marks in column aliases

Page 64: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting
Page 65: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Single-Row Single-Row FunctionsFunctions

Single-Row Single-Row FunctionsFunctions

Page 66: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe various types of functions Describe various types of functions

available in SQLavailable in SQL Use character, number, and date Use character, number, and date

functions in SELECT statementsfunctions in SELECT statements Describe the use of conversion Describe the use of conversion

functions functions

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe various types of functions Describe various types of functions

available in SQLavailable in SQL Use character, number, and date Use character, number, and date

functions in SELECT statementsfunctions in SELECT statements Describe the use of conversion Describe the use of conversion

functions functions

Page 67: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL FunctionsSQL FunctionsSQL FunctionsSQL Functions

FunctionFunctionInputInput

arg 1arg 1

arg 2arg 2

arg arg nn

Function Function performs actionperforms action

OutputOutput

ResultResultvaluevalue

Page 68: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Two Types of SQL Two Types of SQL FunctionsFunctions

Two Types of SQL Two Types of SQL FunctionsFunctions

FunctionsFunctions

Single-row Single-row functionsfunctions

Multiple-rowMultiple-rowfunctionsfunctions

Page 69: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions

Manipulate data itemsManipulate data items Accept arguments and return one Accept arguments and return one

valuevalue Act on each row returnedAct on each row returned Return one result per rowReturn one result per row May modify the datatypeMay modify the datatype Can be nestedCan be nested

Manipulate data itemsManipulate data items Accept arguments and return one Accept arguments and return one

valuevalue Act on each row returnedAct on each row returned Return one result per rowReturn one result per row May modify the datatypeMay modify the datatype Can be nestedCan be nested

function_name (column|expression, [arg1, arg2,...])function_name (column|expression, [arg1, arg2,...])

Page 70: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions

ConversionConversion

CharacterCharacter

NumberNumber

DateDate

GeneralGeneralSingle-row Single-row functionsfunctions

Page 71: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Character FunctionsCharacter FunctionsCharacter FunctionsCharacter Functions

CharacterCharacterfunctionsfunctions

LOWERLOWER

UPPERUPPER

INITCAPINITCAP

CONCATCONCAT

SUBSTRSUBSTR

LENGTHLENGTH

INSTRINSTRLPAD, RPADLPAD, RPADTRIM, LTRIM, RTRIMTRIM, LTRIM, RTRIMREPLACEREPLACE

Case conversion Case conversion functionsfunctions

Character manipulationCharacter manipulationfunctionsfunctions

Page 72: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Character FunctionsCharacter Functions CONCAT – joins 2 character stringsCONCAT – joins 2 character strings INITCAP – returns a string with the initial letter only INITCAP – returns a string with the initial letter only

uppercaseuppercase LENGTH – returns the length of a stringLENGTH – returns the length of a string LPAD, RPAD – returns a string with a specific number LPAD, RPAD – returns a string with a specific number

of characters added on the left or right sideof characters added on the left or right side LTRIM, RTRIM – returns a string with all instances of LTRIM, RTRIM – returns a string with all instances of

a specific character trimmed from the left or right a specific character trimmed from the left or right sideside

REPLACE – replaces all instances of a character with REPLACE – replaces all instances of a character with another characteranother character

UPPER/LOWER – returns a string in all upper/lower UPPER/LOWER – returns a string in all upper/lower case letterscase letters

SUBSTRSUBSTR INSTRINSTR

Page 73: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Function Result

Case Conversion Case Conversion FunctionsFunctions

Case Conversion Case Conversion FunctionsFunctions

Convert case for character stringsConvert case for character strings Convert case for character stringsConvert case for character strings

LOWER('SQL Course')

UPPER('SQL Course')

INITCAP('SQL Course')

sql course

SQL COURSE

Sql Course

Page 74: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Case Conversion Using Case Conversion FunctionsFunctions

Using Case Conversion Using Case Conversion FunctionsFunctions Display the employee number, Display the employee number,

name, and department number name, and department number for employee Blake.for employee Blake.

Display the employee number, Display the employee number, name, and department number name, and department number for employee Blake.for employee Blake.SQL> SELECT empno, ename, deptno

2 FROM emp 3 WHERE ename = 'blake';no rows selectedno rows selected

SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake';no rows selectedno rows selected

EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30

EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30

SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = UPPER('blake');

Page 75: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

CONCAT('Good', 'String')

SUBSTR('String',1,3)

LENGTH('String')

INSTR('String', 'r')

LPAD(sal,10,'*')

TRIM('S' FROM 'SSMITH')

GoodString

Str

6

3

******5000

MITH

Function Result

Character Manipulation Character Manipulation FunctionsFunctions

Character Manipulation Character Manipulation FunctionsFunctions

Manipulate character stringsManipulate character strings Manipulate character stringsManipulate character strings

Page 76: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the Character Using the Character Manipulation FunctionsManipulation Functions

Using the Character Using the Character Manipulation FunctionsManipulation Functions

SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename), 2 INSTR(ename, 'A') 3 FROM emp 4 WHERE SUBSTR(job,1,5) = 'SALES';

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')---------- ------------------- ------------- ----------------MARTIN MARTINSALESMAN 6 2ALLEN ALLENSALESMAN 5 1TURNER TURNERSALESMAN 6 0WARD WARDSALESMAN 4 2

Page 77: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Number FunctionsNumber Functions ABS - absolute valueABS - absolute value CEIL – rounds a number up to the next CEIL – rounds a number up to the next

integerinteger FLOOR – rounds a number down to the FLOOR – rounds a number down to the

previous integerprevious integer MOD – returns the remainder of a number MOD – returns the remainder of a number

and a divisorand a divisor POWER - raises a number to an exponentPOWER - raises a number to an exponent ROUND - rounds a numberROUND - rounds a number SQRT – returns the square root of a valueSQRT – returns the square root of a value TRUNC - truncates a number to the nearest TRUNC - truncates a number to the nearest

whole numberwhole number

Page 78: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Number FunctionsNumber FunctionsNumber FunctionsNumber Functions

ROUND: Rounds value to specified ROUND: Rounds value to specified

decimaldecimalROUND(45.926, 2)ROUND(45.926, 2)

45.9345.93 TRUNC:TRUNC: Truncates value to specified Truncates value to specified

decimaldecimalTRUNC(45.926, 2)TRUNC(45.926, 2)

45.92 45.92

MOD: Returns remainder of divisionMOD: Returns remainder of divisionMOD(1600, 300)MOD(1600, 300)

100 100

ROUND: Rounds value to specified ROUND: Rounds value to specified

decimaldecimalROUND(45.926, 2)ROUND(45.926, 2)

45.9345.93 TRUNC:TRUNC: Truncates value to specified Truncates value to specified

decimaldecimalTRUNC(45.926, 2)TRUNC(45.926, 2)

45.92 45.92

MOD: Returns remainder of divisionMOD: Returns remainder of divisionMOD(1600, 300)MOD(1600, 300)

100 100

Page 79: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the ROUND Using the ROUND FunctionFunction

Using the ROUND Using the ROUND FunctionFunction

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0), 2 ROUND(45.923,-1) 3 FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)--------------- -------------- ----------------- 45.92 46 50

Page 80: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923), 2 TRUNC(45.923,-1) 3 FROM DUAL;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)--------------- ------------- --------------- 45.92 45 40

Using the TRUNC Using the TRUNC FunctionFunction

Using the TRUNC Using the TRUNC FunctionFunction

Page 81: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the MOD FunctionUsing the MOD FunctionUsing the MOD FunctionUsing the MOD Function

Calculate the remainder of the Calculate the remainder of the ratio of salary to commission for ratio of salary to commission for all employees whose job title is all employees whose job title is salesman.salesman.

Calculate the remainder of the Calculate the remainder of the ratio of salary to commission for ratio of salary to commission for all employees whose job title is all employees whose job title is salesman.salesman.SQL> SELECT ename, sal, comm, MOD(sal, comm)

2 FROM emp 3 WHERE job = 'SALESMAN';

ENAME SAL COMM MOD(SAL,COMM)---------- --------- --------- -------------MARTIN 1250 1400 1250ALLEN 1600 300 100TURNER 1500 0 1500WARD 1250 500 250

Page 82: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Working with DatesWorking with DatesWorking with DatesWorking with Dates

Oracle stores dates in an internal Oracle stores dates in an internal numeric format: century, year, numeric format: century, year, month, day, hours, minutes, month, day, hours, minutes, seconds.seconds.

The default date format is DD-The default date format is DD-MON-YY.MON-YY.

SYSDATE is a function returning SYSDATE is a function returning date and time.date and time.

DUAL is a dummy table used to DUAL is a dummy table used to view SYSDATE.view SYSDATE.

Oracle stores dates in an internal Oracle stores dates in an internal numeric format: century, year, numeric format: century, year, month, day, hours, minutes, month, day, hours, minutes, seconds.seconds.

The default date format is DD-The default date format is DD-MON-YY.MON-YY.

SYSDATE is a function returning SYSDATE is a function returning date and time.date and time.

DUAL is a dummy table used to DUAL is a dummy table used to view SYSDATE.view SYSDATE.

Page 83: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Arithmetic with DatesArithmetic with DatesArithmetic with DatesArithmetic with Dates

Add or subtract a number to or Add or subtract a number to or from a date for a resultant from a date for a resultant datedate value.value.

Subtract two dates to find the Subtract two dates to find the numbernumber of days between those of days between those dates.dates.

Add Add hourshours to a date by dividing the to a date by dividing the number of hours by 24.number of hours by 24.

Add or subtract a number to or Add or subtract a number to or from a date for a resultant from a date for a resultant datedate value.value.

Subtract two dates to find the Subtract two dates to find the numbernumber of days between those of days between those dates.dates.

Add Add hourshours to a date by dividing the to a date by dividing the number of hours by 24.number of hours by 24.

Page 84: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date ArithmeticDate Arithmetic

To find a date that is a specific To find a date that is a specific number of days before or after a number of days before or after a known date, add or subtract the known date, add or subtract the number from the known datenumber from the known date

Example:Example:SELECT order_date + 30 SELECT order_date + 30

FROM cust_order;FROM cust_order;

Page 85: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date ArithmeticDate Arithmetic

To find the number of days To find the number of days between two known dates, between two known dates, subtract the later date from the subtract the later date from the earlier dateearlier date

Example:Example:SELECT SYSDATE – s_dobSELECT SYSDATE – s_dob

FROM my_students;FROM my_students;

Page 86: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Arithmetic Using Arithmetic OperatorsOperatorswith Dateswith Dates

Using Arithmetic Using Arithmetic OperatorsOperatorswith Dateswith Dates

SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS 2 FROM emp 3 WHERE deptno = 10;

ENAME WEEKS---------- ---------KING 830.93709CLARK 853.93709MILLER 821.36566

Page 87: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date FunctionsDate FunctionsDate FunctionsDate Functions

Number of monthsbetween two dates

MONTHS_BETWEEN

ADD_MONTHS

NEXT_DAY

LAST_DAY

ROUND

TRUNC

Add calendar months to date

Next day of the date specified

Last day of the month

Round date

Truncate date

Function Description

Page 88: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')

Using Date FunctionsUsing Date FunctionsUsing Date FunctionsUsing Date Functions

• ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)

• NEXT_DAY ('01-SEP-95','FRIDAY') NEXT_DAY ('01-SEP-95','FRIDAY')

• LAST_DAY('01-SEP-95')LAST_DAY('01-SEP-95')

19.677419419.6774194

'11-JUL-94''11-JUL-94'

'08-SEP-95''08-SEP-95'

'30-SEP-95''30-SEP-95'

Page 89: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Date FunctionsUsing Date FunctionsUsing Date FunctionsUsing Date Functions

• ROUND('25-JUL-95','MONTH') 01-AUG-95ROUND('25-JUL-95','MONTH') 01-AUG-95

• ROUND('25-JUL-95','YEAR') ROUND('25-JUL-95','YEAR') 01-JAN-96 01-JAN-96

• TRUNC('25-JUL-95','MONTH') TRUNC('25-JUL-95','MONTH') 01-JUL-95 01-JUL-95

• TRUNC('25-JUL-95','YEAR')TRUNC('25-JUL-95','YEAR') 01-JAN- 01-JAN-9595

Page 90: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date FunctionsDate Functions

ADD_MONTHSADD_MONTHS returns a date that is a specific number returns a date that is a specific number

of months after a given dateof months after a given date

Example:Example:SELECT ADD_MONTHS(SYSDATE, 6) SELECT ADD_MONTHS(SYSDATE, 6)

FROM dual;FROM dual;

Page 91: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date FunctionsDate Functions

LAST_DATELAST_DATE Returns the date that is the last day of Returns the date that is the last day of

the month specified in the current datethe month specified in the current date

Example:Example:SELECT LAST_DATE(order_date) SELECT LAST_DATE(order_date)

FROM cust_orderFROM cust_order

WHERE order_id = 1057;WHERE order_id = 1057;

Page 92: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Date FunctionsDate Functions

MONTHS_BETWEENMONTHS_BETWEEN Returns the number of months Returns the number of months

between two input datesbetween two input dates

Example:Example:SELECT MONTHS_BETWEEN(order_date, SELECT MONTHS_BETWEEN(order_date, SYSDATE) SYSDATE)

FROM cust_orderFROM cust_orderWHERE order_id = 1057;WHERE order_id = 1057;

Page 93: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Conversion FunctionsConversion FunctionsConversion FunctionsConversion Functions

Implicit datatypeImplicit datatypeconversionconversion

Explicit datatypeExplicit datatypeconversionconversion

DatatypeDatatypeconversionconversion

Page 94: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Implicit Datatype Implicit Datatype ConversionConversion

Implicit Datatype Implicit Datatype ConversionConversion

For assignments, the Oracle For assignments, the Oracle Server can automatically convert Server can automatically convert the following:the following:

For assignments, the Oracle For assignments, the Oracle Server can automatically convert Server can automatically convert the following:the following:

VARCHAR2 or CHAR

From To

VARCHAR2 or CHAR

NUMBER

DATE

NUMBER

DATE

VARCHAR2

VARCHAR2

Page 95: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Implicit Datatype Implicit Datatype ConversionConversion

Implicit Datatype Implicit Datatype ConversionConversion

For expression evaluation, the For expression evaluation, the Oracle Server can automatically Oracle Server can automatically convert the following:convert the following:

For expression evaluation, the For expression evaluation, the Oracle Server can automatically Oracle Server can automatically convert the following:convert the following:VARCHAR2 or CHAR

From To

VARCHAR2 or CHAR

NUMBER

DATE

Page 96: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Explicit Datatype Explicit Datatype ConversionConversion

Explicit Datatype Explicit Datatype ConversionConversion

NUMBERNUMBER CHARACTERCHARACTER

TO_CHARTO_CHAR

TO_NUMBERTO_NUMBER

DATEDATE

TO_CHARTO_CHAR

TO_DATETO_DATE

Page 97: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

TO_CHAR Function with TO_CHAR Function with DatesDates

TO_CHAR Function with TO_CHAR Function with DatesDates

The format model: Must be enclosed in single quotation Must be enclosed in single quotation

marks and is case sensitivemarks and is case sensitive Can include any valid date format Can include any valid date format

elementelement Has an Has an fmfm element to remove padded element to remove padded

blanks or suppress leading zerosblanks or suppress leading zeros Is separated from the date value by a Is separated from the date value by a

commacomma

The format model: Must be enclosed in single quotation Must be enclosed in single quotation

marks and is case sensitivemarks and is case sensitive Can include any valid date format Can include any valid date format

elementelement Has an Has an fmfm element to remove padded element to remove padded

blanks or suppress leading zerosblanks or suppress leading zeros Is separated from the date value by a Is separated from the date value by a

commacomma

TO_CHAR(date, 'fmt')TO_CHAR(date, 'fmt')

Page 98: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

YYYY

Elements of Date Format Elements of Date Format ModelModel

Elements of Date Format Elements of Date Format ModelModel

YEAR

MM

MONTH

DY

DAY

Full year in numbers

Year spelled out

Two-digit value for month

Three-letter abbreviation of the day of the week

Full name of the day

Full name of the month

Page 99: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Elements of Date Format Elements of Date Format ModelModel

Elements of Date Format Elements of Date Format ModelModel

Time elements format the time Time elements format the time portion of the date.portion of the date.

Add character strings by Add character strings by enclosing them in double enclosing them in double quotation marks.quotation marks.

Number suffixes spell out Number suffixes spell out numbers.numbers.

Time elements format the time Time elements format the time portion of the date.portion of the date.

Add character strings by Add character strings by enclosing them in double enclosing them in double quotation marks.quotation marks.

Number suffixes spell out Number suffixes spell out numbers.numbers.

HH24:MI:SS AM 15:45:32 PM

DD "of" MONTH 12 of OCTOBER

ddspth fourteenth

Page 100: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using TO_CHAR Using TO_CHAR Function Function with Dateswith Dates

Using TO_CHAR Using TO_CHAR Function Function with Dateswith DatesSQL> SELECT ename,

2 TO_CHAR(hiredate, 'fmDD Month YYYY') HIREDATE 3 FROM emp;

ENAME HIREDATE---------- -----------------KING 17 November 1981BLAKE 1 May 1981CLARK 9 June 1981JONES 2 April 1981MARTIN 28 September 1981ALLEN 20 February 1981...14 rows selected.

Page 101: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

TO_CHAR Function with TO_CHAR Function with NumbersNumbers

TO_CHAR Function with TO_CHAR Function with NumbersNumbers

Use these formats with the Use these formats with the TO_CHAR function to display a TO_CHAR function to display a number value as a character:number value as a character:

Use these formats with the Use these formats with the TO_CHAR function to display a TO_CHAR function to display a number value as a character:number value as a character:

TO_CHAR(number, 'fmt')TO_CHAR(number, 'fmt')

9

0

$

L

.

,

Represents a number

Forces a zero to be displayed

Places a floating dollar sign

Uses the floating local currency symbol

Prints a decimal point

Prints a thousand indicator

Page 102: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using TO_CHAR Using TO_CHAR Function Function

with Numberswith Numbers

Using TO_CHAR Using TO_CHAR Function Function

with Numberswith NumbersSQL> SELECT TO_CHAR(sal,'$99,999') SALARY 2 FROM emp 3 WHERE ename = 'SCOTT';

SALARY-------- $3,000

Page 103: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

TO_NUMBER and TO_NUMBER and TO_DATE Functions TO_DATE Functions

TO_NUMBER and TO_NUMBER and TO_DATE Functions TO_DATE Functions Convert a character string to a Convert a character string to a

number format using the number format using the TO_NUMBERTO_NUMBER function function

Convert a character string to a Convert a character string to a number format using the number format using the TO_NUMBERTO_NUMBER function function

TO_NUMBER(char[, 'fmt'])TO_NUMBER(char[, 'fmt'])

• Convert a character string to a date format using the TO_DATE function• Convert a character string to a date

format using the TO_DATE function

TO_DATE(char[, 'fmt'])TO_DATE(char[, 'fmt'])

Page 104: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

NVL FunctionNVL FunctionNVL FunctionNVL Function

Converts null to an actual valueConverts null to an actual value Datatypes that can be used are Datatypes that can be used are

date, character, and number.date, character, and number. Datatypes must match Datatypes must match

NVL(comm,0)NVL(comm,0) NVL(hiredate,'01-JAN-97')NVL(hiredate,'01-JAN-97') NVL(job,'No Job Yet')NVL(job,'No Job Yet')

Converts null to an actual valueConverts null to an actual value Datatypes that can be used are Datatypes that can be used are

date, character, and number.date, character, and number. Datatypes must match Datatypes must match

NVL(comm,0)NVL(comm,0) NVL(hiredate,'01-JAN-97')NVL(hiredate,'01-JAN-97') NVL(job,'No Job Yet')NVL(job,'No Job Yet')

Page 105: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0) 2 FROM emp;

Using the NVL FunctionUsing the NVL FunctionUsing the NVL FunctionUsing the NVL Function

ENAME SAL COMM (SAL*12)+NVL(COMM,0)---------- --------- --------- --------------------KING 5000 60000BLAKE 2850 34200CLARK 2450 29400JONES 2975 35700MARTIN 1250 1400 16400ALLEN 1600 300 19500...14 rows selected.

Page 106: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Nesting FunctionsNesting FunctionsNesting FunctionsNesting Functions

Single-row functions can be nested to Single-row functions can be nested to any level.any level.

Nested functions are evaluated from Nested functions are evaluated from deepest level to the least-deep level.deepest level to the least-deep level.

Single-row functions can be nested to Single-row functions can be nested to any level.any level.

Nested functions are evaluated from Nested functions are evaluated from deepest level to the least-deep level.deepest level to the least-deep level.

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1

Step 2 = Result 2

Step 3 = Result 3

Page 107: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Nesting FunctionsNesting FunctionsNesting FunctionsNesting Functions

SQL> SELECT ename, 2 NVL(TO_CHAR(mgr),'No Manager') 3 FROM emp 4 WHERE mgr IS NULL;

ENAME NVL(TO_CHAR(MGR),'NOMANAGER')---------- -----------------------------KING No Manager

Page 108: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SummarySummarySummarySummary

Use functions to do the Use functions to do the following:following: Perform calculations on dataPerform calculations on data Modify individual data itemsModify individual data items Manipulate output for groups of Manipulate output for groups of

rowsrows Alter date formats for displayAlter date formats for display Convert column datatypesConvert column datatypes

Use functions to do the Use functions to do the following:following: Perform calculations on dataPerform calculations on data Modify individual data itemsModify individual data items Manipulate output for groups of Manipulate output for groups of

rowsrows Alter date formats for displayAlter date formats for display Convert column datatypesConvert column datatypes

Page 109: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting
Page 110: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Aggregating Data Aggregating Data Using Group Using Group

FunctionsFunctions(multiple row functions)(multiple row functions)

Aggregating Data Aggregating Data Using Group Using Group

FunctionsFunctions(multiple row functions)(multiple row functions)

Page 111: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Identify the available group Identify the available group

functionsfunctions Describe the use of group functionsDescribe the use of group functions Group data using the GROUP BY Group data using the GROUP BY

clauseclause Include or exclude grouped rows Include or exclude grouped rows

by using the HAVING clauseby using the HAVING clause

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Identify the available group Identify the available group

functionsfunctions Describe the use of group functionsDescribe the use of group functions Group data using the GROUP BY Group data using the GROUP BY

clauseclause Include or exclude grouped rows Include or exclude grouped rows

by using the HAVING clauseby using the HAVING clause

Page 112: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

What Are Group What Are Group Functions?Functions?

What Are Group What Are Group Functions?Functions? Group functions operate on sets of Group functions operate on sets of

rows to give one result per group.rows to give one result per group. Group functions operate on sets of Group functions operate on sets of

rows to give one result per group.rows to give one result per group.EMPEMP

““maximum maximum salary in salary in

the EMP table”the EMP table”

DEPTNO SAL--------- --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250

MAX(SAL)

---------

5000

Page 113: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Types of Group Types of Group FunctionsFunctions

Types of Group Types of Group FunctionsFunctions

AVG AVG COUNT COUNT COUNT(*)COUNT(*) MAXMAX MIN MIN SUMSUM

AVG AVG COUNT COUNT COUNT(*)COUNT(*) MAXMAX MIN MIN SUMSUM

Page 114: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using Group FunctionsUsing Group FunctionsUsing Group FunctionsUsing Group Functions

SELECT [column,] group_function(column)FROM table[WHERE condition][GROUP BY column][ORDER BY column];

Page 115: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using AVG and SUM Using AVG and SUM FunctionsFunctions

Using AVG and SUM Using AVG and SUM FunctionsFunctions

AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)-------- --------- --------- --------- 1400 1600 1250 5600

You can use AVG and SUM for numeric You can use AVG and SUM for numeric data.data.

You can use AVG and SUM for numeric You can use AVG and SUM for numeric data.data.SQL> SELECT AVG(sal), MAX(sal),

2 MIN(sal), SUM(sal) 3 FROM emp 4 WHERE job LIKE 'SALES%';

Page 116: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using MIN and MAX Using MIN and MAX FunctionsFunctions

Using MIN and MAX Using MIN and MAX FunctionsFunctions

You can use MIN and MAX for any You can use MIN and MAX for any datatype.datatype.

You can use MIN and MAX for any You can use MIN and MAX for any datatype.datatype.SQL> SELECT MIN(hiredate), MAX(hiredate) 2 FROM emp;

MIN(HIRED MAX(HIRED--------- ---------17-DEC-80 12-JAN-83

Page 117: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the COUNT Using the COUNT FunctionFunction

Using the COUNT Using the COUNT FunctionFunction

COUNT(*)--------- 6

SQL> SELECT COUNT(*) 2 FROM emp 3 WHERE deptno = 30;

COUNT(*) returns the number of COUNT(*) returns the number of rows in a table.rows in a table.

COUNT(*) returns the number of COUNT(*) returns the number of rows in a table.rows in a table.

Page 118: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the COUNT Using the COUNT FunctionFunction

Using the COUNT Using the COUNT FunctionFunction

COUNT(COUNT(exprexpr) returns the ) returns the number of nonnull rows.number of nonnull rows.

COUNT(COUNT(exprexpr) returns the ) returns the number of nonnull rows.number of nonnull rows.

SQL> SELECT COUNT(comm) 2 FROM emp 3 WHERE deptno = 30;

COUNT(COMM)----------- 4

Page 119: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Group Functions and Group Functions and Null ValuesNull Values

Group Functions and Group Functions and Null ValuesNull Values Group functions ignore null Group functions ignore null

values in the column.values in the column.

Group functions ignore null Group functions ignore null values in the column.values in the column.

SQL> SELECT AVG(comm) 2 FROM emp;

AVG(COMM)--------- 550

Page 120: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the NVL Function Using the NVL Function with Group Functionswith Group Functions

Using the NVL Function Using the NVL Function with Group Functionswith Group Functions

The NVL function forces group The NVL function forces group functions to include null values.functions to include null values.

The NVL function forces group The NVL function forces group functions to include null values.functions to include null values.

SQL> SELECT AVG(NVL(comm,0)) 2 FROM emp;

AVG(NVL(COMM,0))---------------- 157.14286

Page 121: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Creating Groups of Creating Groups of Data Data

Creating Groups of Creating Groups of Data Data EMPEMP

““averageaveragesalary salary in EMPin EMPtable table

for each for each department”department”

2916.66672916.6667

21752175

1566.66671566.6667

DEPTNO SAL--------- --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250

DEPTNO AVG(SAL)

------- ---------

10 2916.6667

20 2175

30 1566.6667

Page 122: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Creating Groups of Creating Groups of Data: Data:

GROUP BY ClauseGROUP BY Clause

Creating Groups of Creating Groups of Data: Data:

GROUP BY ClauseGROUP BY ClauseSELECT column, group_function(column)FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];

Divide rows in a table into Divide rows in a table into smaller groups by using the smaller groups by using the GROUP BY clause.GROUP BY clause.

Divide rows in a table into Divide rows in a table into smaller groups by using the smaller groups by using the GROUP BY clause.GROUP BY clause.

Page 123: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the GROUP BY Using the GROUP BY Clause Clause

Using the GROUP BY Using the GROUP BY Clause Clause

All columns in the SELECT list All columns in the SELECT list that are not in group functions that are not in group functions must be in the GROUP BY clause.must be in the GROUP BY clause.

All columns in the SELECT list All columns in the SELECT list that are not in group functions that are not in group functions must be in the GROUP BY clause.must be in the GROUP BY clause.

SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno;

DEPTNO AVG(SAL)--------- --------- 10 2916.6667 20 2175 30 1566.6667

Page 124: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the GROUP BY Using the GROUP BY Clause Clause

Using the GROUP BY Using the GROUP BY Clause Clause

The GROUP BY column does not The GROUP BY column does not have to be in the SELECT list.have to be in the SELECT list.

The GROUP BY column does not The GROUP BY column does not have to be in the SELECT list.have to be in the SELECT list.

SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno;

AVG(SAL)--------- 2916.6667 21751566.6667

Page 125: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Grouping by More Grouping by More Than One ColumnThan One ColumnGrouping by More Grouping by More Than One ColumnThan One Column

EMPEMP

““sum salaries in sum salaries in the EMP tablethe EMP tablefor each job, for each job, grouped by grouped by department”department”

DEPTNO JOB SAL

--------- --------- ---------

10 MANAGER 2450

10 PRESIDENT 5000

10 CLERK 1300

20 CLERK 800

20 CLERK 1100

20 ANALYST 3000

20 ANALYST 3000

20 MANAGER 2975

30 SALESMAN 1600

30 MANAGER 2850

30 SALESMAN 1250

30 CLERK 950

30 SALESMAN 1500

30 SALESMAN 1250

JOB SUM(SAL)

--------- ---------

CLERK 1300

MANAGER 2450

PRESIDENT 5000

ANALYST 6000

CLERK 1900

MANAGER 2975

CLERK 950

MANAGER 2850

SALESMAN 5600

DEPTNO

--------

10

10

10

20

20

20

30

30

30

Page 126: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the GROUP BY Using the GROUP BY Clause Clause

on Multiple Columnson Multiple Columns

Using the GROUP BY Using the GROUP BY Clause Clause

on Multiple Columnson Multiple ColumnsSQL> SELECT deptno, job, sum(sal) 2 FROM emp 3 GROUP BY deptno, job;

DEPTNO JOB SUM(SAL)--------- --------- --------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900...9 rows selected.

Page 127: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions

Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions Any column or expression in the Any column or expression in the

SELECT list that is not an SELECT list that is not an aggregate function must be in the aggregate function must be in the GROUP BY clause.GROUP BY clause.

Any column or expression in the Any column or expression in the SELECT list that is not an SELECT list that is not an aggregate function must be in the aggregate function must be in the GROUP BY clause.GROUP BY clause.SQL> SELECT deptno, COUNT(ename)

2 FROM emp;

SQL> SELECT deptno, COUNT(ename) 2 FROM emp;

SELECT deptno, COUNT(ename) *ERROR at line 1:ORA-00937: not a single-group group function

SELECT deptno, COUNT(ename) *ERROR at line 1:ORA-00937: not a single-group group function

Column missing in the GROUP BY clause

Column missing in the GROUP BY clause

Column missing in the GROUP BY clause

Column missing in the GROUP BY clause

Page 128: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions

Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions You cannot use the WHERE clause to You cannot use the WHERE clause to

restrict groups.restrict groups. You use the HAVING clause to restrict You use the HAVING clause to restrict

groups.groups.

You cannot use the WHERE clause to You cannot use the WHERE clause to restrict groups.restrict groups.

You use the HAVING clause to restrict You use the HAVING clause to restrict groups.groups.

SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 WHERE AVG(sal) > 2000 4 GROUP BY deptno;

SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 WHERE AVG(sal) > 2000 4 GROUP BY deptno;

WHERE AVG(sal) > 2000 *ERROR at line 3:ORA-00934: group function is not allowed here

WHERE AVG(sal) > 2000 *ERROR at line 3:ORA-00934: group function is not allowed here

Cannot use the WHERE clause

Cannot use the WHERE clause

to

restrict groups

to restrict groups

Cannot use the WHERE clause

Cannot use the WHERE clause

to

restrict groups

to restrict groups

Page 129: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Excluding Group ResultsExcluding Group ResultsExcluding Group ResultsExcluding Group Results

““maximummaximumsalarysalary

per departmentper departmentgreater thangreater than

$2900”$2900”

EMPEMP

50005000

30003000

28502850

DEPTNO SAL

--------- ---------

10 2450

10 5000

10 1300

20 800

20 1100

20 3000

20 3000

20 2975

30 1600

30 2850

30 1250

30 950

30 1500

30 1250

DEPTNO MAX(SAL)

--------- ---------

10 5000

20 3000

Page 130: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Excluding Group Results: Excluding Group Results: HAVING ClauseHAVING Clause

Excluding Group Results: Excluding Group Results: HAVING ClauseHAVING Clause

Use the HAVING clause to restrict Use the HAVING clause to restrict groupsgroups Rows are grouped.Rows are grouped. The group function is applied.The group function is applied. Groups matching the HAVING clause Groups matching the HAVING clause

are displayed.are displayed.

Use the HAVING clause to restrict Use the HAVING clause to restrict groupsgroups Rows are grouped.Rows are grouped. The group function is applied.The group function is applied. Groups matching the HAVING clause Groups matching the HAVING clause

are displayed.are displayed.SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

Page 131: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the HAVING Using the HAVING ClauseClause

Using the HAVING Using the HAVING ClauseClause

SQL> SELECT deptno, max(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING max(sal)>2900;

DEPTNO MAX(SAL)--------- --------- 10 5000 20 3000

Page 132: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Using the HAVING Using the HAVING ClauseClause

Using the HAVING Using the HAVING ClauseClause

SQL> SELECT job, SUM(sal) PAYROLL 2 FROM emp 3 WHERE job NOT LIKE 'SALES%' 4 GROUP BY job 6 ORDER BY SUM(sal);

JOB PAYROLL--------- ---------ANALYST 6000MANAGER 8275

5 HAVING SUM(sal)>5000

Page 133: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Nesting Group FunctionsNesting Group FunctionsNesting Group FunctionsNesting Group Functions

SQL> SELECT max(avg(sal)) 2 FROM emp 3 GROUP BY deptno;

MAX(AVG(SAL))------------- 2916.6667

Display the maximum average Display the maximum average salary. salary.

Display the maximum average Display the maximum average salary. salary.

Page 134: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SummarySummarySummarySummarySELECT column, group_function(column)FROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

Order of evaluation of the clauses:Order of evaluation of the clauses: WHERE clauseWHERE clause GROUP BY clauseGROUP BY clause HAVING clause HAVING clause

Order of evaluation of the clauses:Order of evaluation of the clauses: WHERE clauseWHERE clause GROUP BY clauseGROUP BY clause HAVING clause HAVING clause

Page 135: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting
Page 136: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Manipulating DataManipulating DataManipulating DataManipulating Data

Page 137: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe each DML statementDescribe each DML statement Insert rows into a tableInsert rows into a table Update rows in a tableUpdate rows in a table Delete rows from a tableDelete rows from a table Control transactionsControl transactions

After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: Describe each DML statementDescribe each DML statement Insert rows into a tableInsert rows into a table Update rows in a tableUpdate rows in a table Delete rows from a tableDelete rows from a table Control transactionsControl transactions

Page 138: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Data Manipulation Data Manipulation LanguageLanguage

Data Manipulation Data Manipulation LanguageLanguage

A DML statement is executed when A DML statement is executed when you:you: Add new rows to a tableAdd new rows to a table Modify existing rows in a tableModify existing rows in a table Remove existing rows from a tableRemove existing rows from a table

A A transactiontransaction consists of a consists of a collection of DML statements that collection of DML statements that form a logical unit of work.form a logical unit of work.

A DML statement is executed when A DML statement is executed when you:you: Add new rows to a tableAdd new rows to a table Modify existing rows in a tableModify existing rows in a table Remove existing rows from a tableRemove existing rows from a table

A A transactiontransaction consists of a consists of a collection of DML statements that collection of DML statements that form a logical unit of work.form a logical unit of work.

Page 139: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

TransactionsTransactions TransactionTransaction: series of action queries that : series of action queries that

represent a logical unit of workrepresent a logical unit of work consisting of one or more SQL DML commands consisting of one or more SQL DML commands

INSERT, UPDATE, DELETEINSERT, UPDATE, DELETE All transaction commands must succeed or none can All transaction commands must succeed or none can

succeedsucceed User can commit (save) changesUser can commit (save) changes User can roll back (discard) changesUser can roll back (discard) changes

Pending transactionPending transaction: a transaction waiting to : a transaction waiting to be committed or rolled backbe committed or rolled back Oracle DBMS locks records associated with pending Oracle DBMS locks records associated with pending

transactionstransactions Other users cannot view or modify locked recordsOther users cannot view or modify locked records

Page 140: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Adding a New Row to a Adding a New Row to a TableTable

Adding a New Row to a Adding a New Row to a TableTable

DEPT DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

New rowNew row

50 DEVELOPMENT DETROIT

DEPT DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

“…“…insert a new row insert a new row into DEPT table…”into DEPT table…”

50 DEVELOPMENT DETROIT

Page 141: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

The INSERT StatementThe INSERT StatementThe INSERT StatementThe INSERT Statement

Add new rows to a table by using Add new rows to a table by using the INSERT statement.the INSERT statement.

Only one row is inserted at a time Only one row is inserted at a time with this syntax.with this syntax.

Add new rows to a table by using Add new rows to a table by using the INSERT statement.the INSERT statement.

Only one row is inserted at a time Only one row is inserted at a time with this syntax.with this syntax.

INSERT INTO table [(column [, column...])]VALUES (value [, value...]);

INSERT INTO table [(column [, column...])]VALUES (value [, value...]);

Page 142: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Inserting New RowsInserting New RowsInserting New RowsInserting New Rows

Insert a new row containing values Insert a new row containing values for each column.for each column.

List values in the default order of List values in the default order of the columns in the table. the columns in the table.

Optionally list the columns in the Optionally list the columns in the INSERT clause.INSERT clause.

Enclose character and date values Enclose character and date values within single quotation marks.within single quotation marks.

Insert a new row containing values Insert a new row containing values for each column.for each column.

List values in the default order of List values in the default order of the columns in the table. the columns in the table.

Optionally list the columns in the Optionally list the columns in the INSERT clause.INSERT clause.

Enclose character and date values Enclose character and date values within single quotation marks.within single quotation marks.

SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'DEVELOPMENT', 'DETROIT');1 row created.1 row created.

Page 143: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Inserting Rows with Null Inserting Rows with Null ValuesValues

Inserting Rows with Null Inserting Rows with Null ValuesValues

Implicit method: Omit the column Implicit method: Omit the column from the column list.from the column list.

Implicit method: Omit the column Implicit method: Omit the column from the column list.from the column list.

SQL> INSERT INTO dept (deptno, dname ) 2 VALUES (60, 'MIS');1 row created.1 row created.

• Explicit method: Specify the NULL keyword.• Explicit method: Specify the NULL

keyword.

SQL> INSERT INTO dept 2 VALUES (70, 'FINANCE', NULL);1 row created.1 row created.

Page 144: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Inserting Special ValuesInserting Special ValuesInserting Special ValuesInserting Special Values

The SYSDATE function records The SYSDATE function records the current date and time.the current date and time.

The SYSDATE function records The SYSDATE function records the current date and time.the current date and time.

SQL> INSERT INTO emp (empno, ename, job, 2 mgr, hiredate, sal, comm, 3 deptno) 4 VALUES (7196, 'GREEN', 'SALESMAN', 5 7782, SYSDATE, 2000, NULL, 6 10);1 row created.1 row created.

Page 145: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Inserting Specific Date Inserting Specific Date ValuesValues

Inserting Specific Date Inserting Specific Date ValuesValues

Add a new employee.Add a new employee. Add a new employee.Add a new employee.SQL> INSERT INTO emp 2 VALUES (2296,'AROMANO','SALESMAN',7782, 3 TO_DATE('FEB 3, 1997', 'MON DD, YYYY'), 4 1300, NULL, 10);1 row created.1 row created.

• Verify your addition.• Verify your addition.EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO----- ------- -------- ---- --------- ---- ---- ------ 2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10

Page 146: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Inserting Values by Inserting Values by Using Substitution Using Substitution

VariablesVariables

Inserting Values by Inserting Values by Using Substitution Using Substitution

VariablesVariables Create an interactive script by using Create an interactive script by using SQL*Plus substitution parameters.SQL*Plus substitution parameters.

Create an interactive script by using Create an interactive script by using SQL*Plus substitution parameters.SQL*Plus substitution parameters.SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (&department_id, 3 '&department_name', '&location');

Enter value for department_id: 8080Enter value for department_name: EDUCATIONEDUCATIONEnter value for location: ATLANTAATLANTA

1 row created.

Page 147: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Creating a Script Creating a Script with Customized with Customized

PromptsPrompts

Creating a Script Creating a Script with Customized with Customized

PromptsPrompts ACCEPT stores the value in a variable.ACCEPT stores the value in a variable. PROMPT displays your customized text.PROMPT displays your customized text.

ACCEPT stores the value in a variable.ACCEPT stores the value in a variable. PROMPT displays your customized text.PROMPT displays your customized text.

ACCEPT department_id PROMPT 'Please enter the -

department number:'

ACCEPT department_name PROMPT 'Please enter -

the department name:'

ACCEPT location PROMPT 'Please enter the -

location:'

INSERT INTO dept (deptno, dname, loc)

VALUES (&department_id, '&department_name',

'&location');

Page 148: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Copying Rows Copying Rows from Another Tablefrom Another Table

Copying Rows Copying Rows from Another Tablefrom Another Table Write your INSERT statement with Write your INSERT statement with

a subquery.a subquery.

Do not use the VALUES clause.Do not use the VALUES clause. Match the number of columns in Match the number of columns in

the INSERT clause to those in the the INSERT clause to those in the subquery.subquery.

Write your INSERT statement with Write your INSERT statement with a subquery.a subquery.

Do not use the VALUES clause.Do not use the VALUES clause. Match the number of columns in Match the number of columns in

the INSERT clause to those in the the INSERT clause to those in the subquery.subquery.

SQL> INSERT INTO managers(id, name, salary, hiredate) 2 SELECT empno, ename, sal, hiredate 3 FROM emp 4 WHERE job = 'MANAGER';3 rows created.3 rows created.

Page 149: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Changing Data in a TableChanging Data in a TableChanging Data in a TableChanging Data in a TableEMPEMP

“…“…update a row update a row in EMP table…”in EMP table…”

EMPEMP

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ...

20

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ...

Page 150: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

The UPDATE StatementThe UPDATE StatementThe UPDATE StatementThe UPDATE Statement

Modify existing rows with the Modify existing rows with the UPDATE statement.UPDATE statement.

Update more than one row at a Update more than one row at a time, if required.time, if required.

Modify existing rows with the Modify existing rows with the UPDATE statement.UPDATE statement.

Update more than one row at a Update more than one row at a time, if required.time, if required.

UPDATE tableSET column = value [, column = value, ...][WHERE condition];

UPDATE tableSET column = value [, column = value, ...][WHERE condition];

Page 151: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Updating Rows in a Updating Rows in a TableTable

Updating Rows in a Updating Rows in a TableTable Specific row or rows are modified Specific row or rows are modified

when you specify the WHERE when you specify the WHERE clause.clause.

All rows in the table are modified if All rows in the table are modified if you omit the WHERE clause.you omit the WHERE clause.

Specific row or rows are modified Specific row or rows are modified when you specify the WHERE when you specify the WHERE clause.clause.

All rows in the table are modified if All rows in the table are modified if you omit the WHERE clause.you omit the WHERE clause.

SQL> UPDATE emp 2 SET deptno = 20 3 WHERE empno = 7782;1 row updated.1 row updated.

SQL> UPDATE employee 2 SET deptno = 20;14 rows updated.14 rows updated.

SQL> UPDATE employee 2 SET deptno = 20;14 rows updated.14 rows updated.

Page 152: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Updating with Updating with Multiple-Column Multiple-Column

SubquerySubquery

Updating with Updating with Multiple-Column Multiple-Column

SubquerySubquery

SQL> UPDATE emp 2 SET (job, deptno) = 3 (SELECT job, deptno 4 FROM emp 5 WHERE empno = 7499) 6 WHERE empno = 7698;1 row updated.1 row updated.

Update employee 7698’s job and Update employee 7698’s job and department to match that of department to match that of employee 7499.employee 7499.

Update employee 7698’s job and Update employee 7698’s job and department to match that of department to match that of employee 7499.employee 7499.

Page 153: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Updating Rows Based Updating Rows Based on Another Tableon Another Table

Updating Rows Based Updating Rows Based on Another Tableon Another Table

Use subqueries in UPDATE Use subqueries in UPDATE statements to update rows in a table statements to update rows in a table based on values from another table.based on values from another table.

Use subqueries in UPDATE Use subqueries in UPDATE statements to update rows in a table statements to update rows in a table based on values from another table.based on values from another table.SQL> UPDATE employee 2 SET deptno = (SELECT deptno 3 FROM emp 4 WHERE empno = 7788) 5 WHERE job = (SELECT job 6 FROM emp 7 WHERE empno = 7788);2 rows updated.2 rows updated.

SQL> UPDATE employee 2 SET deptno = (SELECT deptno 3 FROM emp 4 WHERE empno = 7788) 5 WHERE job = (SELECT job 6 FROM emp 7 WHERE empno = 7788);2 rows updated.2 rows updated.

Page 154: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

UPDATE emp *ERROR at line 1:ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found

UPDATE emp *ERROR at line 1:ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found

SQL> UPDATE emp 2 SET deptno = 55 3 WHERE deptno = 10;

SQL> UPDATE emp 2 SET deptno = 55 3 WHERE deptno = 10;

Updating Rows: Updating Rows: Integrity Constraint Integrity Constraint

ErrorError

Updating Rows: Updating Rows: Integrity Constraint Integrity Constraint

ErrorError

Department n

umber 55 does

Department n

umber 55 does

not exis

t

not exis

t

Department n

umber 55 does

Department n

umber 55 does

not exis

t

not exis

t

Page 155: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

“…“…delete a row delete a row from DEPT table…”from DEPT table…”

Removing a Row from a Removing a Row from a Table Table

Removing a Row from a Removing a Row from a Table Table DEPT DEPT

DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 50 DEVELOPMENT DETROIT 60 MIS ...

DEPT DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 60 MIS ...

Page 156: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

The DELETE StatementThe DELETE StatementThe DELETE StatementThe DELETE Statement

You can remove existing rows from a You can remove existing rows from a table by using the DELETE table by using the DELETE statement.statement.

You can remove existing rows from a You can remove existing rows from a table by using the DELETE table by using the DELETE statement.statement.DELETE [FROM] table[WHERE condition];

DELETE [FROM] table[WHERE condition];

Page 157: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Specific rows are deleted when you Specific rows are deleted when you specify the WHERE clause.specify the WHERE clause.

All rows in the table are deleted if All rows in the table are deleted if you omit the WHERE clause.you omit the WHERE clause.

Specific rows are deleted when you Specific rows are deleted when you specify the WHERE clause.specify the WHERE clause.

All rows in the table are deleted if All rows in the table are deleted if you omit the WHERE clause.you omit the WHERE clause.

Deleting Rows from a Deleting Rows from a TableTable

Deleting Rows from a Deleting Rows from a TableTable

SQL> DELETE FROM department 2 WHERE dname = 'DEVELOPMENT'; 1 row deleted.1 row deleted.

SQL> DELETE FROM department 2 WHERE dname = 'DEVELOPMENT'; 1 row deleted.1 row deleted.

SQL> DELETE FROM department;4 rows deleted.4 rows deleted.

SQL> DELETE FROM department;4 rows deleted.4 rows deleted.

Page 158: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Deleting Rows Based Deleting Rows Based on Another Tableon Another Table

Deleting Rows Based Deleting Rows Based on Another Tableon Another Table

Use subqueries in DELETE Use subqueries in DELETE statements to remove rows from a statements to remove rows from a table based on values from another table based on values from another table.table.

Use subqueries in DELETE Use subqueries in DELETE statements to remove rows from a statements to remove rows from a table based on values from another table based on values from another table.table.SQL> DELETE FROM employee 2 WHERE deptno = 3 (SELECT deptno 4 FROM dept 5 WHERE dname ='SALES');6 rows deleted.6 rows deleted.

Page 159: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Deleting Rows: Deleting Rows: Integrity Constraint Integrity Constraint

ErrorError

Deleting Rows: Deleting Rows: Integrity Constraint Integrity Constraint

ErrorErrorSQL> DELETE FROM dept 2 WHERE deptno = 10;

SQL> DELETE FROM dept 2 WHERE deptno = 10;

DELETE FROM dept *ERROR at line 1:ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found

DELETE FROM dept *ERROR at line 1:ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found

You cannot delete a row

You cannot delete a row

that contains a primary

that contains a primary

key key

that is used as a foreign

that is used as a foreign

key key

in another table.

in another table.

You cannot delete a row

You cannot delete a row

that contains a primary

that contains a primary

key key

that is used as a foreign

that is used as a foreign

key key

in another table.

in another table.

Page 160: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Database TransactionsDatabase TransactionsDatabase TransactionsDatabase Transactions

Consist of one of the following Consist of one of the following statements:statements: DML statements that make up one DML statements that make up one

consistent change to the dataconsistent change to the data One DDL statementOne DDL statement One DCL statementOne DCL statement

Consist of one of the following Consist of one of the following statements:statements: DML statements that make up one DML statements that make up one

consistent change to the dataconsistent change to the data One DDL statementOne DDL statement One DCL statementOne DCL statement

Page 161: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Database TransactionsDatabase TransactionsDatabase TransactionsDatabase Transactions

Begin when the first executable Begin when the first executable SQL statement is executedSQL statement is executed

End with one of the following End with one of the following events:events: COMMIT or ROLLBACK is issuedCOMMIT or ROLLBACK is issued DDL or DCL statement executes DDL or DCL statement executes

(automatic commit)(automatic commit) User exitsUser exits System crashesSystem crashes

Begin when the first executable Begin when the first executable SQL statement is executedSQL statement is executed

End with one of the following End with one of the following events:events: COMMIT or ROLLBACK is issuedCOMMIT or ROLLBACK is issued DDL or DCL statement executes DDL or DCL statement executes

(automatic commit)(automatic commit) User exitsUser exits System crashesSystem crashes

Page 162: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Advantages of COMMIT Advantages of COMMIT and ROLLBACK and ROLLBACK

StatementsStatements

Advantages of COMMIT Advantages of COMMIT and ROLLBACK and ROLLBACK

StatementsStatements Ensure data consistencyEnsure data consistency Preview data changes before Preview data changes before

making changes permanentmaking changes permanent Group logically related operationsGroup logically related operations

Ensure data consistencyEnsure data consistency Preview data changes before Preview data changes before

making changes permanentmaking changes permanent Group logically related operationsGroup logically related operations

Page 163: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

DELETEDELETE

Controlling TransactionsControlling TransactionsControlling TransactionsControlling Transactions TransactiTransacti

onon

TransactiTransactionon

Savepoint ASavepoint A

ROLLBACK to Savepoint BROLLBACK to Savepoint B

DELETEDELETE

Savepoint BSavepoint BCOMMITCOMMIT

INSERTINSERTUPDATEUPDATE

ROLLBACK to Savepoint AROLLBACK to Savepoint A

INSERTINSERTUPDATEUPDATEINSERTINSERT

ROLLBACKROLLBACK

INSERTINSERT

Page 164: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

An automatic commit occurs under An automatic commit occurs under the following circumstances:the following circumstances: DDL statement is issuedDDL statement is issued DCL statement is issuedDCL statement is issued Normal exit from SQL*Plus, without Normal exit from SQL*Plus, without

explicitly issuing COMMIT or explicitly issuing COMMIT or ROLLBACKROLLBACK

An automatic rollback occurs under An automatic rollback occurs under an abnormal termination of an abnormal termination of SQL*Plus or a system failure.SQL*Plus or a system failure.

An automatic commit occurs under An automatic commit occurs under the following circumstances:the following circumstances: DDL statement is issuedDDL statement is issued DCL statement is issuedDCL statement is issued Normal exit from SQL*Plus, without Normal exit from SQL*Plus, without

explicitly issuing COMMIT or explicitly issuing COMMIT or ROLLBACKROLLBACK

An automatic rollback occurs under An automatic rollback occurs under an abnormal termination of an abnormal termination of SQL*Plus or a system failure.SQL*Plus or a system failure.

Implicit Transaction Implicit Transaction ProcessingProcessing

Implicit Transaction Implicit Transaction ProcessingProcessing

Page 165: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

State of the Data Before State of the Data Before COMMIT or ROLLBACKCOMMIT or ROLLBACK

State of the Data Before State of the Data Before COMMIT or ROLLBACKCOMMIT or ROLLBACK

The previous state of the data can be The previous state of the data can be recovered.recovered.

The current user can review the results The current user can review the results of the DML operations by using the of the DML operations by using the SELECT statement.SELECT statement.

Other users Other users cannotcannot view the results of view the results of the DML statements by the current the DML statements by the current user.user.

The affected rows are The affected rows are lockedlocked; other ; other users cannot change the data within the users cannot change the data within the affected rows.affected rows.

The previous state of the data can be The previous state of the data can be recovered.recovered.

The current user can review the results The current user can review the results of the DML operations by using the of the DML operations by using the SELECT statement.SELECT statement.

Other users Other users cannotcannot view the results of view the results of the DML statements by the current the DML statements by the current user.user.

The affected rows are The affected rows are lockedlocked; other ; other users cannot change the data within the users cannot change the data within the affected rows.affected rows.

Page 166: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

State of the Data After State of the Data After COMMITCOMMIT

State of the Data After State of the Data After COMMITCOMMIT

Data changes are made permanent in Data changes are made permanent in the database.the database.

The previous state of the data is The previous state of the data is permanently lost.permanently lost.

All users can view the results.All users can view the results. Locks on the affected rows are Locks on the affected rows are

released; those rows are available for released; those rows are available for other users to manipulate.other users to manipulate.

All savepoints are erased.All savepoints are erased.

Data changes are made permanent in Data changes are made permanent in the database.the database.

The previous state of the data is The previous state of the data is permanently lost.permanently lost.

All users can view the results.All users can view the results. Locks on the affected rows are Locks on the affected rows are

released; those rows are available for released; those rows are available for other users to manipulate.other users to manipulate.

All savepoints are erased.All savepoints are erased.

Page 167: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Committing DataCommitting DataCommitting DataCommitting Data

SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782;1 row updated.1 row updated.

SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782;1 row updated.1 row updated.

Make the changes.Make the changes. Make the changes.Make the changes.

• Commit the changes.• Commit the changes.SQL> COMMIT;Commit complete.Commit complete.

Page 168: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

State of the Data After State of the Data After ROLLBACKROLLBACK

State of the Data After State of the Data After ROLLBACKROLLBACK Discard all pending changes by Discard all pending changes by

using the ROLLBACK statement.using the ROLLBACK statement. Data changes are undone.Data changes are undone. Previous state of the data is Previous state of the data is

restored.restored. Locks on the affected rows are Locks on the affected rows are

released.released.

Discard all pending changes by Discard all pending changes by using the ROLLBACK statement.using the ROLLBACK statement. Data changes are undone.Data changes are undone. Previous state of the data is Previous state of the data is

restored.restored. Locks on the affected rows are Locks on the affected rows are

released.released.SQL> DELETE FROM employee;14 rows deleted.14 rows deleted.SQL> ROLLBACK;Rollback complete.Rollback complete.

Page 169: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Rolling Back Changes Rolling Back Changes to a Markerto a Marker

Rolling Back Changes Rolling Back Changes to a Markerto a Marker

Create a marker in a current Create a marker in a current transaction by using the SAVEPOINT transaction by using the SAVEPOINT statement.statement.

Roll back to that marker by using the Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.ROLLBACK TO SAVEPOINT statement.

Create a marker in a current Create a marker in a current transaction by using the SAVEPOINT transaction by using the SAVEPOINT statement.statement.

Roll back to that marker by using the Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.ROLLBACK TO SAVEPOINT statement.

SQL> UPDATE...SQL> SAVEPOINT update_done;Savepoint created.Savepoint created.SQL> INSERT...SQL> ROLLBACK TO update_done;Rollback complete.Rollback complete.

Page 170: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

Truncating TablesTruncating TablesTruncating TablesTruncating Tables

Removes all table data without Removes all table data without saving any rollback informationsaving any rollback information Advantage: fast way to delete table Advantage: fast way to delete table

datadata Disadvantage: can’t be undoneDisadvantage: can’t be undone

Syntax:Syntax:TRUNCATE TABLE TRUNCATE TABLE tablenametablename;;

Removes all table data without Removes all table data without saving any rollback informationsaving any rollback information Advantage: fast way to delete table Advantage: fast way to delete table

datadata Disadvantage: can’t be undoneDisadvantage: can’t be undone

Syntax:Syntax:TRUNCATE TABLE TRUNCATE TABLE tablenametablename;;

Page 171: Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Writing basic SQL statements Restricting and Sorting Data Restricting

SummarySummarySummarySummary

Description

Adds a new row to the table

Modifies existing rows in the table

Removes existing rows from the table

Makes all pending changes permanent

Allows a rollback to the savepoint marker

Discards all pending data changes

Statement

INSERT

UPDATE

DELETE

COMMIT

SAVEPOINT

ROLLBACK