SlideShare a Scribd company logo
SQL
Statements
Vikas K.Gupta
SQL as the standard language


Oracle SQL complies with industry-accepted standards.



Oracle Corporation ensures future compliance with evolving
standards by actively involving key personnel in SQL standards
committees.



Industry-accepted committees are the American National Standards
Institute (ANSI) and the International Standards Organization (ISO).



Both ANSI and ISO have accepted SQL as the standard language
for relational databases.
SQL Statements


DRL - Retrieves data from the database



DML - Enters new rows, changes existing
rows, and removes unwanted rows from
tables in the database, respectively.



DDL - Sets up, changes, and removes data
structures from tables.



TCL - Manages the changes made by DML
statements. Changes to the data can be
grouped together into logical transactions.



DCL - Gives or removes access rights to
both the Oracle database and the structures
within it.
SELECT Statements


To extract data from the database, you need to use SELECT statement.

Using a SELECT statement, you can do the following:


Projection:
choose the columns in a table that you want returned by your query. You can choose
as few or as many columns of the table as you require.



Selection:
choose the rows in a table that you want returned by a query. You can use various
criteria to restrict the rows that you see.



Joining:
Bring together data that is stored in different tables by creating a link between them.
Basic SELECT Statement



SELECT identifies what columns
FROM identifies which table
Null Value


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



A null is not the same as zero or a blank space. Zero is a number, and a
space is a character.



If a row lacks the data value for a particular column, that value is said to be
null, or to contain a null.



If any column value in an arithmetic expression is null, the result is null.



For example, if you attempt to perform division with zero, you get an error.
However, if you divide a number by null, the result is a null or unknown.
Column Alias


Renames a column heading



Specify the alias after the column using a space as a separator.
there can also be the optional AS keyword between the column
name and alias



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



