Documente Academic
Documente Profesional
Documente Cultură
PROGRAMS LIST:
1) Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.
2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.
Example:- Select the roll number and name of the student who secured fourth rank in the class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and
Creation and dropping of Views.
4) Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation,
lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char,
to_date)
5) i)Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found) ii)Insert data into student table
and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
6) Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.
7) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION ERROR.
9) Program development using creation of stored functions, invoke functions in SQL Statements and write
complex functions.
1
10) Program development using creation of package specification, package bodies, private objects, package
variables and cursors and calling stored packages.
11) Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.
12) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
2
INDEX FOR LAB MANUL
3
S.NO PROGRAMS LIST PAGE NO
4
11 Program development using creation of package specification, 76 - 82
package bodies, private objects, package variables and cursors and
calling stored packages.
12 Develop programs using features parameters in a CURSOR, FOR 83 - 84
UPDATE CURSOR, WHERE CURRENT of clause and CURSOR
variables.
13 Develop Programs using BEFORE and AFTER Triggers, Row and 85 - 86
Statement Triggers and
INSTEAD OF Triggers
1 Operators In Sql 87 - 98
The current version of Oracle Database is the result of over 30 years of innovative development. Highlights
in the evolution of Oracle Database include the following:
Founding of Oracle
5
In 1977, Larry Ellison, Bob Miner, and Ed Oates started the consultancy Software Development
Laboratories, which became Relational Software, Inc. (RSI). In 1983, RSI became Oracle Systems
Corporation and then later Oracle Corporation.
In 1979, RSI introduced Oracle V2 (Version 2) as the first commercially available SQL-based
RDBMS, a landmark event in the history of relational databases.
Oracle Version 3, released in 1983, was the first relational database to run on mainframes,
minicomputers, and PCs. The database was written in C, enabling the database to be ported to
multiple platforms.
Oracle8 was released in 1997 as the object-relational database, supporting many new data types.
Additionally, Oracle8 supported partitioning of large tables.
Internet computing
Oracle8i Database, released in 1999, provided native support for internet protocols and server-side
support for Java. Oracle8i was designed for internet computing, enabling the database to be deployed
in a multitier environment.
6
Oracle9i Database introduced Oracle RAC in 2001, enabling multiple instances to access a single
database simultaneously. Additionally, Oracle XML Database (Oracle XML DB) introduced the
ability to store and query XML.
Grid computing
Oracle Database 10g introduced grid computing in 2003. This release enabled organizations to
virtualize computing resources by building a grid infrastructure based on low-cost commodity
servers. A key goal was to make the database self-managing and self-tuning. Oracle Automatic
Storage Management (Oracle ASM) helped achieve this goal by virtualizing and simplifying
database storage management.
Oracle Database 11g, released in 2007, introduced a host of new features that enabled administrators
and developers to adapt quickly to changing business requirements. The key to adaptability is
simplifying the information infrastructure by consolidating information and using automation
wherever possible.
Oracle Database 12c, released in 2013, was designed for the Cloud, featuring a new Multitenant
architecture, In-Memory column store, and support for JSON documents. Oracle Database 12c helps
customers make more efficient use of their IT resources, while continuing to reduce costs and
improve service levels for users.
SQL language is divided into four types of primary language statements: DML, DDL, DCL and TCL. Using
these statements, we can define the structure of a database by creating and altering database objects, and we
7
can manipulate data in a table through updates or deletions. We also can control which user can read/write
data or manage transactions to create a single unit of work.
DDL statements are used to alter/modify a database or table structure and schema. These statements handle
the design and storage of database objects.
Command Description
Create To Create New Table Or Database
Alter For Alteration
Drop To Drop A Table
Rename To Rename A Table
Truncate To Remove All Rows (Complete Data) From A Table.
DML (Data Manipulation Language):
DML statements affect records in a table. These are basic operations we perform on data such as selecting a
few records from a table, inserting new records, deleting unnecessary records, and updating/modifying
existing records.
Command Description
Insert To Insert A New Row
Select Select Records From A Table
Update To Update Existing Row
Delete To Delete A Row
TCL : Transaction Control Language
These commands are to keep a check on other commands and their affect on the database. These commands
can annul changes made by other commands by rolling back to original state. It can also make changes
permanent.
Command Description
Commit To Permanently Save
8
Rollback To Undo Change
Savepoint To Save Temporarily
DCL : Data Control Language
Data control language provides command to grant and take back authority.
Command Description
Grant Grant Permission Of Right
Revoke Take Back Permission.
Save point
EXPERIMENT1
Use The Following Sample Data For Employee And Department Tables.
9
Sample Department data:
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
10
AIM: Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.
Creating Tables
create command is also used to create a table. We can specify names and datatypes of various columns
along. Following is the Syntax,
create table table-name
{
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4
};
create table command will tell the database system to create a new table with given table name and column
information.
Example for Creating a database called COMPANY consisting of two tables – EMP & DEPT
SQL> Create Table Dept (Deptno Number(2) Primary Key, Dname Varchar2(14), Loc Varchar2(13) );
Result : Table created
SQL> Desc dept;
Name Null? Type
----------------------------------------- -------- ----------------------------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
11
LOC VARCHAR2(13)
SQL> Create Table Emp (Empno Int Primary Key, Ename Varchar(20) , Job Varchar2(10) ,Mgr Int,
Hiredate Date, Sal Int ,Comm Int, Deptno Int, foreign key(deptno) references Dept(Deptno));
Result : Table created
Selecting a Table
Select command is used to retrieve data from a tables. It is the most used SQL query. We can retrieve
complete tables, or partial by mentioning conditions using WHERE clause.
Syntax
14
Query for Select all Records from DEPT Table
SQL> SELECT * FROM DEPT;
ALTERING TABLES
alter command is used for alteration of table structures. There are various uses of alter command,
such as,
Syntax,
15
Example for adding employee age field into temp table
Syntax,
To Drop a Column
alter command is also used to drop columns also. Following is the Syntax,
DROP COMMAND
drop command completely removes a table from database. This command will also destroy the table
structure.
Syntax,
Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can
go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints are applied only to one column,
whereas table level constraints are applied to the whole table.
NOT NULL Constraint: Ensures that a column cannot have NULL value.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column
or set of columns.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Example:
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:
17
SQL> CREATE TABLE Persons
(
P_Id int UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Result: Table Created
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
18
NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you cannot
insert a new record, or update a record without adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:
Example
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Most tables should have a primary key, and each table can have only ONE primary key.
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the
following SQL:
CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
20
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created.
The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following
SQL:
21
To drop a CHECK constraint, use the following SQL:
DEFAULT Constraint
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is
created:
To create a DEFAULT constraint on the "City" column when the table is already created, use the following
SQL:
22
A foreign key is a key used to link two tables together. This is sometimes called a referencing key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key
in the second table.
Example
Let's illustrate the foreign key with an example. Look at the following two tables:
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
23
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) );
The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use
the following SQL:
SQL> ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id);
EXPERIMENT2
Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.
24
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7698 BLAKE MANAGEr 7839 01-MAY-1981 2850 30
7782 CLARK MANAGEr 7839 09-JUN-1981 2450 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 20
7839 KING PRESIDENT 17-NOV-1981 5000 10
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-1987 1100 20
7900 JAMES CLERk 7698 03-DEC-1981 950 30
7902 FORD ANALYST 7566 03-DEC-1981 3000 20
7934 MILLER CLERK 7782 23-JAN-1982 1300 10
ALL
The ALL comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !
=, >, <, <=, >= and followed by a list or subquery.
When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of
the list and strings them together with AND operators, as shown below.
Example Queries:
To find Employees data whose employee salary should above 2000 and 3000 and 4000
Sql> SELECT empno, sal FROM emp WHERE sal > ALL (2000, 3000, 4000);
Result:
EMPNO SAL
---------- ----------
7839 5000
- Transformed to equivalent statement without ALL.
SQL> SELECT empno, sal FROM emp WHERE sal > 2000 AND sal > 3000 AND sal > 4000;
Result:
EMPNO SAL
---------- ----------
25
7839 5000
When the ALL condition is followed by a subquery, the optimizer performs a two-step transformation as
shown below.
SQL> SELECT e1.empno, e1.sal FROM emp e1 WHERE e1.sal > ALL (SELECT e2.sal
FROM emp e2 WHERE e2.deptno = 20);
Result:
EMPNO SAL
---------- ----------
7839 5000
ANY
The ANY comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !
=, >, <, <=, >= and followed by a list or subquery.
When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of
the list and strings them together with OR operators, as shown below.
Example Queries:
To find Employees data whose employee salary having more than 2000 or 3000 or 4000
SQL> SELECT empno, sal FROM emp WHERE sal > ANY (2000, 3000, 4000);
Result:
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000
-- Transformed to equivalent statement without ANY.
SQL> SELECT empno, sal FROM emp WHERE sal > 2000 OR sal > 3000 OR sal > 4000;
Result:
26
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000
When the ANY condition is followed by a subquery, the optimizer performs a single transformation as
shown below.
SQL> SELECT e1.empno, e1.sal FROM emp e1 WHERE e1.sal > ANY (SELECT e2.sal
FROM emp e2 WHERE e2.deptno = 10);
Result:
EMPNO SAL
---------- ----------
7839 5000
7902 3000
7788 3000
7566 2975
7698 2850
7782 2450
7499 1600
7844 1500
The IN Operator
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Example Queries:
27
To find employees data whose empno is 7839 or 7902
SQL> SELECT * FROM EMP WHERE EMPNO IN(7839, 7902);
Result:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
------
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
The EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery
returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
Example Queries:
Using EXISTS constraint.
SQL> SELECT ENAME FROM EMP E WHERE EXISTS(SELECT DEPTNO FROM DEPT D WHERE
D.DNAME=’SALES’ AND D.DEPTNO=E.DEPTNO);
Result :
UNION is used to combine the results of two or more Select statements. However it will eliminate duplicate
rows from its result set. In case of union, number of columns and datatype must be same in both the tables.
Example Query: To combine enames whose employee deptloc is DALLAS and whose employee DNAME
is ACCOUNTING.
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records which are
common from both SELECT statements. In case of Intersect the number of columns and datatype must be
same. MySQL does not support INTERSECT operator.
29
Example Query: To find enames whose employee deptloc having DALLAS and DNAME having
RESEARCH.
EXPERIMENT 3
AGGREGATE FUNCTIONS
The SQL aggregate functions, as their title suggests are used to retrieve minimum and maximum
values from a column, to sum values in a column, to get the average of a column values, or to
simply count a number of records according to a search condition (or lack of it). The SQL
aggregate functions are
1. COUNT()
2. SUM()
3. MAX()
4. MIN()
5. AVG()
COUNT()
The COUNT() function returns the number of rows that matches a specified criteria.
30
The most commonly used SQL aggregate function is the COUNT function.
COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:
COUNT(*) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified
column:
The MIN() function returns the smallest value of the selected column.
Syntax
SELECT MIN(column_name) FROM table_name;
The MAX() function returns the largest value of the selected column.
Syntax
SELECT MAX(column_name) FROM table_name;
31
The SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name;
Result :
Result :
COUNT(DISTINCTJOB)
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and
group the results by one or more columns.
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one
or more columns.
32
GROUP BY Syntax:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1
The HAVING clause enables you to specify conditions that filter which group results appear in the final
results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.
The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY
clause if used. The following is the syntax of the SELECT statement, including the HAVING clause:
ORDER BY syntax
Examples:
RESULT:
JOB SUM(SAL)
--------- ----------
CLERK 4150
SALESMAN 5600
PRESIDENT 5000
MANAGER 8275
ANALYST 6000
SELECT DEPTNO, MAX (SAL) FROM EMP GROUP BY DEPTNO HAVING MAX
(SAL)>(SELECT MAX(SAL) FROM EMP WHERE DEPTNO=30);
RESULT:
Views can be considered as virtual tables. Generally speaking, a table has a set of definition, and it
physically stores the data. A view also has a set of definitions, which is build on top of table(s) or other
view(s), and it does not physically store the data.
Syntax
EXPERIMENT 4
Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation, lpad,
rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char,
to_date)
SYSDATE
Returns the current system date of the database system.
Syntax:
SYSDATE
Example: To find system date
SQL> SELECT SYSDATE FROM dual;
Output:
28-May-2016
ADD_MONTHS(Date, months_to_add)
35
Returns the month by adding n months to the month of the date specified.
Syntax:
add_months( date1, n )
Example: To add 3 months to date
SQL> Select add_months('01-Aug-03', 3) from dual;
Output:
01-Nov-03
LAST_DAY(Date)
Returns the last day of the date specified.
Syntax:
LAST_DAY(date1)
Example: To find last day of date
SQL> Select last_day('2003/03/15') from dual;
Output:
Mar 31, 2003
MONTHS_BETWEEN(Date1, Date2)
Returns the number of months between date1 and date2
Syntax:
MONTHS_BETWEEN(date1,date2)
Example: To find months between 2 dates
SQL> Select months_between ('2003/01/01'),('2003/03/01' ) from dual;
Output:
2
ADDDATE(expr,days)
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for
DATE_ADD().
SQL> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY) from dual;;
Output:
+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02
36
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the
function is used in a string or numeric context.
SQL> SELECT CURDATE() from dual;;
Output:
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 1997-12-15 |
+-------------
CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function
is used in a string or numeric context. The value is expressed in the current time zone.
Output:
| CURTIME() |
+---------------------------------------------------------+
| 23:50:26 |
+---------------
DATE(expr)
37
DAYNAME(date)
DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values
correspond to the ODBC standard.
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
MINUTE(time)
MONTH(date)
MONTHNAME(date)
SECOND(time)
39
Output:
SQL> SELECT SECOND('10:05:03') from dual;;
+---------------------------------------------------------+
| SECOND('10:05:03') |
+---------------------------------------------------------+
|3
SUBDATE(expr,days)
When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for
DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD().
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.
YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.
40
TIMESTAMPADD(unit,interval,datetime_expr)
Adds the integer expression interval to the date or datetime expression datetime_expr.
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2.
NUMERIC FUNCTIONS
ABS(number)
Returns the absolute positive value of an expression.
Syntax:
ABS(expression)
Example:
SQL> SELECT ABS(-1.0), ABS(0.0) from dual;
Output:
1.0 .0
CEIL(number)
Returns the smallest integer greater than, or equal to, the specified numeric expression.
Syntax:
CEIL (expression)
Example:
SQL> SELECT CEIL ($223.45), CEIL ($-223.45) from dual;
Output:
224.00 -223.00
FLOOR(number)
Returns the largest integer less than, or equal to, the specified numeric expression.
Syntax:
41
FLOOR(expression)
Example:
SQL> SELECT FLOOR($223.45), FLOOR ($-223.45) from dual;
Output:
223.00 -224.00
MOD(number, divisor)
Returns the remainder of the division from 2 integer values.
Syntax:
MOD(dividend, divisor)
Example:
SQL> SELECT MOD(20,3) from dual;
Output:
2
POWER(number, power)
Returns the exponential value for the numeric expression.
Syntax:
POWER(number, power)
Example:
SQL> SELECT POWER(2.0, 3.0) from dual;
Output:
8.0
SIGN(number)
Returns the sign i.e. positive or negative value for the numeric expression. It returns -1 for negative
expressions, a value of 0 for zero
Syntax:
SIGN(number)
Example:
SQL> SELECT SIGN(4) from dual;
Output:
1
ROUND(number, precision)
Returns the numeric value rounded off to the next value specified.
Syntax:
ROUND(number, number of places)
Example:
SQL> SELECT ROUND(1.3456, 2) from dual;
42
SQRT(number)
Returns the square root value of the expression.
Syntax:
SQRT(number)
Example:
SQL> SELECT SQRT(4.0) from dual;
Output:
2.0
TRUNC(number, precision)
Returns a numeric value that truncate to the specific places
Syntax:
TRUNC (number,places)
Example:
SQL> SELECT TRUNC (1.3456, 2) from dual;
Output:
1.34
ACOS(X)
This function returns the arccosine of X. The value of X must range between -1 and 1 or NULL will be
returned. Consider the following example:
ASIN(X)
The ASIN() function returns the arcsine of X. The value of X must be in the range of -1 to 1 or NULL is
returned.
43
ATAN(X)
COT(X)
SIN(X)
This function returns the sine of X. Consider the following example:
SQL>SELECT SIN(90) from dual;
Output:
+---------------------------------------------------------+
| SIN(90) |
+---------------------------------------------------------+
| 0.893997
TAN(X)
This function returns the tangent of the argument X, which is expressed in radians.
44
Output:
+---------------------------------------------------------+
| TAN(45) |
+---------------------------------------------------------+
| 1.619775 |
+-----------
EXP(X)
This function returns the value of e (the base of the natural logarithm) raised to the power of X.
GREATEST(n1,n2,n3,..........)
The GREATEST() function returns the greatest value in the set of input parameters (n1, n2, n3, a nd so on).
The following example uses the GREATEST() function to return the largest number from a set of numeric
values:
LEAST(N1,N2,N3,N4,......)
The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the least-valued
item from the value list (N1, N2, N3, and so on). The following example shows the proper usage and output
for the LEAST() function:
45
LOG
LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other than 0 or 1 and n2
can be any positive value.
Example
STRING FUNCTIONS
ASCII
The SQL function ASCII converts a character in the numeric ascii value. If the string is larger as one
character then the ascii value of the first characters is return.
Syntax:
ASCII( string )
Examples:
Output:
Return Values: 65
CHR()
Syntax
: CHR( expression )
Examples:
46
SQL> SELECT CHR( 65 ) from dual;
Output:
Return Values: A
CONCAT(string1, string2)
Combines result from several different fields.
Syntax:
CONCAT(string1, string2)
Example:
SQL> SELECT CONCAT(empfirst_name, emplast_name) FROM employee
INITCAP(string)
Returns a string with each word's first character in uppercase and the rest in lowercase.
Syntax:
INITCAP(character-expression)
Example:
SQL> SELECT initcap(empfirst_name) FROM emp12;
Output:
Analyst
LENGTH(string)
Returns the length of the string. Also called as LEN()in sql server.
Syntax:
LENGTH(string)
Example:
SQL> select LENGTH (empfirst_name) from employee Where emp_id=’1’
Output:
6
LPAD(string, #,padding_char)
Used to pad the string to left to length n characters. string_pad parameter is optional. If not specified, string
will be padded spaces to the left-side of string.
Syntax:
lpad ('string', n [, 'string_pad')
47
Example:
SQL> Select lpad('tech', 7) from dual;
Output:
‘ tech’
RPAD(string, #,padding_char)
Used to pad the string to right to length n characters.string_pad parameter is optional. If not specified, string
will be padded spaces to the right-side of string.
Syntax:
rpad ('string', n [, 'string_pad')
Example:
SQL> Select rpad('tech', 7) from dual;
Output:
‘tech ’
LTRIM(string,searchString)
Used to remove all white spaces from the beginning of the string.
Syntax:
Ltrim(string)
Example:
SQL> SELECT LTRIM(' Sample ') from dual;
Output:
‘Sample ’
RTRIM(string,searchString)
Used to remove all white spaces at the end of the string.
Syntax:
rtrim(string)
Example:
SQL> SELECT RTRIM(' Sample ') from dual;
Output:
‘ Sample’
REPLACE(string,searchString,replacement)
48
Used to replace the string1, having string2 with string3.
Syntax:
REPLACE(string1, string2, string3)
Example:
SQL> SELECT REPLACE(branch, 'st', 'saint') FROM company;
UPPER(string)
Returns a string in lowercase converted to uppercase
Syntax:
UPPER(string):
Example:
SQL> SELECT UPPER(‘sAnd’) from dual;
Output: SAND
LOWER(string)
Returns a string in uppercase converted to lowercase
Syntax:
LOWER(string):
Example:
SQL> SELECT LOWER(‘sANd’) from dual;
Output:
sand
BIN(N)
Returns a string representation of the binary value of N, where N is a longlong (BIGINT) number.
SQL> SELECT BIN(12) from dual;
Output:
+---------------------------------------------------------+
49
| BIN(12) |
+---------------------------------------------------------+
| 1100
INSERT(str,pos,len,newstr)
Returns the string str, with the substring beginning at position pos and len characters long replaced by the
string newstr.
SQL> SELECT INSERT('Quadratic', 3, 4, 'What')v from dual;
Output:
| INSERT('Quadratic', 3, 4, 'What') |
+---------------------------------------------------------+
| QuWhattic
INSTR(str,substr)
Returns the position of the first occurrence of substring substr in string str.
LEFT(str,len)
Returns the leftmost len characters from the string str, or NULL if any argument is NULL.
50
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty
string. Returns NULL if str or count are NULL.
REVERSE(str)
Returns the string str with the order of the characters reversed.
RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if any argument is NULL.
STRCMP(str1, str2)
Compares two strings and returns 0 if both strings are equal, it returns -1 if the first argument is smaller than
the second according to the current sort order otherwise it returns 1.
51
SQL> SELECT STRCMP('MOHD', 'MOHD') from dual;
Output:
+---------------------------------------------------------+
| STRCMP('MOHD', 'MOHD') |
+---------------------------------------------------------+
|0
COVERSION FUNCTIONS
1. TO_CHAR
Syntax
or
Example:
SQL> SELECT TO_CHAR(1210.73, '9999.9') from dual;
Result: ' 1210.7'
SQL> SELECT TO_CHAR(1210.73, '$9,999.00') from dual;
Result: ' $1,210.73'
2. TO_NUMBER function
The TO_NUMBER function converts a character string of type CHAR or VARCHAR2 into a number.
52
TO_NUMBER(character_string, format, NLS_Params)
The following example converts the string 97.13 to a number using TO_NUMBER():
3. TO_DATE
Syntax
to_date(char[,'format'[,nls_lang])
to_date will convert either a character string or an expression into a date value.
The 'format' must be a valid DATE format: YYYY=year, MM=month, DD=Day, HH=Hour, Mi=Minute
If no format is specified Oracle will assume the default date format has been supplied in char.
Example 1
Result:
2010 01 05 00:00:00
Example 2
Result:
53
1999 01 05 00:00:00
EXPERIMENT 5
5. i)Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found)
ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
Introduction to PL/SQL
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database.
54
PL/SQL is a very secure functionality tool for manipulating, controlling, validating, and restricting
unauthorized access data from the SQL database.
Using PL/SQL we can improve application performance. It also allows to deal with errors so we can
provide user friendly error messages.
PL/SQL have a great functionality to display multiple records from the multiple tables at the same time.
PL/SQL is capable to send entire block of statements and execute it in the Oracle engine at once.
Advantages PL/SQL
Procedural language support : PL/SQL is a development tools not only for data manipulation futures but
also provide the conditional checking, looping or branching operations same as like other programming
language.
Reduces network traffic : This one is great advantages of PL/SQL. Because PL/SQL nature is entire
block of SQL statements execute into oracle engine all at once so it's main benefit
is reducing the network traffic.
Error handling : PL/SQL is dealing with error handling, It's permits the smart way handling the
errors and giving user friendly error messages, when the errors are encountered.
Declare variable : PL/SQL gives you control to declare variables and access them within the block. The
declared variables can be used at the time of query processing.
Intermediate Calculation : Calculations in PL/SQL done quickly and efficiently without using Oracle
engines. Thisimproves the transaction performance.
Portable application : Applications are written in PL/SQL are portable in any Operating system.
PL/SQL applications are independence program to run any computer.
BEGIN block and END; keyword are compulsory, and other two block DECLARE and EXCEPTION are
optional block. END; is not a block only keyword to end of PL/SQL program.
55
Figure - PL/SQL block Structure
AIM: Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found)
56
old 4: eno integer:=&eno;
new 4: eno integer:=4;
No empno found
Oracle PL/SQL transaction oriented language. Oracle transactions provide a data integrity. PL/SQL
transaction is a series of SQL data manipulation statements that are work logical unit. Transaction is an
atomic unit all changes either committed or rollback.
At the end of the transaction that makes database changes, Oracle makes all the changes permanent save
or may be undone. If your program fails in the middle of a transaction, Oracle detect the error and
rollback the transaction and restoring the database.
You can use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION command to control
the transaction.
1. COMMIT : COMMIT command to make changes permanent save to a database during the current
transaction.
2. ROLLBACK : ROLLBACK command execute at the end of current transaction and undo/undone
any changes made since the begin transaction.
3. SAVEPOINT : SAVEPOINT command save the current point with the unique name in the
processing of a transaction.
5. SET TRANSACTION : PL/SQL SET TRANSACTION command set the transaction properties
such as read-write/read only access.
AIM: Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
Begin
insert into student(sid,sname,branch,sage,marks) values (512,'gourav','cse',22,89.4);
Savepoint A;
57
insert into student(sid,sname,branch,sage,marks) values (524,'gireesh','ece',21,90.5);
Savepoint B;
insert into student(sid,sname,branch,sage,marks) values (540,'goutam','eee',20,92.6);
Savepoint C;
Rollback to B;
Commit;
End;
ROLLBACK TO SAVEPOINT A;
EXPERIMENT 6
Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.
58
PL/SQL IF THEN ELSE conditional control statements. PL/SQL Conditional Control two type: IF
THEN ELSE statement and CASE statement,
PL/SQL IF statement check condition and transfer the execution flow on that matched block depending
on a condition. IF statement execute or skip a sequence of one or more statements. PL/SQL IF statement
four different type,
1. IF THEN Statement
IF THEN Statement
IF ( condition ) THEN
statement
END IF;
IF THEN ELSE Statement
IF ( condition ) THEN
statement;
ELSE
statement;
END IF;
IF ( condition-1 ) THEN
statement-1;
statement-3;
ELSE
statement;
END IF;
Logically IF THEN ELSIF Statement and Nested IF THEN ELSE Statement both are same. Nested IF
THEN ELSE Statement write in following syntax format:
IF ( condition-1 ) THEN
statement-1;
ELSE
IF ( condition-2 ) THEN
statement-2;
ELSE
IF ( condition-3 ) THEN
statements-3;
END IF;
END IF;
END IF;
CASE Statement
PL/SQL simple CASE statement evaluates selector and attempt to match one or more WHEN condition.
Syntax
CASE selector
WHEN value-1
60
THEN statement-1;
WHEN value-2
THEN statement-2;
ELSE
statement-3;
END CASE
AIM:
Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.
Declare
vno number:=&anynumber;
vresult varchar2(20);
Begin
If vno<10 then
vno:=vno+1;
else
if vno>10 then
vno:=vno-1;
else
vno:=vno+10;
end if;
end if;
case
when vno>0 then
dbms_output.put_line(‘The given number became’||vno);
when vno<0 then
dbms_output.put_line(‘The given number became’||vno);
end case;
vresult:=case when mod(vno,2)=0
then
vno||’is an even number’
else
61
vno||’is an odd number’
end;
dbms_output.put_line(vresult);
end;
Result:
EXPERIMENT 7
Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
62
Handling, BUILT –IN Exceptions, USER defined Exceptions, RAISE- APPLICATION ERROR.
WHILE<condition> LOOP
<action>
ENDLOOP;
Program:
DECLARE
no NUMBER := 0;
BEGIN
no := no + 1;
END LOOP;
END;
Result
Sum : 10
Program:
BEGIN
63
FOR no IN 1 .. 5 LOOP
END LOOP;
END;
Result
Iteration : 1
Iteration : 2
Iteration : 3
Iteration : 4
Iteration : 5
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
64
exception3-handling-statements
........
exception3-handling-statements
END;
Example:
Let us write some simple code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters:
DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
FROM customers
WHERE id = c_id;
EXCEPTION
dbms_output.put_line('Error!');
END;
65
When the above code is executed at SQL prompt, it produces the following result:
No such customer!
The above program displays the name and address of a customer whose ID is given. Since there is no
customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND,
which is captured inEXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the
simple syntax of raising an exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
statement;
END;
You can use above syntax in raising Oracle standard exception or any user-defined exception. Next section
will give you an example on raising user-defined exception, similar way you can raise Oracle standard
exceptions as well.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined
exception must be declared and then raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
66
The syntax for declaring an exception is:
DECLARE
my-exception EXCEPTION;
Example:
The following example illustrates the concept. This program asks for a customer ID, when the user enters
an invalid ID, the exception invalid_id is raised.
DECLARE
c_name customers.name%type;
c_addr customers.address%type;
ex_invalid_id EXCEPTION;
BEGIN
RAISE ex_invalid_id;
ELSE
FROM customers
WHERE id = c_id;
END IF;
EXCEPTION
67
dbms_output.put_line('No such customer!');
dbms_output.put_line('Error!');
END;
When the above code is executed at SQL prompt, it produces the following result:
EXPERIMENT 8
Programs development using creation of procedures, passing parameters IN and OUT of PROCEDURES
68
PL/SQL Procedures
PL/SQL procedures create using CREATE PROCEDURE statement. The major difference between
PL/SQL function or procedure, function return always value where as procedure may or may not return
value.
When you create a function or procedure, you have to define IN/OUT/INOUT parameters parameters.
1. IN : IN parameter referring to the procedure or function and allow to overwritten the value of
parameter.
2. OUT : OUT parameter referring to the procedure or function and allow to overwritten the value of
parameter.
3. IN OUT : Both IN OUT parameter referring to the procedure or function to pass both IN OUT
parameter, modify/update by the function or procedure and also get returned.
IN/OUT/INOUT parameters you define in procedure argument list that get returned back to a result.
When you create the procedure default IN parameter is passed in argument list. It's means value is passed
but not returned. Explicitly you have define OUT/IN OUT parameter in argument list.
[local declarations ];
BEGIN
Program:
69
i) Program development using creation of procedures passing parameters IN of Procedure.
ii) Program development using creation of procedures passing parameters IN and OUT of Procedure:
create or replace procedure query_emp(p_id in emp.empno%type,p_name out emp.ename%type,p_sal out
emp.sal%type,p_deptno out emp.deptno%type) is
Begin
select ename,sal,deptno into p_name, p_salary , p_deptno from emp where empno=p_id;
End query_emp;
______________
Variable gn varchar2(15)
Variable gs number
Variable gc number
70
GN
--------
WARD
GS
----------
422.96
GC
----------
500
EXPERIMENT 9
71
Program development using creation of stored functions, invoke functions in SQL Statements and write
complex functions.
Aim:
Program development using creation of stored functions, invoke functions in SQL Statements and
write complex functions.
BEGIN
BEGIN
END;
Program:
72
create or replace function counttup (vdep in emp.deptno%type)
return number
is
emptot number;
Begin
select count(*) into emptot from emp where deptno=vdep;
return emptot;
End;
To execute:
variable gsal number
execute :gsal :=get_sal(7900)
73
Function:
create or replace function get_sal
( p_id in emp.empno%type)
return number
is
vsal emp.sal%type ;
Begin
select sal into vsal from emp where empno = p_id;
return vsal;
end get_sal;
To execute:
variable gsal number
execute :gsal :=get_sal(7900)
EXPERIMENT 10
Aim:
74
Program development using creation of package specification, package bodies, private objects, package
variables and cursors and calling stored packages.
Syntax for package specifications:
END package_name;
BEGIN
-----code of procedure
[EXCEPTION
END package_name;
END distance_consts;
PROCEDURE meter_to_yard
(p_meter IN NUMBER, p_yard OUT NUMBER)
IS
BEGIN
p_yard := p_meter * distance_consts.meter_2_yard;
END meter_to_yard;
PROCEDURE yard_to_meter
(p_yard IN NUMBER, p_meter OUT NUMBER)
IS
BEGIN
p_meter:= p_yard * distance_consts.yard_2_meter;
76
END yard_to_meter;
PROCEDURE kilo_to_mile
(p_kilo IN NUMBER, p_mile OUT NUMBER)
IS
BEGIN
p_mile := p_kilo * distance_consts.kilo_2_mile;
END kilo_to_mile;
PROCEDURE mile_to_kilo
(p_mile IN NUMBER, p_kilo OUT NUMBER)
IS
BEGIN
p_kilo := p_mile * distance_consts.mile_2_kilo;
END mile_to_kilo;
end distance_consts;
77
sql> variable kilo number
execute distance_consts.kilo_to_mile(2,:kilo)
print kilo
Q) Create a package specification and body called job_pack. The package contains add_job, upd_job, and
del_job procedures, as well as q_job.
PROCEDURE del_job
(p_jobid IN jobs.job_id%TYPE)
IS
BEGIN
DELETE FROM jobs
WHERE job_id = p_jobid;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR (-20203,'No job deleted.');
END IF;
END del_job;
FUNCTION q_job
(p_jobid IN jobs.job_id%TYPE)
RETURN VARCHAR2
IS
v_jobtitle jobs.job_title%TYPE;
BEGIN
SELECT job_title
INTO v_jobtitle
FROM jobs
WHERE job_id = p_jobid;
RETURN (v_jobtitle);
END q_job;
END job_pack;
79
Q) Create and invoke a package that contains private and public constructs with package specification and
package body called EMP_PACK that contains your VALID_DEPTID function as a private construct
Q) Create a package called CHK_PACK that contains the procedure CHK_HIREDATE and
CHK_DEPT_MGR. Make both constructs public .The procedure CHK_HIREDATE checks wether an
employee hire date is within the given range. The procedure CHK_DEPT_MGR procedure check whether
manager and employee work in the same department.
81
SQL> CREATE OR REPLACE PACKAGE chk_pack IS
PROCEDURE chk_hiredate
(p_date in employees.hire_date%type);
PROCEDURE chk_dept_mgr
(p_empid in employees.employee_id%type,
p_mgr in employees.manager_id%type);
END chk_pack;
/
EXPERIMENT 11
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables
83
Aim:
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.
OPEN <cursor-name>;
Program:
1. Create a Cursor to find employee with given job and deptno. Develop programs using features
parameters in a CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of clause and CURSOR
variables.
DECLARE
cursor sal_cursor is
select e.ename ,e.salary,e.deptno from employee e where e.deptno in (10,20,30) for update of salary
nowait;
Begin
savepoint a;
84
for emp_record in sal_cursor
loop
if emp_record.deptno=10 then
update employee
set salary=emp_record.salary+emp_record.salary*0.1 where current of sal_cursor;
end if;
if emp_record.deptno=20 then
update employee
set salary=emp_record.salary+emp_record.salary*0.2
where current of sal_cursor;
end if;
if emp_record.deptno=30 then
update employee
set salary=emp_record.salary+emp_record.salary*0.3 where current of sal_cursor;
end if;
end loop;
End;
EXPERIMENT 12
Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD OF
Triggers
85
Aim:
Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD OF
Triggers.
ON table_name
Program:
Trigger:
SQL> create or replace trigger tg2 after insert on emp for each row when ( new.sal > 10000)
Begin
dbms_output.put_line(' salary out of range ');
End;
86
SQL> create or replace trigger tg2 after insert on emp for each row when ( new.sal > 10000)
Begin
dbms_output.put_line(' salary out of range ');
End;
SQL> create or replace trigger k1 after insert on emp for each row when ( new.hiredate > sysdate)
Begin
dbms_output.put_line( ' Wrong date ');
End;
Trigger
SQL> create or replace trigger tg2 after insert on emp for each row when(new.salary>10000)
Begin
dbms_output.put_line(' salary out of range ');
End;
ADDITIONAL EXPERIMENTS
OPERATORS IN SQL
87
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Arithmetic Operators
Arithmetic operators can perform arithmetical operations on numeric operands involved. Arithmetic
operators are addition(+), subtraction(-), multiplication(*) and division(/). The + and - operators can also be
used in date arithmetic.
Operator Meaning
+ (Add) Addition
- (Subtract) Subtraction
* (Multiply) Multiplication
/ (Divide) Division
Returns the integer remainder of a division. For example, 17 % 5 = 2 because the remainder of
% (Modulo)
17 divided by 5 is 3.
Syntax :
The SQL plus (+) operator is used to add two or more expressions or numbers.
Example:
+--------+
88
| 10+ 20 |
+--------+
| 30 |
Example :
The SALARY column is added with the BONUS column for a total for each row of data
The SQL minus (-) operator is used to subtract one expression or number from another expression or
number.
Example:
+--------+
| 10 - 20 |
+--------+
| -10 |
Example:
multiply ( * ) operator
The SQL multiply ( * ) operator is used to multiply two or more expressions or numbers.
Example:
+---------+
89
| 10 * 20 |
+---------+
| 200 |
Example:
Divide ( / ) operator
The SQL divide ( / ) operator is used to divide one expressions or numbers by another.
Example:
SQL> select 10 / 5;
+--------+
| 10 / 5 |
+--------+
| 2.0000 |
Example:
modulo ( % ) operator
The SQL MODULO operator returns the remainder (an integer) of the division.
Example:
SQL> select 12 % 5;
+---------+
| 12 % 5 |
90
+---------+
| 2|
+---------+
Logical Operators
There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at
a time to determine whether a row can be selected for the output. When retrieving data using a SELECT
statement, you can use logical operators in the WHERE clause, which allows you to combine more than one
condition.
Logical
Description
Operators
For the row to be selected at least one of
OR
the conditions must be true.
For a row to be selected all the specified
AND
conditions must be true.
For a row to be selected the specified
NOT
condition must be false.
AND operator
Example of AND
SELECT * from Emp WHERE salary < 10000 AND age > 25
The above query will return records where salary is less than 10000 and age greater than 25.
Result:
91
eid name age salary
402 Shane 29 8000
405 Tiger 35 9000
OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference between
AND and OR is their behaviour. When we use AND to combine two or more than two conditions, records
satisfying all the condition will be in the result. But in case of OR, atleast one condition from the conditions
specified must be satisfied by any record to be in the result.
Example of OR
The above query will return records where either salary is greater than 10000 or age greater than 25.
Example:
If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results
in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned.
92
For example: If you want to find out the names of the employees who do not having age 44, the query
would be like:
Comparison Operators
Comparison operators are used in the WHERE clause to determine which records to select.
The greater than operator is used to test whether an expression (or number) is greater than another one.
Example:
The less than operator is used to test whether an expression (or number) is less than another one.
Example:
93
SQL> SELECT * FROM CUSTOMERS WHERE SALARY < 2000;
Equal to ( = ) operator
The equal to operator is used for equality test within two numbers or expressions.
Example:
The not equal to operator is used for inequality test between two numbers or expression.
Example:
The greater than equal to operator is used to test whether an expression (or number) is either greater than or
equal to another one.
Example:
The less than equal to operator is used to test whether an expression (or number) is either less than or equal
to another one.
Example:
LIKE CLAUSE
Like clause is used as condition in SQL query. Like clause compares data with an expression using wildcard
operators. It is used to find similar data from the table.
Wildcard operators
There are two wildcard operators that are used in like clause.
94
Percent sign % : represents zero, one or more than one character.
101 Adam 15
102 Alex 18
103 Abhi 17
The above query will return all records where s_name starts with character 'A'.
Result:
101 Adam 15
102 Alex 18
103 Abhi 17
Example
The above query will return all records from Student table where s_name contain 'd' as second character.
Result:
95
s_id s_Name age
101 Adam 15
Example
The above query will return all records from Student table where s_name contain 'x' as last character.
Result:
102 Alex 18
The IN Operator
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
101 Adam 15
102 Alex 18
103 Abhi 17
96
Example
101 Adam 15
102 Alex 18
BETWEEN Operator
The BETWEEN operator is used to select values within a range. The BETWEEN operator selects values
within a range. The values can be numbers, text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
101 Adam 15
102 Alex 18
103 Abhi 17
Example
Result:
97
s_id s_Name age
101 Adam 15
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
102 Alex 18
103 Abhi 17
Types of Join
98
The following are the types of JOIN that we can use in SQL.
Cross Join
Natural Join
Inner Join
Outer Join
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table which
consists of records which combines each row from the first table with each row of the second table.
SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;
99
Result:
ID NAME ID Address
1 Abhi 1 DELHI
2 adam 1 DELHI
4 Alex 1 DELHI
1 Abhi 2 MUMBAI
2 adam 2 MUMBAI
4 Alex 2 MUMBAI
1 Abhi 3 CHENNAI
2 adam 3 CHENNAI
4 Alex 3 CHENNAI
This is a simple JOIN in which the result is based on matched data as per the equality condition specified in
the query.
SELECT column-name-list
from table-name1
INNER JOIN
table-name2
WHERE table-name1.column-name = table-name2.column-name;
Result:
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
100
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same datatype present
in both the tables to be joined.
SELECT *
from table-name1
NATURAL JOIN
table-name2;
Result:
ID NAME Address
1 Abhi DELHI
2 Adam MUMBAI
In the above example, both the tables being joined have ID column(same name and same datatype), hence
the records for which value of ID matches in both the tables will be the result of Natural Join of these two
tables.
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
The left outer join returns a result table with the matched data of two tables then remaining rows of the left
table and null for the right table's column.
SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Result:
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
4 Alex null null
The right outer join returns a result table with the matched data of two tables then remaining rows of the
right table and null for the left table's columns.
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
102
Example of Right Outer Join
Result:
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
null null 3 CHENNAI
The full outer join returns a result table with the matched data of two table then remaining rows of both left
table and then the right table.
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Result:
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
null null 3 CHENNAI
4 alex null null
103
104