SlideShare uma empresa Scribd logo
1 de 149
DBMS - LAB
Neelam Rawat
SQL: Structured Query Language
 SQL is a language that provides an interface to database systems,
developed by IBM in the 1970
 SQL: Structured Query Language
 SQL is a standard language for accessing databases
 SQL is an ANSI (American National Standards Institute) standard
SQL: History & functions
 how to use SQL to access and manipulate data in: ORACLE
 SQL can execute queries against a database
 SQL can RETRIEVE DATA from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
SQL: Environment
SQL: Components
 DDL:
• It is a set of SQL commands used to create, modify and delete
database structures but not data.
• These commands are normally used by DBA, database designer or
application developer.
• Anybody using DDL command must have the CREATE object privilege
and a tablespace area in which to create objects
 DML:
• It is the area of SQL that allows changing data within the database
 DCL:
• Control access to data and to the database
 DQL:
• Allows getting data from the database and imposing ordering upon it.
It includes SELECT statement fired against tables.
SQL: SELECT statement – for retrieving data
SYNTAX
SELECT [DISTINCT | ALL] {* | select_list}
FROM {table_name [alias] | view_name} [{table_name [alias] | view_name}]...
[WHERE condition]
[GROUP BY condition_list]
[HAVING condition]
[ORDER BY {column_name | column_# [ ASC | DESC ] } ...
 The SELECT clause is mandatory and carries out the relational project operation.
 The FROM clause is also mandatory. It identifies one or more tables and/or views
from which to retrieve the column data displayed in a result table.
 The WHERE clause is optional and carries out the relational select operation. It
specifies which rows are to be selected.
 The GROUP BY clause is optional. It organizes data into groups by one or more
column names listed in the SELECT clause.
 The optional HAVING clause sets conditions regarding which groups to include in a
result table. The groups are specified by the GROUP BY clause.
 The ORDER BY clause is optional. It sorts query results by one or more columns in
ascending or descending order.
SQL: SELECT statement - example
 SELECT * FROM client_master;
 SELECT name, city FROM client_master;
SQL: SELECT statement – for retrieving data
Column Alias
An alias is used to rename a column or an expression during display. The
alias to a column or an expression appears as the heading in the output
of a query. It is useful in providing a meaningful heading to long
expressions in the SELECT query. By default, the alias appears in
uppercase in the query output without spaces
CLIENT_NAME incremented_balance
Ivan Bayross 30000
Mamta MAzumdar 0
Chhaya Bankar 10000
Ashwini Joshi 0
Hansel colaco 4000
Deepak Sharma 0
select name as client_name,
baldue*2
"incremented_balance"
from client_master;
SQL: SELECT statement – for retrieving data
SQL: Components
 DDL:
• It is a set of SQL commands used to create, modify and delete
database structures but not data.
• These commands are normally used by DBA, database designer or
application developer.
• Anybody using DDL command must have the CREATE object privilege
and a tablespace area in which to create objects
 DML:
• It is the area of SQL that allows changing data within the database
 DCL:
• Control access to data and to the database
 DQL:
• Allows getting data from the database and imposing ordering upon it.
It includes SELECT statement fired against tables.
SQL: Components
DDL DML DCL
CREATE
ALTER
DROP
RENAME
TRUNCATE
COMMENT
INSERT
UPDATE
DELETE
CALL
EXPLAIN PLAN
LOCK
COMMIT
ROLLBACK
SAVEPOINT
SET TRANSACTION
GRANT
REVOKE
SQL: Basic DDL commands
SQL CREATE TABLE Syntax:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
Example:
CREATE TABLE student
(
student_ID number(9),
name varchar(30),
age number(2),
gender char(1),
city varchar(15)
);
SQL DROP Syntax:
DROP TABLE table_name
Example:
DROP TABLE student
SQL RENAME Syntax:
RENAME table_name TO new_table name
Example:
RENAME student TO stu_info
SQL: Basic DDL commands - CREATE
SQL CREATE TABLE Syntax:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
Example:
create table client_master1
(client_no varchar2(6),
name varchar2(20),
address varchar2(20),
city varchar2(15),
pincode number(8),
state varchar2(15),
baldue number(10,2));
SYNTAX: Provides a description of the specified table or view
DESCRIBE { table-Name | view-Name } OR DESC { table-Name | view-Name }
Note: The EXPLAIN statement provides information specified table or view in MySQL
SQL: Basic DDL commands - CREATE
CREATING A TABLE FROM A TABLE
CREATE TABLE table_name (col1, col2, ….)
AS SELECT col1, col2 from table_name;
For example:
create table emp_accounts (ename, esalary, eage)
AS SELECT ename, salary, age from EMPLOYEE;
SQL: Basic DDL commands - CREATE
SQL: Basic DDL commands - CREATE
SQL: Basic DDL commands - CREATE
CONCATENATION OPERATORS
 Concatenation operator can be used to join two string values or
expressions in a SELECT query. The double vertical bar symbol, || is used
as string concatenation operator. It is applicable only for character and
string column values resulting into a new character expression
 select name || 'earns' || baldue from client_master;
 select name || '[' || client_no || ']' || 'earns' || baldue from
client_master;
SQL: Basic DQL commands - SELECT
SQL: Basic DQL commands - SELECT
SQL: Basic DQL commands - SELECT
SQL: Basic DDL commands - ALTER
SQL ALTER TABLE Syntax:
To add a column in a TABLE, use the
following syntax:
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use
the following syntax:
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a
table, use the following syntax:
ALTER TABLE table_name
MODIFY column_name datatype
Note: Oracle doesn’t support this syntax to
add a column name in the middle of a
table ALTER TABLE tablename ADD
columnname AFTER columnname;
SQL TRUNCATE Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE student;
SQL: Basic DDL commands - ALTER
SQL: Basic DDL commands - ALTER
SQL: Basic DDL commands - ALTER
SQL: DML commands
SQL INSERT Syntax:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
INSERT INTO table_name
(column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Example:
INSERT INTO student
VALUES (12, Smith, 20, M, Delhi);
INSERT INTO student (student_ID,
name, age, gender, city)
VALUES (12, Smith, 20, M, Delhi);
SQL DELETE Syntax:
DELETE FROM table_name
Example:
DELETE FROM student
Removal of specific rows:
DELETE FROM table_name WHERE conditions;
SQL: DML commands
SQL UPDATE Syntax:
The UPDATE statement is used to
update existing records in a TABLE
UPDATE table_name
SET
column1=value1,column2=value2,...
WHERE some_column=some_value;
Example:
UPDATE student
SET name=John, city=Mumbai
WHERE student_ID=12;
Be careful: when updating records,
what if we omitted WHERE clause, like
UPDATE student
SET name=John, city=Mumbai;
Check !!!
SQL: SELECT statement – with where clause
SYNTAX
SELECT * FROM table_name [WHERE condition]
Note: Oracle provides WHERE clause in an SQL query to apply a filter on
the rows
retrieved.
For example, SELECT * FROM EMPLOYEE WHERE name = ‘A’;
SQL: SELECT statement – with where clause
SQL
IDENTIFIERS
 No SQL keywords may be used
 Table name must be unique within the database
 For each column, the user must specify a name that is unique within the
table
DATA TYPES
 Each column must have a datatype specified
 Standards include various numeric types, fixed-length and varying-length
character strings, bit strings, and user-defined types
 Available datatypes vary from DBMS to DBMS
SQL: Data types (ORACLE 9i)
• String types
– CHAR(n) – fixed-length character data, n characters long Maximum
length = 2000 bytes
– VARCHAR2(n) – variable length character data, maximum 4000 bytes
– LONG – variable-length character data, up to 4GB. Maximum 1 per
table
• Numeric types
– NUMBER(p,q) – general purpose numeric data type
– INTEGER(p) – signed integer, p digits wide
– FLOAT(p) – floating point in scientific notation with p binary digits
precision
• Date/time type
– DATE – fixed-length date/time in dd-mm-yy form
Character Data Types
 VARCHAR2
• Variable-length character data (up to 4000 characters)
• Syntax: columnname VARCHAR2(maximum_size)
• If user enters data value less than maximum_size, DBMS only stores
actual character values
 CHAR
• Fixed-length character data (default = 2000)
• Syntax: columnname CHAR(maximum_size)
• If user enters data value less than maximum_size, DBMS adds trailing
blank spaces to the end of entry
 Oracle stores CHAR and VARCHAR2 data using the ASCII coding
Number Data Types
 NUMBER
• Used for all numeric data
• Syntax
- columnname NUMBER [([precision,] [scale])]
 Example:
• s_balance NUMBER (5,2)
• s_gpa NUMBER (3,2)
# of digits both to left and
right of decimal point
# of digits on the
right side of
decimal point
Data Types- Comparison with other RDBMS
Computations on table data
 None of the techniques used till now allows display of data from a table
after some arithmetic has been done with it.
 For example, to display employee_name and employee’s salary from the
employee_master table along with the annual salary of the employee (i.e.,
salary * 12). The arithemtic (salary * 12) is an example of table data
arithmetic.
 SQL sentences includes:
1. Arithmetic operators
2. Logical operators
Oracle allows arithmetic operators to be used while viewing records from
a table or while performing data manipulation operations such as insert,
update and delete. These include:
1. Addition +
2. Subtraction -
3. Division /
4. Multiplication *
5. Exponentiation **
6. Enclosed operation ()
Computations on table data
For example, Retrieve the contents of the column product_no, description
and compute 5% of the values contained in the column sell_price and
105% of the values in the first sell price for each row from the table
product_master.
Note: Here, sell_price*0.05 and sell_price*1.05 are not columns in the
table product_master. However, the calculations are done on the
contents of the column sell_price of the table product_master. Also,
ORACLE engine will use column names of the product_master as column
headers when displaying column output on the VDU screen
Computations on table data
SELECT product_no, description, sell_price*0.05, sell_price*1.05
FROM product_master
Output:
Renaming columns used with expression lists: rename the default
columns names with alias, when required.
Syntax:
SELECT column_name result_column_name, column_name
result_column_name FROM tablename
For example,
Computations on table data
Product_no Description Sell_price*0.05 Sell_price*1.05
SELECT product_no, description, sell_price*0.05 “current”, sell_price*1.05
“total” FROM product_master
Logical operators
Logical operators that can be used in SQL sentences are:
1. AND operator
2. OR operator
3. NOT operator
AND operator:
 The AND operator allows creating an SQL statement based on two or
more conditions being met.
 It can be used in any valid SQL statements such as SELECT, INSERT,
UPDATE, or DELETE.
 Oracle engine will process all rows in a table and display the result only
when all the conditions specified using the AND operator are satisfied.
Logical operators
OR operator:
 The OR condition allows creating an SQL statement where records are
returned when any one of the conditions are met.
 It can be used in any valid SQL statements such as SELECT, INSERT,
UPDATE, or DELETE.
 Oracle engine will process all rows in a table and display the result only
when any of the conditions specified using the OR operator is satisfied.
NOT operator:
 Oracle engine will process all rows in a table and display only those
records that do not satisfy the conditions specified.
Range searching - BETWEEN
 In order to select data that is within a range of values, the BETWEEN
operator is used.
 The BETWEEN operator allows the selection of rows that contain values
within a specified lower and upper limit.
 The two values in between the range must be linked with the keyword
AND.
 The BETWEEN operator can be used with both character and numeric
data types. (Note: data types cannot be mixed)
 In order the select data that is not in the specified range, the NOT
BETWEEN operator is used.
Pattern matching – LIKE predicate
 LIKE predicate allows comparison of one string value with another string
value, which is not identical.
 Wildcard characters to be used in LIKE predicate:
1. % allows to match any string of any length
2. _ allows to match on a single character
 For example, list all the clients whose name begins with the letter ‘A’
OR, list the name of those client whose second character as ‘A’
SELECT name FROM client_master WHERE name LIKE ‘A%’
SELECT name FROM client_master WHERE name LIKE ‘_A%’
IN and NOT IN predicates
 As the arithmetic operator ‘=‘ compares a single value to another single
value. In case a value needs to be compared to a list of values then the IN
predicate is used.
 IN predicate helps reduce the need to use multiple OR conditions
 For example,
list the details of the clients named mamta, hansel and chhaya.
SELECT * FROM client_master WHERE name IN (‘mamta’, ‘hansel’, ‘chhaya’);
IN and NOT IN predicates
 The NOT IN predicate is the opposite of the IN predicate.
 It will select all the rows where values do not match the values in the list.
 For example,
list the details of the clients other than mamta, hansel and chhaya.
SELECT * FROM client_master WHERE name NOT IN (‘mamta’, ‘hansel’, ‘chhaya’);
Queries: Create the table described below:
Column Name Data Type Size
PRODUCTNO VARCHAR2 6
DESCRIPTION VARCHAR2 15
PROFITPERCENT NUMBER 4,2
UNITMEASURE VARCHAR2 10
QTYONHAND NUMBER 8
REORDERLVL NUMBER 8,2
SELLPRICE NUMBER 8,2
COSTPRICE NUMBER 8,2
PRODUCT_MASTER
Queries: Insert the following values:
PRODUCT_MASTER
PRODUCTNO DESCRIPTION PROFIT
PERCENT
UNIT
MEASURE
QTYON
HAND
REORDER
LVL
SELL
PRICE
COST
PRICE
P00001 T-Shirts 5 Piece 200 50 350 250
P0345 Shirts 6 Piece 150 50 500 350
P06734 Cotton Jeans 5 Piece 100 20 600 450
P07865 Jeans 5 Piece 100 20 750 500
P07868 Trousers 2 Piece 150 50 850 550
P07885 Pull Overs 2.5 Piece 80 30 700 450
P07965 Denim Shirts 4 Piece 100 40 350 250
P07975 Lycra Tops 5 Piece 70 30 300 175
P08865 Skirts 5 Piece 75 30 450 300
Queries: Write the SQL queries for the following:
1. Retrieve the contents of the column product_no, description and compute 5% of
the values contained in the column sell_price and rename it as “Increase” and
105% of the values contained in the field sell_price and rename it as “New Price”
for each row from the table product_master.
2. Retrieve the contents of the columns product no, description, profit percent, sell
price from the table product_master where the values contained in the field
profit_percent is between 10 and 20 both inclusive.
3. Retrieve Client information like client no, name, address, city, and pincode for all
clients where the field pin code has the value 400054 or 400057.
4. Retrieve specified client information for the clients who are not in ‘Bombay’ or
‘Delhi’.
5. Retrieve all the information about client whose name begin with letters ‘I’ from
client_master.
6. Retrieve all the information about client whose name begin with letters ‘I’ from
client_master.
7. Retrieve all the information of client whose name’s second letter is either ‘a’ or ‘h’.
8. Retrieve the information of the client whose last letter of name is ‘s’.
9. Retrieve the names of all clients whose state is in Maharashtra, Delhi.
Queries: Write the SQL queries for the following:
1. Retrieve the value of 100*25 from dual table.
2. Retrieve the system date from dual table.
3. Retrieve and display the employee name in upper and lower case from employee
table. Also display the name with initial capital form.
4. Retrieve all the information about employees whose salary is between 10000 to
30000.
5. Retrieve the maximum salary, total salary and average of each salary of the
employee.
6. Retrieve all the information of employees whose name’s first letter starts from ‘M’
7. Retrieve the round off number 15.91 from dual table.
8. Retrieve the square root of 25 from dual table.
9. Retrieve the number of employees working in.
10. Retreive the length of the names of employees
ORACLE DUAL table
 DUAL is a table automatically created by Oracle Database along with the data
dictionary. DUAL is in the schema of the user SYS but is accessible by the name
DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and
contains one row with a value X. Selecting from the DUAL table is useful for
computing a constant expression with the SELECT statement.
 Because DUAL has only one row, the constant is returned only once. Alternatively,
you can select a constant, pseudocolumn, or expression from any table, but the
value will be returned as many times as there are rows in the table
 DESC DUAL;
 SELECT * FROM DUAL;
NAME NULL? TYPE
Dummy Varchar2(1)
D
X
SYSDATE
SYSDATE is a pseudo column that contains the current date and time. It
requires no arguments when selected from the table dual and returns
the current date.
For Example:
SELECT sysdate FROM DUAL;
SELECT to_char(sysdate,'HH:MI:SS') “time” FROM DUAL;
SELECT to_char(sysdate,'MI') "minutes" FROM DUAL;
SELECT to_char(sysdate,'SS') "seconds" FROM DUAL;
SELECT to_char(sysdate,'AM') FROM DUAL; //For AM or PM
SELECT to_char(sysdate,'BC') FROM DUAL; //For AD or BC
SELECT to_char(sysdate,'CC') FROM DUAL; //Century
SELECT to_char(sysdate,'DL') FROM DUAL; //Date in long format
Functions
SQL Functions
Functions are a very powerful feature of SQL and can be used to do the
following:
• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column datatypes
Note: SQL functions may accept arguments and always return a value.
Functions
Oracle Built in Functions: There are two types of functions in Oracle.
 Single Row Functions: Single row or Scalar functions return a
value for every row that is processed in a query.
 Group Functions: These functions group the rows of data based
on the values returned by the query. This is discussed in SQL
GROUP Functions. The group functions are used to calculate
aggregate values like total or average, which return just one total
or one average value after processing a group of rows.
Functions
There are four types of single row functions. They are:
1. Numeric Functions: These are functions that accept numeric
input and return numeric values.
2. Character or Text Functions: These are functions that accept
character input and can return both character and number
values.
3. Date Functions: These are functions that take values that are of
datatype DATE as input and return values of datatype DATE,
except for the MONTHS_BETWEEN function, which returns a
number.
4. Conversion Functions: These are functions that help us to
convert a value in one form to another form. For Example: a null
value into an actual value, or a value from one datatype to
another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE
etc.
Note: You can combine more than one function together in an
expression. This is known as nesting of functions.
Functions
Functions
SINGLE-ROW FUNCTIONS: CHARACTER FUNCTIONS
Single-row character functions accept character data as input and can
return both character and number values.
Character functions can be divided into the following:
 Case manipulation functions
 Character manipulation functions
CASE MANIPULATION FUNCTIONS:
 LOWER
 UPPER
 INITCAP
Functions
Functions
CASE MANIPULATION FUNCTIONS
LOWER, UPPER, and INITCAP are the three case conversion functions.
 LOWER: Converts mixed case or uppercase character string to
lowercase
 UPPER: Converts mixed case or lowercase character string to
uppercase
 INITCAP: Converts first letter of each word to uppercase and
remaining letters to lowercase
Functions
CHARACTER MANIPULATION FUNCTIONS
 CONCAT
 SUBSTR
 LENGTH
 INSTR
 LTRIM
 RTRIM
 LPAD
 RPAD
 REPLACE
Functions
CONCAT: The Oracle CONCAT function allows you to join (concatenate)
two strings together.
SYNTAX: CONCAT( string1, string2 )
Where, string_1 and string_2 are the two strings to be concatenated.
For Example: SELECT CONCAT('Let''s', ' learn Oracle') FROM dual;
OR,
SELECT 'Let''s' || ' learn Oracle' FROM dual;
In Oracle, the CONCAT function will only allow you to concatenate two
values together. If you want to concatenate more values than two, you
can nest multiple CONCAT function calls. The || operator allows you to
concatenate 2 or more strings together:
For Example: SELECT CONCAT(CONCAT('A', 'B'),'C') FROM dual;
OR,
SELECT 'A' || 'B' || 'C' FROM dual;
Functions
SUBSTR: The Oracle SUBSTR (SUBSTRING) function lets you extract a
portion of a string (a 'substring') from a string of characters.
SYNTAX: SUBSTR( source_string, start_position [, length ] )
 The source_string is the string that the substring will be taken from.
 The starting_position is the position in the source_string where you
want to start extracting characters. The first position in
the source_string is always '1', NOT '0', as in many other languages.
• If the starting_position is 0, then SUBSTR treats start_position as
1 (ie: the first position in the string).
• If the starting_position is a positive number, then SUBSTR starts
from the beginning of the string.
• If the starting_position is a negative number, then SUBSTR starts
from the end of the source_string and counts backwards.
Functions
 The length parameter is optional, and specifies the number of
characters to extract.
 If the length parameter is not used then SUBSTR will return
everything from the starting_position to the end of the string.
 If length is a negative number, then SUBSTR will return a NULL
value.
For Example:
SELECT SUBSTR (‘SECURE’, 3, 4) “substring” FROM DUAL;
SELECT SUBSTR('Dinner starts in one hour.', 8, 6) “substring” from DUAL;
SELECT SUBSTR('Dinner starts in one hour.', 0, 6) “substring” from DUAL;
SELECT SUBSTR('Dinner starts in one hour.', -4, 3) “substring” from DUAL;
SELECT SUBSTR('Dinner starts in one hour.', -9, 3) “substring” from DUAL;
SELECT SUBSTR('Dinner starts in one hour.', -9, 2) “substring” from DUAL;
Functions
LENGTH: The Oracle PL/SQL LENGTH function returns the length of the
specified string. It calculates the length using characters as defined by the
input character set. The return value the LENGTH function is always of
the datatype NUMBER.
SYNTAX: LENGTH( string )
string is the string of characters to find the length of. The input string can
be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB,
or NCLOB. If string is NULL or empty, then the LENGTH function returns
NULL.
For Example:
SELECT LENGTH('Oracle') FROM DUAL;
SELECT LENGTH(‘Good Morning’) FROM DUAL;
Functions
INSTR: The Oracle INSTR function searches inside a string for a substring.
The Oracle INSTR function works in a way similar to the SUBSTR function,
but INSTR returns an integer number indicating the position of the
substring within the string, rather than returning the substring itself.
SYNTAX: INSTR( string, substring [, start_position [, nth_appearance ] ] )
String: The string to search. string can be CHAR, VARCHAR2, NCHAR, NV
ARCHAR2, CLOB, or NCLOB.
Substring: The substring to search for in string. substring can be CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
start_position: Optional, The position in string where the search will start.
If omitted, it defaults to 1. The first position in the string is 1. If the
start_position is negative, the INSTR function counts
back start_position number of characters from the end of string and then
searches towards the beginning of string.
nth_appearance: Optional. The nth appearance of substring. If omitted, it
defaults to 1
Functions
For Example:
SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR','OR', 2, 2) "Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR','OR', 1, 2) "Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR','OR', -1, 2) "Instring" FROM DUAL;
SELECT INSTR('CORPORATE FLOOR','OR', -3,2) "Instring" FROM DUAL;
LTRIM: The Oracle LTRIM function removes all specified characters from
the left-hand side of a string. Space characters are the default.
Syntax: LTRIM( string1 [, trim_string] )
String1: The string to trim the characters from the left-hand side.
trim_string: Optional, the string that will be removed from the left-hand
side of string1. If this parameter is omitted, the LTRIM function will
remove all leading spaces from string1.
For Example: Select LTRIM('NISHA', 'N') from dual;
Functions
RTRIM: The Oracle RTRIM function removes all specified characters
from the right-hand side of a string
Syntax: RTRIM( string1 [, trim_string ] )
string1: The string to trim the characters from the right-hand side.
trim_string: Optional, the string that will be removed from the right-
hand side of string1. If this parameter is omitted, the RTRIM function
will remove all trailing spaces from string1.
For Example: SELECT RTRIM('SUNILA','A') from DUAL;
OR,
SELECT RTRIM('SUNILA') from DUAL;
SELECT RTRIM('123Tech123', '123') from DUAL;
Functions
LPAD: The Oracle LPAD function pads (adds characters to) the left-side
of a string with a given set of characters.
Syntax: LPAD(string, padding_length, [ padding_string ])
 String: string to prepend or pad characters onto. The padded
characters are added to the left-hand side of the string.
 padding_length: is the number of characters to return (not the
number of characters to add). If the padding_length is smaller
than the original string, the LPAD function will truncate the
string to the size of the padding_length
 Note: padding_string is optional. This is the character string
that will be padded to the left-hand side of string. If this
parameter is omitted, the LPAD function will default to padding
space characters to the left-side of the string.
For example: SELECT LPAD('page 1', 10, '*') “Left padded” from dual;
Functions
RPAD: In Oracle PL/SQL, RPAD is a built in function which pads the
input string with extra characters from the right side. It accepts three
arguments: the input string, the net length of the string including
padding, and the character to be used for padded.
Note: The third argument is optional. If it is not provided, Oracle will
use blank spaces as default padding character.
Syntax: RPAD (input_string, length, padding_character)
For Example: SELECT RPAD(‘Page 1',10,‘*’) FROM DUAL;
Functions
REPLACE: Replace function is used to replace a character with another
character in a string.
Syntax: REPLACE( string1, string_to_replace [, replacement_string]
 String1:The string to replace a sequence of characters with another set
of characters.
 string_to_replace: The string that will be searched for in string1.
 replacement_string: Optional, all occurrences of string_to_replace will
be replaced with replacement_string in string1. If
the replacement_string parameter is omitted, the REPLACE function
simply removes all occurrences of string_to_replace, and returns the
resulting string.
For Example:
SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL;
Functions
NUMBER FUNCTIONS
Number functions accept numeric
input and return numeric values:
 ROUND
 TRUNC
 MOD
 ABS
 POWER
 SQRT
 EXP
 FLOOR
 CEIL
Other functions:
 EXTRACT
 GREATEST
 LEAST
Number Functions: ROUND
In Oracle, ROUND is a built in overloaded function, which is used to round off
numeric and DATE type inputs to a specified precision
Syntax: ROUND( n, X)
In the syntax example above, "n" can be a numeric or date type input. "X" is the
rounding format. Date type inputs can be rounded by year, month, quarter, week,
hour and minute.
For Example:
SELECT ROUND(1.2536,2) FROM DUAL;
SELECT ROUND(1234,-2) FROM DUAL;
SELECT ROUND(TO_DATE('02-AUG-2011','DD-MM-YYYY'),'YYYY') FROM DUAL;
Note: TO_CHAR - Convert to character string & TO_DATE - Convert to date value
Number Functions: TRUNC
The TRUNC function truncates either a number or a datetime value. The syntax
of the TRUNC function is different depending on the whether it is being used for
a number or a date and time value.
TRUNC (datetime): The TRUNCATE (datetime) function returns date with the
time portion of the day truncated to the unit specified by the format model.
Syntax: TRUNC(datetime_exp, [fmt]);
The [fmt] parameter is the format that indicates how the date and time
number should be truncated. If you omit fmt, then date is truncated to the
nearest day.
TRUNC(number):When you specify a number as an argument, the TRUNCATE
function truncates a number to a specified number of decimal places.
Syntax: TRUNC (number, tvalue)
tvalue is an integer value that specifies the number of places to the right or
left of the decimal point to which the number should be truncated. When
the tvalue parameter is positive, digits to the right of the decimal point are
truncated. When tvalue is negative the digits to the left of the decimal point
are truncated. When the tvalueparameter is omitted, number is truncated
to 0 decimal places.
Number Functions: TRUNC
TRUNC (datetime): For Example
SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR') FROM DUAL;
SELECT TRUNC(TO_DATE('22-AUG-03','DD-MON-YY'), 'MONTH') FROM DUAL;
SELECT TRUNC(TO_DATE('22-AUG-03','DD-MON-YY'), 'DAY') FROM DUAL;
TRUNC(number): For Example
SELECT TRUNC(125.815) from DUAL;
SELECT TRUNC(125.815, 1) from DUAL;
SELECT TRUNC(125.815, 2) from DUAL;
SELECT TRUNC(125.815, 3) from DUAL;
SELECT TRUNC(125.815, -1) from DUAL;
SELECT TRUNC(125.815, -2) from DUAL;
SELECT TRUNC(125.815, -3) from DUAL;
Note:
When a date format is used
by TO_CHAR or TO_DATE they
return a formatted date/time.
When used by TRUNC they will
return the first day of the period.
When used by ROUND the values
will round up at mid year/mid
month (July 1 or 16th day)
Number Functions: MOD
The Oracle MOD (short for modulus) function returns the remainder when
one argument is divided by the second argument. It accepts two number
arguments and returns a single numeric value.
Note: The modulus is calculated according to the formula: x - y * floor(x/y).
Syntax: MOD(x,y)
 The remainder will be returned when 'x' is divided by 'y‘
 The mod function will return x if y is 0. If y = 0, it returns x.
For Example:
SELECT MOD(10,3) RES FROM DUAL;
SELECT MOD(3,10) RES FROM DUAL;
SELECT MOD(11,-4) "Modulus" FROM DUAL;
SELECT MOD(-11,4) "Modulus" FROM DUAL;
SELECT MOD(-11,-4) "Modulus" FROM DUAL;
Number Functions: ABS
In Oracle PL/SQL, the ABS function returns the absolute value of a
number, which will always be zero or a positive number.
Syntax: ABS( number )
 Number: The number to convert to an absolute value.
For Example:
SELECT ABS(-23.65) "Absolute" FROM DUAL;
SELECT ABS(0005) "Absolute" FROM DUAL;
SELECT ABS(20.537) FROM DUAL;
Number Functions: POWER
The Oracle PL/SQL, the POWER function is a built in function
which takes two numeric inputs and returns numeric result as first
argument raised to second argument.
Syntax: POWER(x,y)
Where, "x" is the base while "y" is the exponent.
For Example:
SELECT POWER(10,2) FROM DUAL;
SELECT POWER(3,2) "Raised" FROM DUAL;
SELECT POWER(-5, 3) "Raised" FROM DUAL;
SELECT POWER(6.2, 3) "Raised" FROM DUAL;
SELECT POWER(6.2, 3.5) "Raised" FROM DUAL;
Number Functions: SQRT
In Oracle PL/SQL, SQRT is a built in function which returns the square
root of a numeric input. It returns positive output if the input argument is
a number.
Note: For negative input arguments, it raises ORA-01428 exception.
Syntax: SQRT(x)
 x: A positive number that is used in the square root calculation.
For Example:
SELECT SQRT(9) "square root" FROM DUAL;
SELECT SQRT(37) "square root" FROM DUAL;
SELECT SQRT(-20) "square root" FROM DUAL;
Number Functions: EXP
The Oracle EXP function returns e raised to the nth power, where e = 2.71828
Syntax: exp( number )
 Number: The power to raise e.
For Example:
SELECT EXP(2) FROM dual;
SELECT EXP(3.1) FROM dual;
SELECT EXP(-3) FROM dual;
Number Functions: FLOOR
The FLOOR function rounds a number down to the next higher integer. If
number is already rounded, it simply returns the number unchanged.
Syntax: FLOOR(number)
Number: The value used to determine the largest integer value that is
equal to or less than a number.
For Example:
SELECT FLOOR(15.7) "Floor" FROM DUAL;
SELECT FLOOR(-5.9) "Floor" FROM DUAL;
SELECT FLOOR(-27.8) "Floor" FROM DUAL;
Number Functions: CEIL
The Oracle CEIL() function rounds a number up to the next higher
integer. If number is already rounded, it simply returns the number
unchanged.
Syntax: CEIL(number)
 Number: The value used to find the smallest integer value.
For Example:
SELECT CEIL(32.65) "Floor" FROM DUAL;
SELECT CEIL(32.1) "Floor" FROM DUAL;
SELECT CEIL(-32.65) "Floor" FROM DUAL;
SELECT CEIL(-32) "Floor" FROM DUAL;
Number Functions: EXTRACT
The Oracle/PLSQL EXTRACT function extracts a value from a date or
interval value.
Syntax:
EXTRACT ({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND }| {
TIMEZONE_HOUR | TIMEZONE_MINUTE }| { TIMEZONE_REGION |
TIMEZONE_ABBR } FROM { date_value | interval_value } )
For Example:
SELECT EXTRACT(YEAR FROM DATE '2010-01-12') FROM DUAL;
SELECT EXTRACT(DAY FROM DATE '2003-08-22') FROM DUAL;
SELECT EXTRACT(MONTH FROM SYSDATE-40) FROM DUAL;
Number Functions: GREATEST
The Oracle/PLSQL GREATEST function returns the greatest value in a list of
expressions
Syntax: GREATEST( expr1 [, expr2, ... expr_n]
 Expr1: The first expression to be evaluated whether it is the greatest.
 Expr2,…., expr_n: Optional, additional expressions that are to be
evaluated.
 Note: If the datatypes of the expressions are different, all expressions
will be converted to whatever datatype expr1 is.
For Example:
SELECT GREATEST(7, 19, 85, 2) FROM DUAL;
SELECT GREATEST('blue', 'blew', 'blow') FROM DUAL;
SELECT GREATEST('dallas', 'dulles', 'dullus') FROM DUAL;
SELECT GREATEST('Dallas', 19, 'Dalie', 2) FROM DUAL;
Note: Do not confuse GREATEST with MAX. GREATEST returns the greatest of
the list of expressions, while MAXreturns the maximum value of expressions
and is normally used as an aggregate or analytic function.
Number Functions: LEAST
The Oracle/PLSQL LEAST function returns the smallest value in a list of
expressions.
Syntax: LEAST( expr1 [, expr2, ... expr_n] )
 Expr1: The first expression to evaluate whether it is the smallest.
 expr2, ... expr_n: Optional, additional expressions that are to be
evaluated.
For Example:
SELECT LEAST(2, 5, 12, 3) FROM DUAL;
SELECT LEAST('apples', 'oranges', 'bananas') FROM DUAL;
SELECT LEAST('apples', 'applis', 'applas', null) FROM DUAL;
Note: Do not confuse LEAST with MAX. LEAST returns the least of the list
of expressions, while MAX returns the maximum value of expressions and
is normally used as an aggregate or analytic function.
Functions: Group Functions
1. SUM( [ALL | DISTINCT] expression )
2. AVG( [ALL | DISTINCT] expression )
3. COUNT( [ALL | DISTINCT] expression )
4. COUNT(*)
5. MAX(expression)
6. MIN(expression)
Functions
Aggregate and Scalar Functions
Another way of categorizing functions is in terms of whether they operate on
values from just one row at a time, on values from a collection, or on a set of
rows. Aggregate functions operate against a collection of values and return a
single summarizing value. Scalar functions return a single value based on scalar
input arguments. Some scalar functions, such as CURRENT_TIME, do not
require any arguments
Aggregate functions return a single value based upon a set of other values. If
used among other expressions in the item list of a SELECT statement, the
SELECT must have a GROUP BY or HAVING clause. No GROUP BY or HAVING
clause is required if the aggregate function is the only value retrieved by the
SELECT statement.
The general syntax of an aggregate function is:
aggregate_function_name ( [ALL | DISTINCT] expression)
The aggregate function name may be AVG, COUNT, MAX, MIN, or SUM.
Functions
AVG and SUM
The AVG function computes the average of values in a column or an expression.
SUM computes the sum. Both functions work with numeric values and ignore
NULL values. Use the DISTINCT keyword to compute the average or sum of all
distinct values of a column or expression.
SQL Standard Syntax:
AVG ([ALL | DISTINCT] expression)
SUM ([ALL | DISTINCT] expression)
Functions
AVG and SUM
The AVG function computes the average of values in a column or an expression.
SUM computes the sum. Both functions work with numeric values and ignore
NULL values. Use the DISTINCT keyword to compute the average or sum of all
distinct values of a column or expression.
SQL Standard Syntax:
AVG ([ALL | DISTINCT] expression)
SUM ([ALL | DISTINCT] expression)
Functions
COUNT
The COUNT function is used to compute the number of rows in an expression.
SQL Syntax:
COUNT(*)
COUNT( [ALL|DISTINCT] expression)
COUNT(*)
Counts all the rows in the target table whether or not they include NULLs.
COUNT( [ALL|DISTINCT] expression)
Computes the number of rows with non-NULL values in a specific column or
expression. When the keyword DISTINCT is used, duplicate values will be
ignored and a count of the distinct values is returned. ALL returns the number
of non-NULL values in the expression and is implicit when DISTINCT is not used
Functions
COUNT Example:
This query counts all rows in a table:
SELECT COUNT(*) FROM publishers;
The following query finds the number of different countries where publishers
are located:
SELECT COUNT(DISTINCT country) "Count of Countries"
FROM publishers;
Functions
MIN and MAX
MIN (expression) and MAX (expression) find the minimum and maximum value
of expression (string, datetime, or numeric) in a set of rows. DISTINCT or ALL
may be used with these functions, but do not affect the result.
SQL Syntax:
MIN( [ALL | DISTINCT]expression)
MAX( [ALL | DISTINCT]expression)
Examples:
The following query finds the best and worst sales for any title on record:
SELECT MIN(ytd_sales), MAX(ytd_sales)
FROM titles;
 TO_NUMBER
 TO_CHAR – Date/ Number Conversion Function
 TO_DATE – Date conversion Function
CONVERSION FUNCTION
The TO_NUMBER function converts a character value to a numeric datatype.
If the string being converted contains nonnumeric characters, the function
returns an error.
Syntax: TO_NUMBER (string1, [format], [nls_parameter])
 String1: The string that will be converted to a number.
 Format: Optional, this is the format that will be used to convert string1 to a
number.
 nls_parameter: Optional, this is the nls language used to convert string1 to
a number.
For Example:
select TO_NUMBER('9999.99') from dual;
select TO_NUMBER('1210.73', '9999.99') from dual;
CONVERSION FUNCTION: TO_NUMBER
TO_CHAR is a conversion function in Oracle to convert
1. number to character
2. date to character
TO_CHAR (number conversion): Converts a value of a number datatype to a character
datatype, using the optional format string. TO_CHAR() accepts a number(n) and a
numeric format (fmt) in which the number has to appear. If (fmt) is omitted, n is
converted to a char value exactly long enough to hold all significant digit.
Syntax: TO_CHAR (n [,fmt])
Example: SELECT TO_CHAR (17145, ‘$09021’) “char” FROM dual;
TO_CHAR (date conversion): Converts a value of a DATE datatype to CHAR datatype.
TO_CHAR() accepts a date, as well as the format (fmt) in which the date has to appear.
Fmt must be a date format. If fmt is omitted, the DATE is converted to a character
value using the default date format, i.e., DD-MON-YY.
Syntax: TO_CHAR (date [,fmt])
Example: SELECT TO_CHAR(dely_date, ‘month dd, yyyy’) new_date FROM
SALES_ORDER WHERE order_no =‘O00001’;
CONVERSION FUNCTION: TO_CHAR
For Example: TO_CHAR number function
select to_char(‘012’) as str from dual;
select to_char('012','$9999') as str from dual;
select to_char('012','$000009999') as str from dual;
select to_char('012','$0009999.99') as str from dual;
select to_char('012.48','$9999.999') as str from dual;
For Example: TO_CHAR (DATE FUNCTION)
select sysdate,to_char(sysdate,’mm/dd/yyyy’) from dual;
select sysdate,to_char(sysdate,’YYTH MONTH YEAR’) as fmt_date from dual;
select to_char(sysdate,’mm/dd/yyyy’) as today from dual;
select to_char(sysdate,’mm/dd/yyyy hh:mi:ss AM’) as today from dual;
select to_char(sysdate,’YEAR’) as today from dual;
select to_char(sysdate,’mon ddth yyyy’) as today from dual;
CONVERSION FUNCTION: TO_CHAR
TO_CHAR(,[fmt]) - format may be the following:
MM Numeric month (e.g., 07)
MON Abbreviated month name (e.g., JUL)
MONTH Full month name (e.g., JULY)
DD Day of month (e.g., 24)
DY Abbreviated name of day (e.g., FRI)
YYYY 4-digit year (e.g., 1998)
YY Last 2 digits of the year (e.g., 98)
RR
Like YY, but the two digits are ``rounded'' to a year in the range
1950 to 2049. Thus, 06 is considered 2006 instead of 1906
AM (or PM) Meridian indicator
HH Hour of day (1-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)
TO_DATE: The Oracle TO_DATE function will convert either a character
string or an expression into a date value.
Syntax: TO_DATE( string1 [, format_mask] [, nls_language] )
 String1: The string that will be converted to a date.
 format_mask: Optional, this is the format that will be used to
convert string1 to a date.
 nls_language: Optional, this is the nls language used to
convert string1 to a date.
For Example:
 select to_date('16-Feb-09', 'DD-Mon-YY') as str from dual;
 select to_date('021609', 'MMDDYY') as str from dual;
 select to_date('Feb/16/09', 'Mon/DD/YY HH:MI:SS') "change" from dual;
 select to_date('February.16.2009', 'Month.DD.YYYY HH:MI:SS') "change"
from dual;
CONVERSION FUNCTION: TO_DATE
Functions
SYSDATE
SYSDATE is a date function that returns the current date and time. You can use
SYSDATE just as you would use any other column name.
For example, you can display the current date by selecting SYSDATE from a
table. It is customary to select SYSDATE from a dummy table called DUAL.
Example Display the current date using the DUAL table:
SQL> SELECT SYSDATE FROM DUAL;
SELECT to_char (SYSDATE, 'MM-DD-YYYY HH:MI:SS') FROM dual;
Functions
Date Functions
Date functions operate on Oracle dates. All date functions return a value of DATE
datatype except MONTHS_BETWEEN, which returns a numeric value
.
•MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and
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. The non-integer part of the
result represents a portion of the month.
•ADD_MONTHS(date, n):Adds n number of calendar months to date. The value of n
must be an integer and can be negative.
•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']): Returns date rounded to the unit specified by the format model
fmt. If the format model fmt is omitted, date is rounded to the nearest day.
•TRUNC(date[,'fmt']): Returns date with the time portion of the day truncated to the
unit specified by the format model fmt. If the format model fmt is omitted, date is
truncated to the nearest day.
Functions
MONTHS_BETWEEN: For Example,
SELECT MONTHS_BETWEEN(SYSDATE,DOJ) FROM employee;
ADD_MONTHS: For Example,
SELECT SYSDATE, ADD_MONTHS(SYSDATE,1), ADD_MONTHS(SYSDATE,2),
ADD_MONTHS(SYSDATE,3), ADD_MONTHS(SYSDATE,4), ADD_MONTHS(SYSDATE,5),
ADD_MONTHS(SYSDATE,6)
FROM dual;
LAST_DAY: For Example,
SELECT SYSDATE, LAST_DAY(SYSDATE) EOM, LAST_DAY(SYSDATE)+1 FOM FROM dual;
NEXT_DAY: For Example,
SELECT SYSDATE, NEXT_DAY(SYSDATE,'MONDAY') "Next Mon",
NEXT_DAY(SYSDATE,'FRIDAY') "Next Fri", NEXT_DAY(LAST_DAY(SYSDATE)+1,'TUESDAY')
"First Tue“ FROM dual;
Functions
Arithmetic with Dates
Since the database stores dates as numbers, you can perform calculations
using arithmetic operators such as addition and subtraction. You can add and
subtract number constants as well as dates. You can perform the following
operations:
Grouping data from tables
GROUP BY clause: group the rows based on distinct values that exist for
specified columns. GROUP BY clause creates a data set, containing several sets
of records grouped together based on condition.
Syntax:
SELECT <columnname1>, <columnname2>, <columnnamen>,
AGGREGATE_FUNCTION (expression)
FROM <tablename>
WHERE <condition>
GROUP BY <columnname1>, <columnname2>, <columnnamen>;
Grouping data from tables
NAME
Banana
Orange
Orange
Apple
Banana
Apple
Apple
Apple
NAME
Apple
Banana
Orange
I want result as:
SELECT NAME FROM FRUIT
ORDER BY NAME
GROUP BY NAME
SELECT DISTINCT NAME FROM FRUIT
ORDER BY NAME;
Having clause
Having clause: used in conjunction with the GROUP BY clause. HAVING
imposes a condition on the GROUP BY clause, which further filters created by
the GROUP BY clause.
For example: Find out the customers having more than one account in the
bank.
SELECT cust_no, COUNT (acct_no) “no. of accounts held”
FROM acct_master
WHERE where acct_no LIKE ‘CA%’ OR acct_no LIKE ‘SB%’
GROUP BY cust_no HAVING COUNT(acct_no)>1;
Having clause
Having clause: used in conjunction with the GROUP BY clause. HAVING
imposes a condition on the GROUP BY clause, which further filters created by
the GROUP BY clause.
For example: Find out the customers having more than one account in the
bank.
SELECT cust_no, COUNT (acct_no) “no. of accounts held”
FROM acct_master
WHERE where acct_no LIKE ‘CA%’ OR acct_no LIKE ‘SB%’
GROUP BY cust_no HAVING COUNT(acct_no)>1;
Sub-queries
A sub-query is a form of an SQL statement that appears inside another SQL
statement. It is also termed as nested query. The statement containing a
Sub-query is called parent statement. The parent statement uses the rows
(i.e., the result set) returned by the sub-query.
For example: Find the product number and description of non-moving
products, i.e., products not being sold.
SELECT product_no, description FROM product_master
WHERE product_no NOT IN (SELECT product_no FROM sales_order_details;
List the names of clients who have placed orders worth Rs. 10000 or more.
SELECT name FROM client_master WHERE client_no IN ( SELECT client_no
FROM sales_order where (( ty_ordered*product_Rate) > 10000));
Correlated sub-queries
A sub-query becomes correlated when the subquery references a column
from a table in the parent query. A correlated subquery is evaluated once
for each row processed by the parent statement, which can be any of
SELECT, DELETE, UPDATE.
For example: Find out the products, which have been sold to Ivan Bayross.
SELECT sales_order_details.product_no, product_master.description
FROM sales_order_details, sales_order, product_master, client_master
WHERE product_master.product_no=sales_order_details.product_no AND
sales_order.order_no=sales_order_details.order_no AND
client_master.client_no=sales_order.client_no AND
client_master.name=‘Ivan Bayross’;
Data constraints
Oracle allows programmers to define constraints at:
1. Column level
2. Table level
1. If data constraints are defined along with the column definition when
creating or altering a table structure, they are column level constraints
2. If data constraints are defined after defining all the table columns when
creating or altering a table structure, it as table level constraint
Note: Both the CREATE TABLE and ALTER TABLE SQL verbs can be used to
write SQL sentences that attach constraints (i.e., business or system
rules) to a table column
Data constraints: types
1. I/O constraints
2. UNIQUE key constraint
3. NULL value concept
4. CHECK constraint
5. DEFAULT value concept
I/O constraints includes:
1. PRIMARY KEY constraint
2. FOREIGN KEY constraint
PRIMARY KEY
Primary key is one or more column(s) in a table used to uniquely identify
each row in a table. None of the fields that are part of primary key can
contain a null value. A table can have only one primary key
A primary key column in a table has following properties:
1. It defines the column, as mandatory column (i.e., the column cannot
be left blank), as NOT NULL attribute is active
2. The data held across the column must be UNIQUE.
PRIMARY KEY = UNIQUE + NOT NULL
PRIMARY KEY: features
1. Primary key is a column or a set of columns that uniquely identifies a row.
Its main purpose is the RECORD UNIQUENESS.
2. Primary key will not allow duplicate values
3. Primary key will also not allow null values
4. Primary key is not compulsory but it is recommended
5. Primary key helps to identify one record from another record and also
helps in relating tables with one another
6. Primary key cannot be LONG or LONG RAW data type
7. Only one primary key is allowed per table
8. Unique index is created automatically if there is a primary key
9. One table can combine upto 16 columns in a composite primary key
PRIMARY KEY
Primary key constraint at column
level
Primary key constraint at table level
<column_name> <datatype(size)>
PRIMARY KEY
PRIMARY KEY(<column_name>,
<column_name>)
For example,
CLIENT TABLE client_master(client_no
varchar2(6) PRIMARY KEY, name
varchar2(30), address varchar2(30), city
varchar2(15), state varchar2(15), baldue
number(10,2));
For example,
CREATE TABLE
sales_order_master(product_no
varchar2(6), order_no varchar2(6),
qtyordered number(8), qtydisp
number(8), PRIMARY KEY(order_no,
product_no));
FOREIGN KEY
 Foreign key represents relationships between tables. A foreign key is a
column (or a group of columns) whose values are derived from the
primary key or unique key of some other table.
 The table in which the foreign key is defined is called a foreign table or
detail table. The table that defines the primary or unique key and is
referenced by the foreign key is called the primary table or master table.
 The master table can be referenced in the foreign key definition by using
the REFERENCES adverb. If the name of the column is not specified, by
default, Oracle references the primary key in the master table.
FOREIGN KEY: features
1. Foreign key is a column(s) that reference a column(s) of a table and it can
be the same table.
2. Parent that is being referenced has to be unique or primary key.
3. Child may have duplicates and nulls but unless it is specified.
4. Foreign key constraint can be specified on child but not on parent.
5. Parent record can be delete provided no child record exist.
6. Master table cannot be updated if child record exist.
Note: Relationship ensures:
 Record cannot be inserted into a detail table if corresponding records in
the master table do not exist
 Record of master able cannot be deleted if corresponding record in detail
table actually exist.
FOREIGN KEY
foreign key constraint at column
level
Foreign key constraint at table level
<column_name> <datatype(size)>
REFERENCES
<tablename(column_name)>
FOREIGN KEY (<column_name>
<column_name>) REFERENCES
<tablename(column_name,
column_name)>
For example,
CLIENT TABLE sales_order(order_no
varchar2(6) PRIMARY KEY, order_date
date, client_no varchar2(6) REFERENCES
client_master));
For example,
CLIENT TABLE sales_order(order_no
varchar2(6) PRIMARY KEY, order_date
date, FOREIGN KEY(order_no)
REFERENCES client_master);
FOREIGN KEY
FOREIGN KEY constraint defined with ON DELETE CASCADE:
 A foreign key with cascade delete means that if a record in the parent
table is deleted, then the corresponding records in the child table
with automatically be deleted. This is called a cascade delete in
Oracle.
FOREIGN KEY constraint defined with ON DELETE SET NULL:
 A FOREIGN KEY with a SET NULL ON DELETE means that if a record in
the parent table is deleted then the corresponding records in the
child table will have the foreign key fields set to NULL. The records in
the child table will not be deleted.
 A FOREIGN KEY with a SET NULL ON DELETE can be defined in either a
CREATE TABLE statement or an ALTER TABLE statement.
FOREIGN KEY: example
CREATE TABLE product_master
(productno varchar2(6) not null, description varchar2(30) not null,
CONSTRAINT fk_order_no FOREIGN KEY (order_no REFERENCES
order_master(orderno) ON DELETE CASCADE);
CREATE TABLE product_master
(productno varchar2(6) not null, description varchar2(30) not null,
CONSTRAINT fk_order_no FOREIGN KEY (order_no REFERENCES
order_master(orderno) ON DELETE SET NULL);
CONSTRAINTS: user-defined
Adding user-defined names to CONSTRAINTS:
For example,
Explanation: User named constraint simplifies the task of dropping
constraints. A constraint can be given a user-defined name by preceding
the constraint definitions with the reserved word CONSTRAINT and a
user-defined name
CONSTRAINT <constraint_name> <constraint_definition>
CREATE TABLE client_master ( clientno varchar2(6) CONSTRAINT c_key PRIMARY KEY,
cname varchar2(20) NOT NULL);
UNIQUE CONCEPT
UNIQUE column constraint permits multiple entries of NULL into the
column. These NULL values are clubbed at the top of the column in the
order in which they were entered into the table.
Key Points:
1. Unique key will not allow duplicate values.
2. Unique index is created automatically.
3. A table can have more than one UNIQUE KEY which is not possible in
PRIMARY KEY.
4. Unique key can combine 16 columns in a composite unique key.
5. Unique key cannot be LONG or LONG RAW data type.
UNIQUE CONCEPT
Syntax:
At column level At table level
Create table client_master
(clientno varchar2(6) PRIMARY KEY,
name varchar2(20) UNIQUE, age
number(2));
Create table client_master
(clientno varchar2(6) PRIMARY KEY,
name varchar2(20), age number(2),
UNIQUE(name, age));
NULL CONCEPT
NULL implies that the value is unknown and not that the value does not
exist or is absent. NOT NULL constraints are in-line constraints that
indicate that a column can not contain NULL values.
A NULL value can be inserted into columns of any data type.
Principles:
1. Setting NULL value is appropriate when actual values is unknown or
when value would not be meaningful.
2. A NULL value is not equivalent to a value zero if the data type is number
and is not equivalent to spaces if the data type is character.
3. A NULL value can be inserted into columns of any data type.
4. If the column has NULL value, ORACLE ignores any UNIQUE, FOREIGN
KEY, CHECK constraints that may be attached to the column.
Note: Now ORACLE has changed its rule to an empty string is treated as NULL
value.
NULL CONCEPT
Syntax:
Example:
CREATE TABLE salesman_master
(salesman_no varchar2(6) PRIMARY KEY,
Salesman_name varchar2(20) NOT NULL);
Note: NOT NULL constraint can not be applied at column level
<column_name> <datatype(size) NOT NULL
CHECK constraint
 Business rule validations can be applied to a table column by using
CHECK constraint. CHECK constraints must be specified as a logical
expression that evaluates either to TRUE or FALSE.
 A CHECK constraint takes substantially longer to execute as compared to
NOT NULL, PRIMARY KEY, FOREIGN KEY, UNIQUE. Thus, CHECK constraints
must be avoided if the constraint can be defined using NOT NULL,
PRIMARY KEY or FOREIGN KEY constraint.
CHECK constraint
At column level At table level
<column_name> <datatype(size) CHECK
(<logical_expression>)
CHECK (<logical_expression>)
For example,
CREATE TABLE client_master
(client_no varchar2(6) CHECK client_no
like C%);
For example,
CREATE TABLE client_master
(……………, ……………, …………,
CHECK (client_no LIKE C%));
PL / SQL
Procedural Language / Structured Query Language
PL/ SQL
 An extension to non-procedural language SQL.
 It combines the data-manipulation power of SQL with data-processing
power of the procedural language.
 PL/SQL provides high-level language features such as block structure,
conditional statements, loop statements, variable types, structured
data and customized error handling.
 The basic unit in PL/SQL is a block.
All PL/SQL programs are made up of blocks, which can be nested
within each other.
PL/ SQL
PL/ SQL: structure
DECLARE
/* Declarative section: variables, types, and local subprograms. */
BEGIN
/* Executable section: procedural and SQL-DML statements go here. */
/* This section of the block is required. */
EXCEPTION
/* Exception handling section: error handling statements go here. */
END;
PL/ SQL: structure ….
 SET SERVEROUTPUT ON is the SQL*Plus command1 to activate the
console output. You only need to issue this command once in a SQL*Plus
session.
 the keywords BEGIN...END define a scope and are equivalent to the curly
braces in Java {...}
 a semi-column character (;) marks the end of a statement
 the put_line function (in the built-in package dbms_output) displays a
string in the SQL*Plus console.
 The only SQL statements allowed in a PL/SQL program are SELECT, INSERT,
UPDATE, DELETE and several other data manipulation statements plus
some transaction control.
 Data definition statements like CREATE, ALTER, or DROP are not allowed.
 The executable section also contains constructs such as assignments,
branches, loops, procedure calls, and triggers.
 PL/SQL is not case sensitive.
PL/ SQL: variable declaration
SYNTAX:
Here, VARIABLE_NAME is the name of the variable and VARIABLE_DATATYPE
is any valid SQL data type such as DATE, NUMBER, or PL/ SQL data type such
as BOOLEAN or COMPOSITE data type.
VARIABLE_NAME VARIABLE_DATATYPE
PL/ SQL: variable declaration
BOOLEAN data type:
1. Used to store the logical values TRUE, FALSE, NULL
2. They do not take parameters
3. We cannot insert a BOOLEAN data type into a database column
COMPOSITE data type:
1. %TYPE
2. %ROWTYPE
%TYPE: provides data type information of a column or variable.
Example: X emp.sal %TYPE
– Here, %TYPE will declare a variable X having the same data type as
that column of emp table.
– It is not necessary to know the data type of sal column.
– If we change the data type of sal column in the database then data
type of X will change accordingly.
PL/ SQL: variable declaration
%ROWTYPE data type:
PL/ SQL record is used to store information that is related and consists of
different data types.
Example: EMP_RECORD is a variable which holds the value of one row of emp
table, i.e.,
Here, the fields of EMP_RECORD are having same name as columns of emp
table and can be called by using . (dot) notation
EMP_RECORD EMP %ROWTYPE
PL/ SQL
DISPLAYING USER MESSAGE ON SCREEN
To display the message on user screen, the SERVER OUTPUT flag should be
ON as:
Now, we can write the PL/ SQL code block to display the message to the user.
SET SERVEROUTPUT ON
DBMS_OUTPUT.PUT_LINE (‘welcome’)
PL/ SQL: control constructs
CONDITIONAL STATEMENTS
1. IF …. ENDIF
2. IF …. ELSE …. ENDIF
3. IF …. ELSE …. ENDIF …. ELSE …. ENDIF
ITERATIVE STATEMENTS
1. WHILE …. LOOP …. END LOOP
2. FOR …. LOOP …. END LOOP
3. LOOP …. EXIT …. END LOOP
UNCODITIONAL BRANCHING
1. GOTO
PL/ SQL: exceptions
 Any well-written program must have the ability to handle errors
intelligently and recover from them, if possible.
 ORACLE has given such facility, called EXCEPTIONS to handle run time
errors or abnormal conditions according to user’s choice.
 EXCEPTIONS are functions used to generate error messages and replace
default error messages.
 We can handle both unexpected and expected errors during execution
through EXCEPTIONS.
 Designed for run-time, not for compile time
 Types of EXCEPTIONS:
1. Pre-defined exception
2. User-defined exception
3. Pragma exception
PL/ SQL: pre-defined exception
Exception Name Reason Error Number
CURSOR_ALREADY_OPEN When you open a cursor that is already
open. ORA-06511
INVALID_CURSOR
When you perform an invalid operation
on a cursor like closing a cursor, fetch
data from a cursor that is not opened.
ORA-01001
NO_DATA_FOUND When a SELECT...INTO clause does not
return any row from a table. ORA-01403
TOO_MANY_ROWS When you SELECT or fetch more than one
row into a record or variable. ORA-01422
ZERO_DIVIDE When you attempt to divide a number by
zero. ORA-01476
PL/ SQL: pre-defined exception
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we
can write a code to handle the exception as given below.
BEGIN
Execution section
EXCEPTION WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;
PL/ SQL: RAISE_APPLICATION_ERROR
 RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used
to display the user-defined error messages along with the error number
whose range is in between -20000 and -20999.
 Whenever a message is displayed using RAISE_APPLICATION_ERROR, all
previous transactions which are not committed within the PL/SQL Block
are rolled back automatically (i.e. change due to INSERT, UPDATE, or
DELETE statements).
 RAISE_APPLICATION_ERROR raises an exception but does not handle it.
 RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
RAISE_APPLICATION_ERROR (error_number, error_message);
PL/ SQL: RAISE_APPLICATION_ERROR
SYNTAX
Here,
• The Error number must be between -20000 and -20999
• The Error_message is the message you want to display when the error
occurs.
Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:
1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in
the execution section.
3. Finally, catch the exception and link the exception to a user-defined
error number in RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR (error_number, error_message);
PL/ SQL: user-defined Exceptions
 Apart from system exceptions we can explicitly define exceptions based on
business rules. These are known as user-defined exceptions.
 Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name
in the exception section.
 User-defined exceptions are declared in DECLARE section of a PL/ SQL
block. Just like variables, exceptions have a type EXCEPTION. Example:
 User-defined exceptions are raised by giving the RAISE statement.
 The built-in exception can also be raised by using RAISE statement.
invalid_day EXCEPTION
PL/ SQL: user-defined Exceptions
Syntax:
Example:
DECLARE
invalid_day EXCEPTION
BEGIN
IF RTRIM (to_char(sysdate, ‘day’), ‘ ‘) = ‘Thursday’ THEN
RAISE invalid_day
ELSE
dbms_output.put_line(“you are allowed to do data entry”)
END If;
EXCEPTION
WHEN invalid_day THEN
RAISE_APPLICATION_ERROR(-20001, ‘not a valid day for data entry’)
END;
IF <condition> THEN
RAISE <exception_name>;
ELSE
….
END IF;
PL/ SQL: when others trigger
WHEN OTHERS handle all errors not already handled in the block.
Example:
WHEN no_data_found THEN
insert into error_table values(‘no employees joined in 1992’);
WHEN others THEN
insert into error_table values(‘some unknown error’);
END;
In the case, WHEN OTHERS trigger for all errors, we may wish to evaluate the
associated error code and error message.
PL/ SQL: when others trigger
PL/ SQL provides two functions for this purpose:
1. SQLCODE: returns numeric data as negative number.
2. SQLERRM: it returns the message related with the error, may be assigned
to VARCHAR2 type of variable and message length of 512 characters.
EXAMPLE: WHEN OTHERS then
error_code:= SQLCODE;
error_message:= SQLERRM;
insert into error_table values(error_code ||
error_message);
PL/ SQL: cursors
 Oracle creates a memory area, known as context area, for processing an
SQL statement, which contains all information needed for processing the
statement, for example, number of rows processed, etc.
 A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement. The set of rows the cursor holds is referred to as the active set.
 There are two types of cursors:
1. Implicit cursors
2. Explicit cursors
PL/ SQL: implicit cursors
 Implicit cursors are automatically created by Oracle whenever an SQL
statement is executed, when there is no explicit cursor for the statement.
Programmers cannot control the implicit cursors and the information in it.
 Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an
implicit cursor is associated with this statement. For INSERT operations,
the cursor holds the data that needs to be inserted. For UPDATE and
DELETE operations, the cursor identifies the rows that would be affected.
PL/ SQL: explicit cursors
 Explicit cursors are programmer defined cursors for gaining more control
over the context area. An explicit cursor should be defined in the
declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.
 SYNTAX:
 Working with an explicit cursor involves four steps:
1. Declaring the cursor for initializing in the memory
2. Opening the cursor for allocating memory
3. Fetching the cursor for retrieving data
4. Closing the cursor to release allocated memory
CURSOR cursor_name IS select_statement;
PL/ SQL: explicit cursors
DECLARING THE CURSOR
 Declaring the cursor defines the cursor with a name and the associated
SELECT statement. For example:
OPENING THE CURSOR
 Opening the cursor allocates memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we
will open above-defined cursor as follows:
CURSOR c_customers IS SELECT id, name, address FROM customers;
OPEN c_customers;
PL/ SQL: explicit cursors
FETCHING THE CURSOR
• Fetching the cursor involves accessing one row at a time. For example we
will fetch rows from the above-opened cursor as follows:
CLOSING THE CURSOR
• Closing the cursor means releasing the allocated memory. For example,
we will close above-opened cursor as follows:
FETCH c_customers INTO c_id, c_name, c_addr;
CLOSE c_customers;
PL/ SQL: triggers
 Triggers are stored programs, which are automatically executed or fired
when some events occur. Triggers are, in fact, written to be executed in
response to any of the following events:
1. A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE).
2. A database definition (DDL) statement (CREATE, ALTER, or DROP).
3. A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Note: Triggers could be defined on the table, view, schema, or database
with which the event is associated.
PL/ SQL: triggers
ADVANTAGES: Triggers can be written for the following purposes:
1. Generating some derived column values automatically
2. Enforcing referential integrity
3. Event logging and storing information on table access
4. Auditing
5. Synchronous replication of tables
6. Imposing security authorizations
7. Preventing invalid transactions
PL/ SQL: triggers
CREATING TRIGGERS: SYNTAX –
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
PL/ SQL: triggers
Where,
1. CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing
trigger with thetrigger_name.
2. {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
3. {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
4. [OF col_name]: This specifies the column name that would be updated.
5. [ON table_name]: This specifies the name of the table associated with the trigger.
6. [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values
for various DML statements, like INSERT, UPDATE, and DELETE.
7. [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
8. WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.

Mais conteúdo relacionado

Mais procurados

Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
SANTOSH RATH
 
BCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdfBCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdf
KeerthanaP37
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 

Mais procurados (19)

Dbms practical list
Dbms practical listDbms practical list
Dbms practical list
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
DML using oracle
 DML using oracle DML using oracle
DML using oracle
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
Create table
Create tableCreate table
Create table
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
BCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdfBCS4L1-Database Management lab.pdf
BCS4L1-Database Management lab.pdf
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Assignment#07
Assignment#07Assignment#07
Assignment#07
 
Oracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guideOracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guide
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
 
My sql.ppt
My sql.pptMy sql.ppt
My sql.ppt
 

Semelhante a Lab

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
EliasPetros
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
EliasPetros
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 

Semelhante a Lab (20)

chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Query
QueryQuery
Query
 
SQL Query
SQL QuerySQL Query
SQL Query
 
SQL
SQLSQL
SQL
 
SQL
SQLSQL
SQL
 
Module 3
Module 3Module 3
Module 3
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
lovely
lovelylovely
lovely
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 

Último

Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
MarinCaroMartnezBerg
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
JoseMangaJr1
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
amitlee9823
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 

Último (20)

Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Predicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science ProjectPredicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science Project
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Anomaly detection and data imputation within time series
Anomaly detection and data imputation within time seriesAnomaly detection and data imputation within time series
Anomaly detection and data imputation within time series
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 

Lab

  • 2. SQL: Structured Query Language  SQL is a language that provides an interface to database systems, developed by IBM in the 1970  SQL: Structured Query Language  SQL is a standard language for accessing databases  SQL is an ANSI (American National Standards Institute) standard
  • 3. SQL: History & functions  how to use SQL to access and manipulate data in: ORACLE  SQL can execute queries against a database  SQL can RETRIEVE DATA from a database  SQL can insert records in a database  SQL can update records in a database  SQL can delete records from a database  SQL can create new databases  SQL can create new tables in a database  SQL can create stored procedures in a database  SQL can create views in a database  SQL can set permissions on tables, procedures, and views
  • 5. SQL: Components  DDL: • It is a set of SQL commands used to create, modify and delete database structures but not data. • These commands are normally used by DBA, database designer or application developer. • Anybody using DDL command must have the CREATE object privilege and a tablespace area in which to create objects  DML: • It is the area of SQL that allows changing data within the database  DCL: • Control access to data and to the database  DQL: • Allows getting data from the database and imposing ordering upon it. It includes SELECT statement fired against tables.
  • 6. SQL: SELECT statement – for retrieving data SYNTAX SELECT [DISTINCT | ALL] {* | select_list} FROM {table_name [alias] | view_name} [{table_name [alias] | view_name}]... [WHERE condition] [GROUP BY condition_list] [HAVING condition] [ORDER BY {column_name | column_# [ ASC | DESC ] } ...  The SELECT clause is mandatory and carries out the relational project operation.  The FROM clause is also mandatory. It identifies one or more tables and/or views from which to retrieve the column data displayed in a result table.  The WHERE clause is optional and carries out the relational select operation. It specifies which rows are to be selected.  The GROUP BY clause is optional. It organizes data into groups by one or more column names listed in the SELECT clause.  The optional HAVING clause sets conditions regarding which groups to include in a result table. The groups are specified by the GROUP BY clause.  The ORDER BY clause is optional. It sorts query results by one or more columns in ascending or descending order.
  • 7. SQL: SELECT statement - example  SELECT * FROM client_master;  SELECT name, city FROM client_master;
  • 8. SQL: SELECT statement – for retrieving data Column Alias An alias is used to rename a column or an expression during display. The alias to a column or an expression appears as the heading in the output of a query. It is useful in providing a meaningful heading to long expressions in the SELECT query. By default, the alias appears in uppercase in the query output without spaces CLIENT_NAME incremented_balance Ivan Bayross 30000 Mamta MAzumdar 0 Chhaya Bankar 10000 Ashwini Joshi 0 Hansel colaco 4000 Deepak Sharma 0 select name as client_name, baldue*2 "incremented_balance" from client_master;
  • 9. SQL: SELECT statement – for retrieving data
  • 10. SQL: Components  DDL: • It is a set of SQL commands used to create, modify and delete database structures but not data. • These commands are normally used by DBA, database designer or application developer. • Anybody using DDL command must have the CREATE object privilege and a tablespace area in which to create objects  DML: • It is the area of SQL that allows changing data within the database  DCL: • Control access to data and to the database  DQL: • Allows getting data from the database and imposing ordering upon it. It includes SELECT statement fired against tables.
  • 11. SQL: Components DDL DML DCL CREATE ALTER DROP RENAME TRUNCATE COMMENT INSERT UPDATE DELETE CALL EXPLAIN PLAN LOCK COMMIT ROLLBACK SAVEPOINT SET TRANSACTION GRANT REVOKE
  • 12. SQL: Basic DDL commands SQL CREATE TABLE Syntax: CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); Example: CREATE TABLE student ( student_ID number(9), name varchar(30), age number(2), gender char(1), city varchar(15) ); SQL DROP Syntax: DROP TABLE table_name Example: DROP TABLE student SQL RENAME Syntax: RENAME table_name TO new_table name Example: RENAME student TO stu_info
  • 13. SQL: Basic DDL commands - CREATE SQL CREATE TABLE Syntax: CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); Example: create table client_master1 (client_no varchar2(6), name varchar2(20), address varchar2(20), city varchar2(15), pincode number(8), state varchar2(15), baldue number(10,2)); SYNTAX: Provides a description of the specified table or view DESCRIBE { table-Name | view-Name } OR DESC { table-Name | view-Name } Note: The EXPLAIN statement provides information specified table or view in MySQL
  • 14. SQL: Basic DDL commands - CREATE CREATING A TABLE FROM A TABLE CREATE TABLE table_name (col1, col2, ….) AS SELECT col1, col2 from table_name; For example: create table emp_accounts (ename, esalary, eage) AS SELECT ename, salary, age from EMPLOYEE;
  • 15. SQL: Basic DDL commands - CREATE
  • 16. SQL: Basic DDL commands - CREATE
  • 17. SQL: Basic DDL commands - CREATE
  • 18. CONCATENATION OPERATORS  Concatenation operator can be used to join two string values or expressions in a SELECT query. The double vertical bar symbol, || is used as string concatenation operator. It is applicable only for character and string column values resulting into a new character expression  select name || 'earns' || baldue from client_master;  select name || '[' || client_no || ']' || 'earns' || baldue from client_master; SQL: Basic DQL commands - SELECT
  • 19. SQL: Basic DQL commands - SELECT
  • 20. SQL: Basic DQL commands - SELECT
  • 21. SQL: Basic DDL commands - ALTER SQL ALTER TABLE Syntax: To add a column in a TABLE, use the following syntax: ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax: ALTER TABLE table_name DROP COLUMN column_name To change the data type of a column in a table, use the following syntax: ALTER TABLE table_name MODIFY column_name datatype Note: Oracle doesn’t support this syntax to add a column name in the middle of a table ALTER TABLE tablename ADD columnname AFTER columnname; SQL TRUNCATE Syntax: TRUNCATE TABLE table_name; Example: TRUNCATE TABLE student;
  • 22. SQL: Basic DDL commands - ALTER
  • 23. SQL: Basic DDL commands - ALTER
  • 24. SQL: Basic DDL commands - ALTER
  • 25. SQL: DML commands SQL INSERT Syntax: INSERT INTO table_name VALUES (value1,value2,value3,...); INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); Example: INSERT INTO student VALUES (12, Smith, 20, M, Delhi); INSERT INTO student (student_ID, name, age, gender, city) VALUES (12, Smith, 20, M, Delhi); SQL DELETE Syntax: DELETE FROM table_name Example: DELETE FROM student Removal of specific rows: DELETE FROM table_name WHERE conditions;
  • 26. SQL: DML commands SQL UPDATE Syntax: The UPDATE statement is used to update existing records in a TABLE UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value; Example: UPDATE student SET name=John, city=Mumbai WHERE student_ID=12; Be careful: when updating records, what if we omitted WHERE clause, like UPDATE student SET name=John, city=Mumbai; Check !!!
  • 27. SQL: SELECT statement – with where clause SYNTAX SELECT * FROM table_name [WHERE condition] Note: Oracle provides WHERE clause in an SQL query to apply a filter on the rows retrieved. For example, SELECT * FROM EMPLOYEE WHERE name = ‘A’;
  • 28. SQL: SELECT statement – with where clause
  • 29. SQL IDENTIFIERS  No SQL keywords may be used  Table name must be unique within the database  For each column, the user must specify a name that is unique within the table DATA TYPES  Each column must have a datatype specified  Standards include various numeric types, fixed-length and varying-length character strings, bit strings, and user-defined types  Available datatypes vary from DBMS to DBMS
  • 30. SQL: Data types (ORACLE 9i) • String types – CHAR(n) – fixed-length character data, n characters long Maximum length = 2000 bytes – VARCHAR2(n) – variable length character data, maximum 4000 bytes – LONG – variable-length character data, up to 4GB. Maximum 1 per table • Numeric types – NUMBER(p,q) – general purpose numeric data type – INTEGER(p) – signed integer, p digits wide – FLOAT(p) – floating point in scientific notation with p binary digits precision • Date/time type – DATE – fixed-length date/time in dd-mm-yy form
  • 31. Character Data Types  VARCHAR2 • Variable-length character data (up to 4000 characters) • Syntax: columnname VARCHAR2(maximum_size) • If user enters data value less than maximum_size, DBMS only stores actual character values  CHAR • Fixed-length character data (default = 2000) • Syntax: columnname CHAR(maximum_size) • If user enters data value less than maximum_size, DBMS adds trailing blank spaces to the end of entry  Oracle stores CHAR and VARCHAR2 data using the ASCII coding
  • 32. Number Data Types  NUMBER • Used for all numeric data • Syntax - columnname NUMBER [([precision,] [scale])]  Example: • s_balance NUMBER (5,2) • s_gpa NUMBER (3,2) # of digits both to left and right of decimal point # of digits on the right side of decimal point
  • 33. Data Types- Comparison with other RDBMS
  • 34. Computations on table data  None of the techniques used till now allows display of data from a table after some arithmetic has been done with it.  For example, to display employee_name and employee’s salary from the employee_master table along with the annual salary of the employee (i.e., salary * 12). The arithemtic (salary * 12) is an example of table data arithmetic.  SQL sentences includes: 1. Arithmetic operators 2. Logical operators
  • 35. Oracle allows arithmetic operators to be used while viewing records from a table or while performing data manipulation operations such as insert, update and delete. These include: 1. Addition + 2. Subtraction - 3. Division / 4. Multiplication * 5. Exponentiation ** 6. Enclosed operation () Computations on table data
  • 36. For example, Retrieve the contents of the column product_no, description and compute 5% of the values contained in the column sell_price and 105% of the values in the first sell price for each row from the table product_master. Note: Here, sell_price*0.05 and sell_price*1.05 are not columns in the table product_master. However, the calculations are done on the contents of the column sell_price of the table product_master. Also, ORACLE engine will use column names of the product_master as column headers when displaying column output on the VDU screen Computations on table data SELECT product_no, description, sell_price*0.05, sell_price*1.05 FROM product_master
  • 37. Output: Renaming columns used with expression lists: rename the default columns names with alias, when required. Syntax: SELECT column_name result_column_name, column_name result_column_name FROM tablename For example, Computations on table data Product_no Description Sell_price*0.05 Sell_price*1.05 SELECT product_no, description, sell_price*0.05 “current”, sell_price*1.05 “total” FROM product_master
  • 38. Logical operators Logical operators that can be used in SQL sentences are: 1. AND operator 2. OR operator 3. NOT operator AND operator:  The AND operator allows creating an SQL statement based on two or more conditions being met.  It can be used in any valid SQL statements such as SELECT, INSERT, UPDATE, or DELETE.  Oracle engine will process all rows in a table and display the result only when all the conditions specified using the AND operator are satisfied.
  • 39. Logical operators OR operator:  The OR condition allows creating an SQL statement where records are returned when any one of the conditions are met.  It can be used in any valid SQL statements such as SELECT, INSERT, UPDATE, or DELETE.  Oracle engine will process all rows in a table and display the result only when any of the conditions specified using the OR operator is satisfied. NOT operator:  Oracle engine will process all rows in a table and display only those records that do not satisfy the conditions specified.
  • 40. Range searching - BETWEEN  In order to select data that is within a range of values, the BETWEEN operator is used.  The BETWEEN operator allows the selection of rows that contain values within a specified lower and upper limit.  The two values in between the range must be linked with the keyword AND.  The BETWEEN operator can be used with both character and numeric data types. (Note: data types cannot be mixed)  In order the select data that is not in the specified range, the NOT BETWEEN operator is used.
  • 41. Pattern matching – LIKE predicate  LIKE predicate allows comparison of one string value with another string value, which is not identical.  Wildcard characters to be used in LIKE predicate: 1. % allows to match any string of any length 2. _ allows to match on a single character  For example, list all the clients whose name begins with the letter ‘A’ OR, list the name of those client whose second character as ‘A’ SELECT name FROM client_master WHERE name LIKE ‘A%’ SELECT name FROM client_master WHERE name LIKE ‘_A%’
  • 42. IN and NOT IN predicates  As the arithmetic operator ‘=‘ compares a single value to another single value. In case a value needs to be compared to a list of values then the IN predicate is used.  IN predicate helps reduce the need to use multiple OR conditions  For example, list the details of the clients named mamta, hansel and chhaya. SELECT * FROM client_master WHERE name IN (‘mamta’, ‘hansel’, ‘chhaya’);
  • 43. IN and NOT IN predicates  The NOT IN predicate is the opposite of the IN predicate.  It will select all the rows where values do not match the values in the list.  For example, list the details of the clients other than mamta, hansel and chhaya. SELECT * FROM client_master WHERE name NOT IN (‘mamta’, ‘hansel’, ‘chhaya’);
  • 44. Queries: Create the table described below: Column Name Data Type Size PRODUCTNO VARCHAR2 6 DESCRIPTION VARCHAR2 15 PROFITPERCENT NUMBER 4,2 UNITMEASURE VARCHAR2 10 QTYONHAND NUMBER 8 REORDERLVL NUMBER 8,2 SELLPRICE NUMBER 8,2 COSTPRICE NUMBER 8,2 PRODUCT_MASTER
  • 45. Queries: Insert the following values: PRODUCT_MASTER PRODUCTNO DESCRIPTION PROFIT PERCENT UNIT MEASURE QTYON HAND REORDER LVL SELL PRICE COST PRICE P00001 T-Shirts 5 Piece 200 50 350 250 P0345 Shirts 6 Piece 150 50 500 350 P06734 Cotton Jeans 5 Piece 100 20 600 450 P07865 Jeans 5 Piece 100 20 750 500 P07868 Trousers 2 Piece 150 50 850 550 P07885 Pull Overs 2.5 Piece 80 30 700 450 P07965 Denim Shirts 4 Piece 100 40 350 250 P07975 Lycra Tops 5 Piece 70 30 300 175 P08865 Skirts 5 Piece 75 30 450 300
  • 46. Queries: Write the SQL queries for the following: 1. Retrieve the contents of the column product_no, description and compute 5% of the values contained in the column sell_price and rename it as “Increase” and 105% of the values contained in the field sell_price and rename it as “New Price” for each row from the table product_master. 2. Retrieve the contents of the columns product no, description, profit percent, sell price from the table product_master where the values contained in the field profit_percent is between 10 and 20 both inclusive. 3. Retrieve Client information like client no, name, address, city, and pincode for all clients where the field pin code has the value 400054 or 400057. 4. Retrieve specified client information for the clients who are not in ‘Bombay’ or ‘Delhi’. 5. Retrieve all the information about client whose name begin with letters ‘I’ from client_master. 6. Retrieve all the information about client whose name begin with letters ‘I’ from client_master. 7. Retrieve all the information of client whose name’s second letter is either ‘a’ or ‘h’. 8. Retrieve the information of the client whose last letter of name is ‘s’. 9. Retrieve the names of all clients whose state is in Maharashtra, Delhi.
  • 47. Queries: Write the SQL queries for the following: 1. Retrieve the value of 100*25 from dual table. 2. Retrieve the system date from dual table. 3. Retrieve and display the employee name in upper and lower case from employee table. Also display the name with initial capital form. 4. Retrieve all the information about employees whose salary is between 10000 to 30000. 5. Retrieve the maximum salary, total salary and average of each salary of the employee. 6. Retrieve all the information of employees whose name’s first letter starts from ‘M’ 7. Retrieve the round off number 15.91 from dual table. 8. Retrieve the square root of 25 from dual table. 9. Retrieve the number of employees working in. 10. Retreive the length of the names of employees
  • 48. ORACLE DUAL table  DUAL is a table automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X. Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement.  Because DUAL has only one row, the constant is returned only once. Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the value will be returned as many times as there are rows in the table  DESC DUAL;  SELECT * FROM DUAL; NAME NULL? TYPE Dummy Varchar2(1) D X
  • 49. SYSDATE SYSDATE is a pseudo column that contains the current date and time. It requires no arguments when selected from the table dual and returns the current date. For Example: SELECT sysdate FROM DUAL; SELECT to_char(sysdate,'HH:MI:SS') “time” FROM DUAL; SELECT to_char(sysdate,'MI') "minutes" FROM DUAL; SELECT to_char(sysdate,'SS') "seconds" FROM DUAL; SELECT to_char(sysdate,'AM') FROM DUAL; //For AM or PM SELECT to_char(sysdate,'BC') FROM DUAL; //For AD or BC SELECT to_char(sysdate,'CC') FROM DUAL; //Century SELECT to_char(sysdate,'DL') FROM DUAL; //Date in long format
  • 50. Functions SQL Functions Functions are a very powerful feature of SQL and can be used to do the following: • Perform calculations on data • Modify individual data items • Manipulate output for groups of rows • Format dates and numbers for display • Convert column datatypes Note: SQL functions may accept arguments and always return a value.
  • 51. Functions Oracle Built in Functions: There are two types of functions in Oracle.  Single Row Functions: Single row or Scalar functions return a value for every row that is processed in a query.  Group Functions: These functions group the rows of data based on the values returned by the query. This is discussed in SQL GROUP Functions. The group functions are used to calculate aggregate values like total or average, which return just one total or one average value after processing a group of rows.
  • 52. Functions There are four types of single row functions. They are: 1. Numeric Functions: These are functions that accept numeric input and return numeric values. 2. Character or Text Functions: These are functions that accept character input and can return both character and number values. 3. Date Functions: These are functions that take values that are of datatype DATE as input and return values of datatype DATE, except for the MONTHS_BETWEEN function, which returns a number. 4. Conversion Functions: These are functions that help us to convert a value in one form to another form. For Example: a null value into an actual value, or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc. Note: You can combine more than one function together in an expression. This is known as nesting of functions.
  • 54. Functions SINGLE-ROW FUNCTIONS: CHARACTER FUNCTIONS Single-row character functions accept character data as input and can return both character and number values. Character functions can be divided into the following:  Case manipulation functions  Character manipulation functions CASE MANIPULATION FUNCTIONS:  LOWER  UPPER  INITCAP
  • 56. Functions CASE MANIPULATION FUNCTIONS LOWER, UPPER, and INITCAP are the three case conversion functions.  LOWER: Converts mixed case or uppercase character string to lowercase  UPPER: Converts mixed case or lowercase character string to uppercase  INITCAP: Converts first letter of each word to uppercase and remaining letters to lowercase
  • 57. Functions CHARACTER MANIPULATION FUNCTIONS  CONCAT  SUBSTR  LENGTH  INSTR  LTRIM  RTRIM  LPAD  RPAD  REPLACE
  • 58. Functions CONCAT: The Oracle CONCAT function allows you to join (concatenate) two strings together. SYNTAX: CONCAT( string1, string2 ) Where, string_1 and string_2 are the two strings to be concatenated. For Example: SELECT CONCAT('Let''s', ' learn Oracle') FROM dual; OR, SELECT 'Let''s' || ' learn Oracle' FROM dual; In Oracle, the CONCAT function will only allow you to concatenate two values together. If you want to concatenate more values than two, you can nest multiple CONCAT function calls. The || operator allows you to concatenate 2 or more strings together: For Example: SELECT CONCAT(CONCAT('A', 'B'),'C') FROM dual; OR, SELECT 'A' || 'B' || 'C' FROM dual;
  • 59. Functions SUBSTR: The Oracle SUBSTR (SUBSTRING) function lets you extract a portion of a string (a 'substring') from a string of characters. SYNTAX: SUBSTR( source_string, start_position [, length ] )  The source_string is the string that the substring will be taken from.  The starting_position is the position in the source_string where you want to start extracting characters. The first position in the source_string is always '1', NOT '0', as in many other languages. • If the starting_position is 0, then SUBSTR treats start_position as 1 (ie: the first position in the string). • If the starting_position is a positive number, then SUBSTR starts from the beginning of the string. • If the starting_position is a negative number, then SUBSTR starts from the end of the source_string and counts backwards.
  • 60. Functions  The length parameter is optional, and specifies the number of characters to extract.  If the length parameter is not used then SUBSTR will return everything from the starting_position to the end of the string.  If length is a negative number, then SUBSTR will return a NULL value. For Example: SELECT SUBSTR (‘SECURE’, 3, 4) “substring” FROM DUAL; SELECT SUBSTR('Dinner starts in one hour.', 8, 6) “substring” from DUAL; SELECT SUBSTR('Dinner starts in one hour.', 0, 6) “substring” from DUAL; SELECT SUBSTR('Dinner starts in one hour.', -4, 3) “substring” from DUAL; SELECT SUBSTR('Dinner starts in one hour.', -9, 3) “substring” from DUAL; SELECT SUBSTR('Dinner starts in one hour.', -9, 2) “substring” from DUAL;
  • 61. Functions LENGTH: The Oracle PL/SQL LENGTH function returns the length of the specified string. It calculates the length using characters as defined by the input character set. The return value the LENGTH function is always of the datatype NUMBER. SYNTAX: LENGTH( string ) string is the string of characters to find the length of. The input string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. If string is NULL or empty, then the LENGTH function returns NULL. For Example: SELECT LENGTH('Oracle') FROM DUAL; SELECT LENGTH(‘Good Morning’) FROM DUAL;
  • 62. Functions INSTR: The Oracle INSTR function searches inside a string for a substring. The Oracle INSTR function works in a way similar to the SUBSTR function, but INSTR returns an integer number indicating the position of the substring within the string, rather than returning the substring itself. SYNTAX: INSTR( string, substring [, start_position [, nth_appearance ] ] ) String: The string to search. string can be CHAR, VARCHAR2, NCHAR, NV ARCHAR2, CLOB, or NCLOB. Substring: The substring to search for in string. substring can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. start_position: Optional, The position in string where the search will start. If omitted, it defaults to 1. The first position in the string is 1. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string. nth_appearance: Optional. The nth appearance of substring. If omitted, it defaults to 1
  • 63. Functions For Example: SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL; SELECT INSTR('CORPORATE FLOOR','OR', 2, 2) "Instring" FROM DUAL; SELECT INSTR('CORPORATE FLOOR','OR', 1, 2) "Instring" FROM DUAL; SELECT INSTR('CORPORATE FLOOR','OR', -1, 2) "Instring" FROM DUAL; SELECT INSTR('CORPORATE FLOOR','OR', -3,2) "Instring" FROM DUAL; LTRIM: The Oracle LTRIM function removes all specified characters from the left-hand side of a string. Space characters are the default. Syntax: LTRIM( string1 [, trim_string] ) String1: The string to trim the characters from the left-hand side. trim_string: Optional, the string that will be removed from the left-hand side of string1. If this parameter is omitted, the LTRIM function will remove all leading spaces from string1. For Example: Select LTRIM('NISHA', 'N') from dual;
  • 64. Functions RTRIM: The Oracle RTRIM function removes all specified characters from the right-hand side of a string Syntax: RTRIM( string1 [, trim_string ] ) string1: The string to trim the characters from the right-hand side. trim_string: Optional, the string that will be removed from the right- hand side of string1. If this parameter is omitted, the RTRIM function will remove all trailing spaces from string1. For Example: SELECT RTRIM('SUNILA','A') from DUAL; OR, SELECT RTRIM('SUNILA') from DUAL; SELECT RTRIM('123Tech123', '123') from DUAL;
  • 65. Functions LPAD: The Oracle LPAD function pads (adds characters to) the left-side of a string with a given set of characters. Syntax: LPAD(string, padding_length, [ padding_string ])  String: string to prepend or pad characters onto. The padded characters are added to the left-hand side of the string.  padding_length: is the number of characters to return (not the number of characters to add). If the padding_length is smaller than the original string, the LPAD function will truncate the string to the size of the padding_length  Note: padding_string is optional. This is the character string that will be padded to the left-hand side of string. If this parameter is omitted, the LPAD function will default to padding space characters to the left-side of the string. For example: SELECT LPAD('page 1', 10, '*') “Left padded” from dual;
  • 66. Functions RPAD: In Oracle PL/SQL, RPAD is a built in function which pads the input string with extra characters from the right side. It accepts three arguments: the input string, the net length of the string including padding, and the character to be used for padded. Note: The third argument is optional. If it is not provided, Oracle will use blank spaces as default padding character. Syntax: RPAD (input_string, length, padding_character) For Example: SELECT RPAD(‘Page 1',10,‘*’) FROM DUAL;
  • 67. Functions REPLACE: Replace function is used to replace a character with another character in a string. Syntax: REPLACE( string1, string_to_replace [, replacement_string]  String1:The string to replace a sequence of characters with another set of characters.  string_to_replace: The string that will be searched for in string1.  replacement_string: Optional, all occurrences of string_to_replace will be replaced with replacement_string in string1. If the replacement_string parameter is omitted, the REPLACE function simply removes all occurrences of string_to_replace, and returns the resulting string. For Example: SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL;
  • 68. Functions NUMBER FUNCTIONS Number functions accept numeric input and return numeric values:  ROUND  TRUNC  MOD  ABS  POWER  SQRT  EXP  FLOOR  CEIL Other functions:  EXTRACT  GREATEST  LEAST
  • 69. Number Functions: ROUND In Oracle, ROUND is a built in overloaded function, which is used to round off numeric and DATE type inputs to a specified precision Syntax: ROUND( n, X) In the syntax example above, "n" can be a numeric or date type input. "X" is the rounding format. Date type inputs can be rounded by year, month, quarter, week, hour and minute. For Example: SELECT ROUND(1.2536,2) FROM DUAL; SELECT ROUND(1234,-2) FROM DUAL; SELECT ROUND(TO_DATE('02-AUG-2011','DD-MM-YYYY'),'YYYY') FROM DUAL; Note: TO_CHAR - Convert to character string & TO_DATE - Convert to date value
  • 70. Number Functions: TRUNC The TRUNC function truncates either a number or a datetime value. The syntax of the TRUNC function is different depending on the whether it is being used for a number or a date and time value. TRUNC (datetime): The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model. Syntax: TRUNC(datetime_exp, [fmt]); The [fmt] parameter is the format that indicates how the date and time number should be truncated. If you omit fmt, then date is truncated to the nearest day. TRUNC(number):When you specify a number as an argument, the TRUNCATE function truncates a number to a specified number of decimal places. Syntax: TRUNC (number, tvalue) tvalue is an integer value that specifies the number of places to the right or left of the decimal point to which the number should be truncated. When the tvalue parameter is positive, digits to the right of the decimal point are truncated. When tvalue is negative the digits to the left of the decimal point are truncated. When the tvalueparameter is omitted, number is truncated to 0 decimal places.
  • 71. Number Functions: TRUNC TRUNC (datetime): For Example SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR') FROM DUAL; SELECT TRUNC(TO_DATE('22-AUG-03','DD-MON-YY'), 'MONTH') FROM DUAL; SELECT TRUNC(TO_DATE('22-AUG-03','DD-MON-YY'), 'DAY') FROM DUAL; TRUNC(number): For Example SELECT TRUNC(125.815) from DUAL; SELECT TRUNC(125.815, 1) from DUAL; SELECT TRUNC(125.815, 2) from DUAL; SELECT TRUNC(125.815, 3) from DUAL; SELECT TRUNC(125.815, -1) from DUAL; SELECT TRUNC(125.815, -2) from DUAL; SELECT TRUNC(125.815, -3) from DUAL; Note: When a date format is used by TO_CHAR or TO_DATE they return a formatted date/time. When used by TRUNC they will return the first day of the period. When used by ROUND the values will round up at mid year/mid month (July 1 or 16th day)
  • 72. Number Functions: MOD The Oracle MOD (short for modulus) function returns the remainder when one argument is divided by the second argument. It accepts two number arguments and returns a single numeric value. Note: The modulus is calculated according to the formula: x - y * floor(x/y). Syntax: MOD(x,y)  The remainder will be returned when 'x' is divided by 'y‘  The mod function will return x if y is 0. If y = 0, it returns x. For Example: SELECT MOD(10,3) RES FROM DUAL; SELECT MOD(3,10) RES FROM DUAL; SELECT MOD(11,-4) "Modulus" FROM DUAL; SELECT MOD(-11,4) "Modulus" FROM DUAL; SELECT MOD(-11,-4) "Modulus" FROM DUAL;
  • 73. Number Functions: ABS In Oracle PL/SQL, the ABS function returns the absolute value of a number, which will always be zero or a positive number. Syntax: ABS( number )  Number: The number to convert to an absolute value. For Example: SELECT ABS(-23.65) "Absolute" FROM DUAL; SELECT ABS(0005) "Absolute" FROM DUAL; SELECT ABS(20.537) FROM DUAL;
  • 74. Number Functions: POWER The Oracle PL/SQL, the POWER function is a built in function which takes two numeric inputs and returns numeric result as first argument raised to second argument. Syntax: POWER(x,y) Where, "x" is the base while "y" is the exponent. For Example: SELECT POWER(10,2) FROM DUAL; SELECT POWER(3,2) "Raised" FROM DUAL; SELECT POWER(-5, 3) "Raised" FROM DUAL; SELECT POWER(6.2, 3) "Raised" FROM DUAL; SELECT POWER(6.2, 3.5) "Raised" FROM DUAL;
  • 75. Number Functions: SQRT In Oracle PL/SQL, SQRT is a built in function which returns the square root of a numeric input. It returns positive output if the input argument is a number. Note: For negative input arguments, it raises ORA-01428 exception. Syntax: SQRT(x)  x: A positive number that is used in the square root calculation. For Example: SELECT SQRT(9) "square root" FROM DUAL; SELECT SQRT(37) "square root" FROM DUAL; SELECT SQRT(-20) "square root" FROM DUAL;
  • 76. Number Functions: EXP The Oracle EXP function returns e raised to the nth power, where e = 2.71828 Syntax: exp( number )  Number: The power to raise e. For Example: SELECT EXP(2) FROM dual; SELECT EXP(3.1) FROM dual; SELECT EXP(-3) FROM dual;
  • 77. Number Functions: FLOOR The FLOOR function rounds a number down to the next higher integer. If number is already rounded, it simply returns the number unchanged. Syntax: FLOOR(number) Number: The value used to determine the largest integer value that is equal to or less than a number. For Example: SELECT FLOOR(15.7) "Floor" FROM DUAL; SELECT FLOOR(-5.9) "Floor" FROM DUAL; SELECT FLOOR(-27.8) "Floor" FROM DUAL;
  • 78. Number Functions: CEIL The Oracle CEIL() function rounds a number up to the next higher integer. If number is already rounded, it simply returns the number unchanged. Syntax: CEIL(number)  Number: The value used to find the smallest integer value. For Example: SELECT CEIL(32.65) "Floor" FROM DUAL; SELECT CEIL(32.1) "Floor" FROM DUAL; SELECT CEIL(-32.65) "Floor" FROM DUAL; SELECT CEIL(-32) "Floor" FROM DUAL;
  • 79. Number Functions: EXTRACT The Oracle/PLSQL EXTRACT function extracts a value from a date or interval value. Syntax: EXTRACT ({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND }| { TIMEZONE_HOUR | TIMEZONE_MINUTE }| { TIMEZONE_REGION | TIMEZONE_ABBR } FROM { date_value | interval_value } ) For Example: SELECT EXTRACT(YEAR FROM DATE '2010-01-12') FROM DUAL; SELECT EXTRACT(DAY FROM DATE '2003-08-22') FROM DUAL; SELECT EXTRACT(MONTH FROM SYSDATE-40) FROM DUAL;
  • 80. Number Functions: GREATEST The Oracle/PLSQL GREATEST function returns the greatest value in a list of expressions Syntax: GREATEST( expr1 [, expr2, ... expr_n]  Expr1: The first expression to be evaluated whether it is the greatest.  Expr2,…., expr_n: Optional, additional expressions that are to be evaluated.  Note: If the datatypes of the expressions are different, all expressions will be converted to whatever datatype expr1 is. For Example: SELECT GREATEST(7, 19, 85, 2) FROM DUAL; SELECT GREATEST('blue', 'blew', 'blow') FROM DUAL; SELECT GREATEST('dallas', 'dulles', 'dullus') FROM DUAL; SELECT GREATEST('Dallas', 19, 'Dalie', 2) FROM DUAL; Note: Do not confuse GREATEST with MAX. GREATEST returns the greatest of the list of expressions, while MAXreturns the maximum value of expressions and is normally used as an aggregate or analytic function.
  • 81. Number Functions: LEAST The Oracle/PLSQL LEAST function returns the smallest value in a list of expressions. Syntax: LEAST( expr1 [, expr2, ... expr_n] )  Expr1: The first expression to evaluate whether it is the smallest.  expr2, ... expr_n: Optional, additional expressions that are to be evaluated. For Example: SELECT LEAST(2, 5, 12, 3) FROM DUAL; SELECT LEAST('apples', 'oranges', 'bananas') FROM DUAL; SELECT LEAST('apples', 'applis', 'applas', null) FROM DUAL; Note: Do not confuse LEAST with MAX. LEAST returns the least of the list of expressions, while MAX returns the maximum value of expressions and is normally used as an aggregate or analytic function.
  • 82. Functions: Group Functions 1. SUM( [ALL | DISTINCT] expression ) 2. AVG( [ALL | DISTINCT] expression ) 3. COUNT( [ALL | DISTINCT] expression ) 4. COUNT(*) 5. MAX(expression) 6. MIN(expression)
  • 83. Functions Aggregate and Scalar Functions Another way of categorizing functions is in terms of whether they operate on values from just one row at a time, on values from a collection, or on a set of rows. Aggregate functions operate against a collection of values and return a single summarizing value. Scalar functions return a single value based on scalar input arguments. Some scalar functions, such as CURRENT_TIME, do not require any arguments Aggregate functions return a single value based upon a set of other values. If used among other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY or HAVING clause. No GROUP BY or HAVING clause is required if the aggregate function is the only value retrieved by the SELECT statement. The general syntax of an aggregate function is: aggregate_function_name ( [ALL | DISTINCT] expression) The aggregate function name may be AVG, COUNT, MAX, MIN, or SUM.
  • 84. Functions AVG and SUM The AVG function computes the average of values in a column or an expression. SUM computes the sum. Both functions work with numeric values and ignore NULL values. Use the DISTINCT keyword to compute the average or sum of all distinct values of a column or expression. SQL Standard Syntax: AVG ([ALL | DISTINCT] expression) SUM ([ALL | DISTINCT] expression)
  • 85. Functions AVG and SUM The AVG function computes the average of values in a column or an expression. SUM computes the sum. Both functions work with numeric values and ignore NULL values. Use the DISTINCT keyword to compute the average or sum of all distinct values of a column or expression. SQL Standard Syntax: AVG ([ALL | DISTINCT] expression) SUM ([ALL | DISTINCT] expression)
  • 86. Functions COUNT The COUNT function is used to compute the number of rows in an expression. SQL Syntax: COUNT(*) COUNT( [ALL|DISTINCT] expression) COUNT(*) Counts all the rows in the target table whether or not they include NULLs. COUNT( [ALL|DISTINCT] expression) Computes the number of rows with non-NULL values in a specific column or expression. When the keyword DISTINCT is used, duplicate values will be ignored and a count of the distinct values is returned. ALL returns the number of non-NULL values in the expression and is implicit when DISTINCT is not used
  • 87. Functions COUNT Example: This query counts all rows in a table: SELECT COUNT(*) FROM publishers; The following query finds the number of different countries where publishers are located: SELECT COUNT(DISTINCT country) "Count of Countries" FROM publishers;
  • 88. Functions MIN and MAX MIN (expression) and MAX (expression) find the minimum and maximum value of expression (string, datetime, or numeric) in a set of rows. DISTINCT or ALL may be used with these functions, but do not affect the result. SQL Syntax: MIN( [ALL | DISTINCT]expression) MAX( [ALL | DISTINCT]expression) Examples: The following query finds the best and worst sales for any title on record: SELECT MIN(ytd_sales), MAX(ytd_sales) FROM titles;
  • 89.  TO_NUMBER  TO_CHAR – Date/ Number Conversion Function  TO_DATE – Date conversion Function CONVERSION FUNCTION
  • 90. The TO_NUMBER function converts a character value to a numeric datatype. If the string being converted contains nonnumeric characters, the function returns an error. Syntax: TO_NUMBER (string1, [format], [nls_parameter])  String1: The string that will be converted to a number.  Format: Optional, this is the format that will be used to convert string1 to a number.  nls_parameter: Optional, this is the nls language used to convert string1 to a number. For Example: select TO_NUMBER('9999.99') from dual; select TO_NUMBER('1210.73', '9999.99') from dual; CONVERSION FUNCTION: TO_NUMBER
  • 91. TO_CHAR is a conversion function in Oracle to convert 1. number to character 2. date to character TO_CHAR (number conversion): Converts a value of a number datatype to a character datatype, using the optional format string. TO_CHAR() accepts a number(n) and a numeric format (fmt) in which the number has to appear. If (fmt) is omitted, n is converted to a char value exactly long enough to hold all significant digit. Syntax: TO_CHAR (n [,fmt]) Example: SELECT TO_CHAR (17145, ‘$09021’) “char” FROM dual; TO_CHAR (date conversion): Converts a value of a DATE datatype to CHAR datatype. TO_CHAR() accepts a date, as well as the format (fmt) in which the date has to appear. Fmt must be a date format. If fmt is omitted, the DATE is converted to a character value using the default date format, i.e., DD-MON-YY. Syntax: TO_CHAR (date [,fmt]) Example: SELECT TO_CHAR(dely_date, ‘month dd, yyyy’) new_date FROM SALES_ORDER WHERE order_no =‘O00001’; CONVERSION FUNCTION: TO_CHAR
  • 92. For Example: TO_CHAR number function select to_char(‘012’) as str from dual; select to_char('012','$9999') as str from dual; select to_char('012','$000009999') as str from dual; select to_char('012','$0009999.99') as str from dual; select to_char('012.48','$9999.999') as str from dual; For Example: TO_CHAR (DATE FUNCTION) select sysdate,to_char(sysdate,’mm/dd/yyyy’) from dual; select sysdate,to_char(sysdate,’YYTH MONTH YEAR’) as fmt_date from dual; select to_char(sysdate,’mm/dd/yyyy’) as today from dual; select to_char(sysdate,’mm/dd/yyyy hh:mi:ss AM’) as today from dual; select to_char(sysdate,’YEAR’) as today from dual; select to_char(sysdate,’mon ddth yyyy’) as today from dual; CONVERSION FUNCTION: TO_CHAR
  • 93. TO_CHAR(,[fmt]) - format may be the following: MM Numeric month (e.g., 07) MON Abbreviated month name (e.g., JUL) MONTH Full month name (e.g., JULY) DD Day of month (e.g., 24) DY Abbreviated name of day (e.g., FRI) YYYY 4-digit year (e.g., 1998) YY Last 2 digits of the year (e.g., 98) RR Like YY, but the two digits are ``rounded'' to a year in the range 1950 to 2049. Thus, 06 is considered 2006 instead of 1906 AM (or PM) Meridian indicator HH Hour of day (1-12) HH24 Hour of day (0-23) MI Minute (0-59) SS Second (0-59)
  • 94. TO_DATE: The Oracle TO_DATE function will convert either a character string or an expression into a date value. Syntax: TO_DATE( string1 [, format_mask] [, nls_language] )  String1: The string that will be converted to a date.  format_mask: Optional, this is the format that will be used to convert string1 to a date.  nls_language: Optional, this is the nls language used to convert string1 to a date. For Example:  select to_date('16-Feb-09', 'DD-Mon-YY') as str from dual;  select to_date('021609', 'MMDDYY') as str from dual;  select to_date('Feb/16/09', 'Mon/DD/YY HH:MI:SS') "change" from dual;  select to_date('February.16.2009', 'Month.DD.YYYY HH:MI:SS') "change" from dual; CONVERSION FUNCTION: TO_DATE
  • 95. Functions SYSDATE SYSDATE is a date function that returns the current date and time. You can use SYSDATE just as you would use any other column name. For example, you can display the current date by selecting SYSDATE from a table. It is customary to select SYSDATE from a dummy table called DUAL. Example Display the current date using the DUAL table: SQL> SELECT SYSDATE FROM DUAL; SELECT to_char (SYSDATE, 'MM-DD-YYYY HH:MI:SS') FROM dual;
  • 96. Functions Date Functions Date functions operate on Oracle dates. All date functions return a value of DATE datatype except MONTHS_BETWEEN, which returns a numeric value . •MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and 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. The non-integer part of the result represents a portion of the month. •ADD_MONTHS(date, n):Adds n number of calendar months to date. The value of n must be an integer and can be negative. •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']): Returns date rounded to the unit specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest day. •TRUNC(date[,'fmt']): Returns date with the time portion of the day truncated to the unit specified by the format model fmt. If the format model fmt is omitted, date is truncated to the nearest day.
  • 97. Functions MONTHS_BETWEEN: For Example, SELECT MONTHS_BETWEEN(SYSDATE,DOJ) FROM employee; ADD_MONTHS: For Example, SELECT SYSDATE, ADD_MONTHS(SYSDATE,1), ADD_MONTHS(SYSDATE,2), ADD_MONTHS(SYSDATE,3), ADD_MONTHS(SYSDATE,4), ADD_MONTHS(SYSDATE,5), ADD_MONTHS(SYSDATE,6) FROM dual; LAST_DAY: For Example, SELECT SYSDATE, LAST_DAY(SYSDATE) EOM, LAST_DAY(SYSDATE)+1 FOM FROM dual; NEXT_DAY: For Example, SELECT SYSDATE, NEXT_DAY(SYSDATE,'MONDAY') "Next Mon", NEXT_DAY(SYSDATE,'FRIDAY') "Next Fri", NEXT_DAY(LAST_DAY(SYSDATE)+1,'TUESDAY') "First Tue“ FROM dual;
  • 98. Functions Arithmetic with Dates Since the database stores dates as numbers, you can perform calculations using arithmetic operators such as addition and subtraction. You can add and subtract number constants as well as dates. You can perform the following operations:
  • 99. Grouping data from tables GROUP BY clause: group the rows based on distinct values that exist for specified columns. GROUP BY clause creates a data set, containing several sets of records grouped together based on condition. Syntax: SELECT <columnname1>, <columnname2>, <columnnamen>, AGGREGATE_FUNCTION (expression) FROM <tablename> WHERE <condition> GROUP BY <columnname1>, <columnname2>, <columnnamen>;
  • 100. Grouping data from tables NAME Banana Orange Orange Apple Banana Apple Apple Apple NAME Apple Banana Orange I want result as: SELECT NAME FROM FRUIT ORDER BY NAME GROUP BY NAME SELECT DISTINCT NAME FROM FRUIT ORDER BY NAME;
  • 101. Having clause Having clause: used in conjunction with the GROUP BY clause. HAVING imposes a condition on the GROUP BY clause, which further filters created by the GROUP BY clause. For example: Find out the customers having more than one account in the bank. SELECT cust_no, COUNT (acct_no) “no. of accounts held” FROM acct_master WHERE where acct_no LIKE ‘CA%’ OR acct_no LIKE ‘SB%’ GROUP BY cust_no HAVING COUNT(acct_no)>1;
  • 102. Having clause Having clause: used in conjunction with the GROUP BY clause. HAVING imposes a condition on the GROUP BY clause, which further filters created by the GROUP BY clause. For example: Find out the customers having more than one account in the bank. SELECT cust_no, COUNT (acct_no) “no. of accounts held” FROM acct_master WHERE where acct_no LIKE ‘CA%’ OR acct_no LIKE ‘SB%’ GROUP BY cust_no HAVING COUNT(acct_no)>1;
  • 103. Sub-queries A sub-query is a form of an SQL statement that appears inside another SQL statement. It is also termed as nested query. The statement containing a Sub-query is called parent statement. The parent statement uses the rows (i.e., the result set) returned by the sub-query. For example: Find the product number and description of non-moving products, i.e., products not being sold. SELECT product_no, description FROM product_master WHERE product_no NOT IN (SELECT product_no FROM sales_order_details; List the names of clients who have placed orders worth Rs. 10000 or more. SELECT name FROM client_master WHERE client_no IN ( SELECT client_no FROM sales_order where (( ty_ordered*product_Rate) > 10000));
  • 104. Correlated sub-queries A sub-query becomes correlated when the subquery references a column from a table in the parent query. A correlated subquery is evaluated once for each row processed by the parent statement, which can be any of SELECT, DELETE, UPDATE. For example: Find out the products, which have been sold to Ivan Bayross. SELECT sales_order_details.product_no, product_master.description FROM sales_order_details, sales_order, product_master, client_master WHERE product_master.product_no=sales_order_details.product_no AND sales_order.order_no=sales_order_details.order_no AND client_master.client_no=sales_order.client_no AND client_master.name=‘Ivan Bayross’;
  • 105. Data constraints Oracle allows programmers to define constraints at: 1. Column level 2. Table level 1. If data constraints are defined along with the column definition when creating or altering a table structure, they are column level constraints 2. If data constraints are defined after defining all the table columns when creating or altering a table structure, it as table level constraint Note: Both the CREATE TABLE and ALTER TABLE SQL verbs can be used to write SQL sentences that attach constraints (i.e., business or system rules) to a table column
  • 106. Data constraints: types 1. I/O constraints 2. UNIQUE key constraint 3. NULL value concept 4. CHECK constraint 5. DEFAULT value concept I/O constraints includes: 1. PRIMARY KEY constraint 2. FOREIGN KEY constraint
  • 107. PRIMARY KEY Primary key is one or more column(s) in a table used to uniquely identify each row in a table. None of the fields that are part of primary key can contain a null value. A table can have only one primary key A primary key column in a table has following properties: 1. It defines the column, as mandatory column (i.e., the column cannot be left blank), as NOT NULL attribute is active 2. The data held across the column must be UNIQUE. PRIMARY KEY = UNIQUE + NOT NULL
  • 108. PRIMARY KEY: features 1. Primary key is a column or a set of columns that uniquely identifies a row. Its main purpose is the RECORD UNIQUENESS. 2. Primary key will not allow duplicate values 3. Primary key will also not allow null values 4. Primary key is not compulsory but it is recommended 5. Primary key helps to identify one record from another record and also helps in relating tables with one another 6. Primary key cannot be LONG or LONG RAW data type 7. Only one primary key is allowed per table 8. Unique index is created automatically if there is a primary key 9. One table can combine upto 16 columns in a composite primary key
  • 109. PRIMARY KEY Primary key constraint at column level Primary key constraint at table level <column_name> <datatype(size)> PRIMARY KEY PRIMARY KEY(<column_name>, <column_name>) For example, CLIENT TABLE client_master(client_no varchar2(6) PRIMARY KEY, name varchar2(30), address varchar2(30), city varchar2(15), state varchar2(15), baldue number(10,2)); For example, CREATE TABLE sales_order_master(product_no varchar2(6), order_no varchar2(6), qtyordered number(8), qtydisp number(8), PRIMARY KEY(order_no, product_no));
  • 110. FOREIGN KEY  Foreign key represents relationships between tables. A foreign key is a column (or a group of columns) whose values are derived from the primary key or unique key of some other table.  The table in which the foreign key is defined is called a foreign table or detail table. The table that defines the primary or unique key and is referenced by the foreign key is called the primary table or master table.  The master table can be referenced in the foreign key definition by using the REFERENCES adverb. If the name of the column is not specified, by default, Oracle references the primary key in the master table.
  • 111. FOREIGN KEY: features 1. Foreign key is a column(s) that reference a column(s) of a table and it can be the same table. 2. Parent that is being referenced has to be unique or primary key. 3. Child may have duplicates and nulls but unless it is specified. 4. Foreign key constraint can be specified on child but not on parent. 5. Parent record can be delete provided no child record exist. 6. Master table cannot be updated if child record exist. Note: Relationship ensures:  Record cannot be inserted into a detail table if corresponding records in the master table do not exist  Record of master able cannot be deleted if corresponding record in detail table actually exist.
  • 112. FOREIGN KEY foreign key constraint at column level Foreign key constraint at table level <column_name> <datatype(size)> REFERENCES <tablename(column_name)> FOREIGN KEY (<column_name> <column_name>) REFERENCES <tablename(column_name, column_name)> For example, CLIENT TABLE sales_order(order_no varchar2(6) PRIMARY KEY, order_date date, client_no varchar2(6) REFERENCES client_master)); For example, CLIENT TABLE sales_order(order_no varchar2(6) PRIMARY KEY, order_date date, FOREIGN KEY(order_no) REFERENCES client_master);
  • 113. FOREIGN KEY FOREIGN KEY constraint defined with ON DELETE CASCADE:  A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table with automatically be deleted. This is called a cascade delete in Oracle. FOREIGN KEY constraint defined with ON DELETE SET NULL:  A FOREIGN KEY with a SET NULL ON DELETE means that if a record in the parent table is deleted then the corresponding records in the child table will have the foreign key fields set to NULL. The records in the child table will not be deleted.  A FOREIGN KEY with a SET NULL ON DELETE can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
  • 114. FOREIGN KEY: example CREATE TABLE product_master (productno varchar2(6) not null, description varchar2(30) not null, CONSTRAINT fk_order_no FOREIGN KEY (order_no REFERENCES order_master(orderno) ON DELETE CASCADE); CREATE TABLE product_master (productno varchar2(6) not null, description varchar2(30) not null, CONSTRAINT fk_order_no FOREIGN KEY (order_no REFERENCES order_master(orderno) ON DELETE SET NULL);
  • 115. CONSTRAINTS: user-defined Adding user-defined names to CONSTRAINTS: For example, Explanation: User named constraint simplifies the task of dropping constraints. A constraint can be given a user-defined name by preceding the constraint definitions with the reserved word CONSTRAINT and a user-defined name CONSTRAINT <constraint_name> <constraint_definition> CREATE TABLE client_master ( clientno varchar2(6) CONSTRAINT c_key PRIMARY KEY, cname varchar2(20) NOT NULL);
  • 116. UNIQUE CONCEPT UNIQUE column constraint permits multiple entries of NULL into the column. These NULL values are clubbed at the top of the column in the order in which they were entered into the table. Key Points: 1. Unique key will not allow duplicate values. 2. Unique index is created automatically. 3. A table can have more than one UNIQUE KEY which is not possible in PRIMARY KEY. 4. Unique key can combine 16 columns in a composite unique key. 5. Unique key cannot be LONG or LONG RAW data type.
  • 117. UNIQUE CONCEPT Syntax: At column level At table level Create table client_master (clientno varchar2(6) PRIMARY KEY, name varchar2(20) UNIQUE, age number(2)); Create table client_master (clientno varchar2(6) PRIMARY KEY, name varchar2(20), age number(2), UNIQUE(name, age));
  • 118. NULL CONCEPT NULL implies that the value is unknown and not that the value does not exist or is absent. NOT NULL constraints are in-line constraints that indicate that a column can not contain NULL values. A NULL value can be inserted into columns of any data type. Principles: 1. Setting NULL value is appropriate when actual values is unknown or when value would not be meaningful. 2. A NULL value is not equivalent to a value zero if the data type is number and is not equivalent to spaces if the data type is character. 3. A NULL value can be inserted into columns of any data type. 4. If the column has NULL value, ORACLE ignores any UNIQUE, FOREIGN KEY, CHECK constraints that may be attached to the column. Note: Now ORACLE has changed its rule to an empty string is treated as NULL value.
  • 119. NULL CONCEPT Syntax: Example: CREATE TABLE salesman_master (salesman_no varchar2(6) PRIMARY KEY, Salesman_name varchar2(20) NOT NULL); Note: NOT NULL constraint can not be applied at column level <column_name> <datatype(size) NOT NULL
  • 120. CHECK constraint  Business rule validations can be applied to a table column by using CHECK constraint. CHECK constraints must be specified as a logical expression that evaluates either to TRUE or FALSE.  A CHECK constraint takes substantially longer to execute as compared to NOT NULL, PRIMARY KEY, FOREIGN KEY, UNIQUE. Thus, CHECK constraints must be avoided if the constraint can be defined using NOT NULL, PRIMARY KEY or FOREIGN KEY constraint.
  • 121. CHECK constraint At column level At table level <column_name> <datatype(size) CHECK (<logical_expression>) CHECK (<logical_expression>) For example, CREATE TABLE client_master (client_no varchar2(6) CHECK client_no like C%); For example, CREATE TABLE client_master (……………, ……………, …………, CHECK (client_no LIKE C%));
  • 122. PL / SQL Procedural Language / Structured Query Language
  • 123. PL/ SQL  An extension to non-procedural language SQL.  It combines the data-manipulation power of SQL with data-processing power of the procedural language.  PL/SQL provides high-level language features such as block structure, conditional statements, loop statements, variable types, structured data and customized error handling.  The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other.
  • 125. PL/ SQL: structure DECLARE /* Declarative section: variables, types, and local subprograms. */ BEGIN /* Executable section: procedural and SQL-DML statements go here. */ /* This section of the block is required. */ EXCEPTION /* Exception handling section: error handling statements go here. */ END;
  • 126. PL/ SQL: structure ….  SET SERVEROUTPUT ON is the SQL*Plus command1 to activate the console output. You only need to issue this command once in a SQL*Plus session.  the keywords BEGIN...END define a scope and are equivalent to the curly braces in Java {...}  a semi-column character (;) marks the end of a statement  the put_line function (in the built-in package dbms_output) displays a string in the SQL*Plus console.  The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and several other data manipulation statements plus some transaction control.  Data definition statements like CREATE, ALTER, or DROP are not allowed.  The executable section also contains constructs such as assignments, branches, loops, procedure calls, and triggers.  PL/SQL is not case sensitive.
  • 127. PL/ SQL: variable declaration SYNTAX: Here, VARIABLE_NAME is the name of the variable and VARIABLE_DATATYPE is any valid SQL data type such as DATE, NUMBER, or PL/ SQL data type such as BOOLEAN or COMPOSITE data type. VARIABLE_NAME VARIABLE_DATATYPE
  • 128. PL/ SQL: variable declaration BOOLEAN data type: 1. Used to store the logical values TRUE, FALSE, NULL 2. They do not take parameters 3. We cannot insert a BOOLEAN data type into a database column COMPOSITE data type: 1. %TYPE 2. %ROWTYPE %TYPE: provides data type information of a column or variable. Example: X emp.sal %TYPE – Here, %TYPE will declare a variable X having the same data type as that column of emp table. – It is not necessary to know the data type of sal column. – If we change the data type of sal column in the database then data type of X will change accordingly.
  • 129. PL/ SQL: variable declaration %ROWTYPE data type: PL/ SQL record is used to store information that is related and consists of different data types. Example: EMP_RECORD is a variable which holds the value of one row of emp table, i.e., Here, the fields of EMP_RECORD are having same name as columns of emp table and can be called by using . (dot) notation EMP_RECORD EMP %ROWTYPE
  • 130. PL/ SQL DISPLAYING USER MESSAGE ON SCREEN To display the message on user screen, the SERVER OUTPUT flag should be ON as: Now, we can write the PL/ SQL code block to display the message to the user. SET SERVEROUTPUT ON DBMS_OUTPUT.PUT_LINE (‘welcome’)
  • 131. PL/ SQL: control constructs CONDITIONAL STATEMENTS 1. IF …. ENDIF 2. IF …. ELSE …. ENDIF 3. IF …. ELSE …. ENDIF …. ELSE …. ENDIF ITERATIVE STATEMENTS 1. WHILE …. LOOP …. END LOOP 2. FOR …. LOOP …. END LOOP 3. LOOP …. EXIT …. END LOOP UNCODITIONAL BRANCHING 1. GOTO
  • 132. PL/ SQL: exceptions  Any well-written program must have the ability to handle errors intelligently and recover from them, if possible.  ORACLE has given such facility, called EXCEPTIONS to handle run time errors or abnormal conditions according to user’s choice.  EXCEPTIONS are functions used to generate error messages and replace default error messages.  We can handle both unexpected and expected errors during execution through EXCEPTIONS.  Designed for run-time, not for compile time  Types of EXCEPTIONS: 1. Pre-defined exception 2. User-defined exception 3. Pragma exception
  • 133. PL/ SQL: pre-defined exception Exception Name Reason Error Number CURSOR_ALREADY_OPEN When you open a cursor that is already open. ORA-06511 INVALID_CURSOR When you perform an invalid operation on a cursor like closing a cursor, fetch data from a cursor that is not opened. ORA-01001 NO_DATA_FOUND When a SELECT...INTO clause does not return any row from a table. ORA-01403 TOO_MANY_ROWS When you SELECT or fetch more than one row into a record or variable. ORA-01422 ZERO_DIVIDE When you attempt to divide a number by zero. ORA-01476
  • 134. PL/ SQL: pre-defined exception For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below. BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END;
  • 135. PL/ SQL: RAISE_APPLICATION_ERROR  RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range is in between -20000 and -20999.  Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).  RAISE_APPLICATION_ERROR raises an exception but does not handle it.  RAISE_APPLICATION_ERROR is used for the following reasons, a) to create a unique id for an user-defined exception. b) to make the user-defined exception look like an Oracle error. RAISE_APPLICATION_ERROR (error_number, error_message);
  • 136. PL/ SQL: RAISE_APPLICATION_ERROR SYNTAX Here, • The Error number must be between -20000 and -20999 • The Error_message is the message you want to display when the error occurs. Steps to be folowed to use RAISE_APPLICATION_ERROR procedure: 1. Declare a user-defined exception in the declaration section. 2. Raise the user-defined exception based on a specific business rule in the execution section. 3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR RAISE_APPLICATION_ERROR (error_number, error_message);
  • 137. PL/ SQL: user-defined Exceptions  Apart from system exceptions we can explicitly define exceptions based on business rules. These are known as user-defined exceptions.  Steps to be followed to use user-defined exceptions: • They should be explicitly declared in the declaration section. • They should be explicitly raised in the Execution Section. • They should be handled by referencing the user-defined exception name in the exception section.  User-defined exceptions are declared in DECLARE section of a PL/ SQL block. Just like variables, exceptions have a type EXCEPTION. Example:  User-defined exceptions are raised by giving the RAISE statement.  The built-in exception can also be raised by using RAISE statement. invalid_day EXCEPTION
  • 138. PL/ SQL: user-defined Exceptions Syntax: Example: DECLARE invalid_day EXCEPTION BEGIN IF RTRIM (to_char(sysdate, ‘day’), ‘ ‘) = ‘Thursday’ THEN RAISE invalid_day ELSE dbms_output.put_line(“you are allowed to do data entry”) END If; EXCEPTION WHEN invalid_day THEN RAISE_APPLICATION_ERROR(-20001, ‘not a valid day for data entry’) END; IF <condition> THEN RAISE <exception_name>; ELSE …. END IF;
  • 139. PL/ SQL: when others trigger WHEN OTHERS handle all errors not already handled in the block. Example: WHEN no_data_found THEN insert into error_table values(‘no employees joined in 1992’); WHEN others THEN insert into error_table values(‘some unknown error’); END; In the case, WHEN OTHERS trigger for all errors, we may wish to evaluate the associated error code and error message.
  • 140. PL/ SQL: when others trigger PL/ SQL provides two functions for this purpose: 1. SQLCODE: returns numeric data as negative number. 2. SQLERRM: it returns the message related with the error, may be assigned to VARCHAR2 type of variable and message length of 512 characters. EXAMPLE: WHEN OTHERS then error_code:= SQLCODE; error_message:= SQLERRM; insert into error_table values(error_code || error_message);
  • 141. PL/ SQL: cursors  Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example, number of rows processed, etc.  A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.  There are two types of cursors: 1. Implicit cursors 2. Explicit cursors
  • 142. PL/ SQL: implicit cursors  Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.  Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
  • 143. PL/ SQL: explicit cursors  Explicit cursors are programmer defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.  SYNTAX:  Working with an explicit cursor involves four steps: 1. Declaring the cursor for initializing in the memory 2. Opening the cursor for allocating memory 3. Fetching the cursor for retrieving data 4. Closing the cursor to release allocated memory CURSOR cursor_name IS select_statement;
  • 144. PL/ SQL: explicit cursors DECLARING THE CURSOR  Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example: OPENING THE CURSOR  Opening the cursor allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open above-defined cursor as follows: CURSOR c_customers IS SELECT id, name, address FROM customers; OPEN c_customers;
  • 145. PL/ SQL: explicit cursors FETCHING THE CURSOR • Fetching the cursor involves accessing one row at a time. For example we will fetch rows from the above-opened cursor as follows: CLOSING THE CURSOR • Closing the cursor means releasing the allocated memory. For example, we will close above-opened cursor as follows: FETCH c_customers INTO c_id, c_name, c_addr; CLOSE c_customers;
  • 146. PL/ SQL: triggers  Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events: 1. A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). 2. A database definition (DDL) statement (CREATE, ALTER, or DROP). 3. A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Note: Triggers could be defined on the table, view, schema, or database with which the event is associated.
  • 147. PL/ SQL: triggers ADVANTAGES: Triggers can be written for the following purposes: 1. Generating some derived column values automatically 2. Enforcing referential integrity 3. Event logging and storing information on table access 4. Auditing 5. Synchronous replication of tables 6. Imposing security authorizations 7. Preventing invalid transactions
  • 148. PL/ SQL: triggers CREATING TRIGGERS: SYNTAX – CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements BEGIN Executable-statements EXCEPTION Exception-handling-statements END;
  • 149. PL/ SQL: triggers Where, 1. CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with thetrigger_name. 2. {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF clause is used for creating trigger on a view. 3. {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation. 4. [OF col_name]: This specifies the column name that would be updated. 5. [ON table_name]: This specifies the name of the table associated with the trigger. 6. [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML statements, like INSERT, UPDATE, and DELETE. 7. [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. 8. WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid only for row level triggers.