By default, alias headings appear in uppercase. If the alias contains
spaces or special characters (such as # or $), or is case sensitive,
enclose the alias in double quotation marks (" ").
Concatenation Operator


Concatenates columns or character strings to other columns



Is represented by two vertical bars (||)



Creates a resultant column that is a character expression



You can link columns to other columns, arithmetic expressions, or
constant values to create a character expression by using the
concatenation operator (||).



Columns on either side of the operator are combined to make a
single output column.
Literal Character Strings


A literal is a character, a number, or a date that is included in the SELECT
list and that is not a column name or a column alias.



It is printed for each row returned.



Literal strings of free-format text can be included in the query result and are
treated the same as a column in the SELECT list.



Date and character literals must be enclosed within single quotation
marks (’ ’); number literals need not.
Eliminating Duplicate Rows


Eliminate duplicate rows by using the DISTINCT
keyword in the SELECT clause.
SQL Statements
Versus

iSQL*Plus Commands
Displaying Table Structure


Use the iSQL*Plus DESCRIBE command to display the
structure of a table.
Chapter - 2

Restricting and
Sorting Data
Where clause
Selection


Restrict the rows returned by using the WHERE clause.



A WHERE clause contains a condition that must be met, and it directly follows the
FROM clause.



If the condition is true, the row meeting the condition is returned.



The WHERE clause can compare values in columns, literal values, arithmetic
expressions, or functions.



It consists of three elements:



Column name
Comparison condition
Column name, constant, or list of values



Character Strings and Dates


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



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



The default date format is DD-MON-RR.
Comparison Conditions


Comparison conditions are
used in conditions that
compare one expression to
another value or expression.



They are used in the WHERE
clause.



An alias cannot be used in the
WHERE clause.



Note: The symbol != and ^=
can also represent the not
equal to condition.
Other Comparison Conditions


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



Use the IN membership condition to test for
values in a list.



Use the LIKE condition 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.



Test for nulls with the IS NULL operator.
Examples
Logical Conditions


A logical condition combines
the result of two component
conditions to produce a single
result based on them or inverts
the result of a single condition.



A row is returned only if the
overall result of the condition is
true.



You can use several
conditions in one WHERE
clause using the AND and OR
operators.
Examples :
Rules of Precedence
ORDER BY Clause


Sort rows with the ORDER BY clause
ASC: ascending order, default
DESC: descending order



The ORDER BY clause comes last in the SELECT statement.



The order of rows returned in a query result is undefined. The ORDER BY clause can
be used to sort the rows.



You can specify an expression, or an alias, or column position as the sort condition.



Null values are displayed last for ascending sequences and first for descending
sequences.
Chapter - 3

Single-Row
Functions
character, number, and date functions
SQL Functions


Perform calculations on data



Modify individual data items



Manipulate output for groups of rows



Format dates and numbers for display



Convert column data types



SQL functions sometimes take
arguments and always return a value.
Types of SQL Functions
Single-Row Functions


These functions operate on single rows only
and return one result per row.

There are different types of single-row functions.





Character
Number
Date
Conversion

Multiple-Row Functions


Functions can manipulate groups of rows to
give one result per group of rows. These
functions are known as group functions.
Character Functions
Case Manipulation Functions
LOWER, UPPER, and INITCAP are
the three case- conversion
functions.


LOWER Converts mixed case or
uppercase character strings to
lowercase



UPPER Converts mixed case or
lowercase character strings to
uppercase



INITCAP Converts the first letter
of each word to uppercase and
remaining letters to lowercase
Character-Manipulation Functions


CONCAT Joins values together (You are
limited to using two parameters with
CONCAT.)



SUBSTR Extracts a string of determined
length



LENGTH Shows the length of a string as a
numeric value



INSTR Finds numeric position of a named
character



LPAD Pads the character value rightjustified



RPAD: Pads the character value leftjustified



TRIM: Trims heading or trailing characters
(or both) from a character string
Number Functions


ROUND: Rounds value to specified decimal
ROUND(45.926, 2)



TRUNC: Truncates value to specified decimal
TRUNC(45.926, 2)



45.93

45.92

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

100
ROUND Function


The ROUND function rounds the column, expression, or value to n decimal
places.



If the second argument is 0 or is missing, the value is rounded to zero decimal
places.



If the second argument is 2, the value is rounded to two decimal places.



Conversely, if the second argument is -2, the value is rounded to two decimal places
to the left.

TRUNC Function


The TRUNC function works with arguments similar to those of the ROUND function.
DUAL Table


The DUAL table is owned by the user SYS and can be accessed by
all users.



It contains one column, DUMMY, and one row with the value X.



The DUAL table is useful when you want to return a value once
only, for instance, the value of a constant, pseudo column, or
expression that is not derived from a table with user data.



The DUAL table is generally used for SELECT clause syntax
completeness, because both SELECT and FROM clauses are
mandatory, and several calculations do not need to select from
actual tables.
Working with Dates


The default date display format is DD-MON-RR.



Valid Oracle dates are between January 1, 4712 B.C. and December 31, 9999 A.D.

SYSDATE is a function that returns:




Date
Time
SYSDATE is a date function that returns the current database server date and time.
You can use SYSDATE just as you would use any other column name.
Arithmetic with Dates


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



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



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



The example on the slide displays the last name and the number of weeks
employed for all employees in department 90.



It subtracts the date on which the employee was hired from the current date
(SYSDATE) and divides the result by 7 to calculate the number of weeks
that a worker has been employed.
Date Functions


MONTHS_BETWEEN(date1, date2) -The
result can be positive or negative. If date1 is
later than date2, the result is positive; if
date1 is earlier than date2, the result is
negative.



ADD_MONTHS (date, n) Adds n number of
calendar months to date.



NEXT_DAY (date, 'char') Finds the date of
the next specified day of the week ('char')
following date. The value of char may be a
number representing a day or a character
string.



LAST_DAY (date) Finds the date of the last
day of the month that contains date.



ROUND (date[,'fmt']) If the format model
fmt is omitted, date is rounded to the
nearest day.



TRUNC (date[, 'fmt']) If the format model
fmt is omitted, date is truncated to the
nearest day.
Using Date Functions
Using Date Functions
Conversion Functions
Implicit Data Type Conversion
Explicit Data Type Conversion
Using the TO_CHAR Function with Dates

The format model:


Must be enclosed in single quotation marks and is case sensitive



Can include any valid date format element



Has an fm element to remove padded blanks or suppress leading zeros



Is separated from the date value by a comma
Elements of the Date Format Model
SQL select statement and functions
SQL select statement and functions
SQL select statement and functions
SQL select statement and functions
Using the TO_CHAR Function with Numbers

These are some of the format elements you can use with the TO_CHAR function to
display a number value as a character:
SQL select statement and functions
SQL select statement and functions

More Related Content

SQL select statement and functions

  • 2. SQL as the standard language  Oracle SQL complies with industry-accepted standards.  Oracle Corporation ensures future compliance with evolving standards by actively involving key personnel in SQL standards committees.  Industry-accepted committees are the American National Standards Institute (ANSI) and the International Standards Organization (ISO).  Both ANSI and ISO have accepted SQL as the standard language for relational databases.
  • 3. SQL Statements  DRL - Retrieves data from the database  DML - Enters new rows, changes existing rows, and removes unwanted rows from tables in the database, respectively.  DDL - Sets up, changes, and removes data structures from tables.  TCL - Manages the changes made by DML statements. Changes to the data can be grouped together into logical transactions.  DCL - Gives or removes access rights to both the Oracle database and the structures within it.
  • 4. SELECT Statements  To extract data from the database, you need to use SELECT statement. Using a SELECT statement, you can do the following:  Projection: choose the columns in a table that you want returned by your query. You can choose as few or as many columns of the table as you require.  Selection: choose the rows in a table that you want returned by a query. You can use various criteria to restrict the rows that you see.  Joining: Bring together data that is stored in different tables by creating a link between them.
  • 5. Basic SELECT Statement   SELECT identifies what columns FROM identifies which table
  • 6. Null Value  A null is a value that is unavailable, unassigned, unknown, or inapplicable.  A null is not the same as zero or a blank space. Zero is a number, and a space is a character.  If a row lacks the data value for a particular column, that value is said to be null, or to contain a null.  If any column value in an arithmetic expression is null, the result is null.  For example, if you attempt to perform division with zero, you get an error. However, if you divide a number by null, the result is a null or unknown.
  • 7. Column Alias  Renames a column heading  Specify the alias after the column using a space as a separator. there can also be the optional AS keyword between the column name and alias  Requires double quotation marks if it contains spaces or special characters or is case sensitive  By default, alias headings appear in uppercase. If the alias contains spaces or special characters (such as # or $), or is case sensitive, enclose the alias in double quotation marks (" ").
  • 8. Concatenation Operator  Concatenates columns or character strings to other columns  Is represented by two vertical bars (||)  Creates a resultant column that is a character expression  You can link columns to other columns, arithmetic expressions, or constant values to create a character expression by using the concatenation operator (||).  Columns on either side of the operator are combined to make a single output column.
  • 9. Literal Character Strings  A literal is a character, a number, or a date that is included in the SELECT list and that is not a column name or a column alias.  It is printed for each row returned.  Literal strings of free-format text can be included in the query result and are treated the same as a column in the SELECT list.  Date and character literals must be enclosed within single quotation marks (’ ’); number literals need not.
  • 10. Eliminating Duplicate Rows  Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.
  • 12. Displaying Table Structure  Use the iSQL*Plus DESCRIBE command to display the structure of a table.
  • 13. Chapter - 2 Restricting and Sorting Data Where clause
  • 14. Selection  Restrict the rows returned by using the WHERE clause.  A WHERE clause contains a condition that must be met, and it directly follows the FROM clause.  If the condition is true, the row meeting the condition is returned.  The WHERE clause can compare values in columns, literal values, arithmetic expressions, or functions.  It consists of three elements:  Column name Comparison condition Column name, constant, or list of values  
  • 15. Character Strings and Dates  Character strings and date values are enclosed in single quotation marks.  Character values are case sensitive, and date values are format sensitive.  The default date format is DD-MON-RR.
  • 16. Comparison Conditions  Comparison conditions are used in conditions that compare one expression to another value or expression.  They are used in the WHERE clause.  An alias cannot be used in the WHERE clause.  Note: The symbol != and ^= can also represent the not equal to condition.
  • 17. Other Comparison Conditions  Use the BETWEEN condition to display rows based on a range of values.  Use the IN membership condition to test for values in a list.  Use the LIKE condition 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.  Test for nulls with the IS NULL operator.
  • 19. Logical Conditions  A logical condition combines the result of two component conditions to produce a single result based on them or inverts the result of a single condition.  A row is returned only if the overall result of the condition is true.  You can use several conditions in one WHERE clause using the AND and OR operators.
  • 22. ORDER BY Clause  Sort rows with the ORDER BY clause ASC: ascending order, default DESC: descending order  The ORDER BY clause comes last in the SELECT statement.  The order of rows returned in a query result is undefined. The ORDER BY clause can be used to sort the rows.  You can specify an expression, or an alias, or column position as the sort condition.  Null values are displayed last for ascending sequences and first for descending sequences.
  • 23. Chapter - 3 Single-Row Functions character, number, and date functions
  • 24. SQL Functions  Perform calculations on data  Modify individual data items  Manipulate output for groups of rows  Format dates and numbers for display  Convert column data types  SQL functions sometimes take arguments and always return a value.
  • 25. Types of SQL Functions Single-Row Functions  These functions operate on single rows only and return one result per row. There are different types of single-row functions.     Character Number Date Conversion Multiple-Row Functions  Functions can manipulate groups of rows to give one result per group of rows. These functions are known as group functions.
  • 27. Case Manipulation Functions LOWER, UPPER, and INITCAP are the three case- conversion functions.  LOWER Converts mixed case or uppercase character strings to lowercase  UPPER Converts mixed case or lowercase character strings to uppercase  INITCAP Converts the first letter of each word to uppercase and remaining letters to lowercase
  • 28. Character-Manipulation Functions  CONCAT Joins values together (You are limited to using two parameters with CONCAT.)  SUBSTR Extracts a string of determined length  LENGTH Shows the length of a string as a numeric value  INSTR Finds numeric position of a named character  LPAD Pads the character value rightjustified  RPAD: Pads the character value leftjustified  TRIM: Trims heading or trailing characters (or both) from a character string
  • 29. Number Functions  ROUND: Rounds value to specified decimal ROUND(45.926, 2)  TRUNC: Truncates value to specified decimal TRUNC(45.926, 2)  45.93 45.92 MOD: Returns remainder of division MOD(1600, 300) 100
  • 30. ROUND Function  The ROUND function rounds the column, expression, or value to n decimal places.  If the second argument is 0 or is missing, the value is rounded to zero decimal places.  If the second argument is 2, the value is rounded to two decimal places.  Conversely, if the second argument is -2, the value is rounded to two decimal places to the left. TRUNC Function  The TRUNC function works with arguments similar to those of the ROUND function.
  • 31. DUAL Table  The DUAL table is owned by the user SYS and can be accessed by all users.  It contains one column, DUMMY, and one row with the value X.  The DUAL table is useful when you want to return a value once only, for instance, the value of a constant, pseudo column, or expression that is not derived from a table with user data.  The DUAL table is generally used for SELECT clause syntax completeness, because both SELECT and FROM clauses are mandatory, and several calculations do not need to select from actual tables.
  • 32. Working with Dates  The default date display format is DD-MON-RR.  Valid Oracle dates are between January 1, 4712 B.C. and December 31, 9999 A.D. SYSDATE is a function that returns:    Date Time SYSDATE is a date function that returns the current database server date and time. You can use SYSDATE just as you would use any other column name.
  • 33. Arithmetic with Dates  Add or subtract a number to or from a date for a resultant date value.  Subtract two dates to find the number of days between those dates.  Add hours to a date by dividing the number of hours by 24.
  • 34. Calculate the number of weeks  The example on the slide displays the last name and the number of weeks employed for all employees in department 90.  It subtracts the date on which the employee was hired from the current date (SYSDATE) and divides the result by 7 to calculate the number of weeks that a worker has been employed.
  • 35. Date Functions  MONTHS_BETWEEN(date1, date2) -The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative.  ADD_MONTHS (date, n) Adds n number of calendar months to date.  NEXT_DAY (date, 'char') Finds the date of the next specified day of the week ('char') following date. The value of char may be a number representing a day or a character string.  LAST_DAY (date) Finds the date of the last day of the month that contains date.  ROUND (date[,'fmt']) If the format model fmt is omitted, date is rounded to the nearest day.  TRUNC (date[, 'fmt']) If the format model fmt is omitted, date is truncated to the nearest day.
  • 39. Implicit Data Type Conversion
  • 40. Explicit Data Type Conversion
  • 41. Using the TO_CHAR Function with Dates The format model:  Must be enclosed in single quotation marks and is case sensitive  Can include any valid date format element  Has an fm element to remove padded blanks or suppress leading zeros  Is separated from the date value by a comma
  • 42. Elements of the Date Format Model
  • 47. Using the TO_CHAR Function with Numbers These are some of the format elements you can use with the TO_CHAR function to display a number value as a character: