0% found this document useful (0 votes)
16 views

SQL.ppt

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

SQL.ppt

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

STRUCTURED QUERY

LANGUAGE
(SQL)
STRUCTURED QUERY LANGUAGE
The standard query language for relational databases is
SQL.
Structured query language is a fourth generation,
high-level, nonprocedural language unlike third
generation compiler language such as C, visual basics.
Using a non procedural language query, a user requests
data from the RDBMS.
SQL*Plus: The SQL*Plus environment is for writing
command-line SQL queries to work with database objects
such as tables, views, synonyms, and sequences.
iSQL*Plus: a Web-based environment to execute
SQL*Plus code.
PL/SQL: PL/SQL is oracle extension to SQL for creating
Procedural code to manipulate data.
SQL Worksheet: to enter, edit, and execute SQL*Plus code
or to run client side scripts.
Oracle Application server: A tool for creating a Web site
that allows users to access Oracle databases through Web
pages.
THE SQL*PLUS ENVIRONMENT
When a user logs in to connect to the Oracle server,
SQL*Plus provides the user with SQL> prompt, where the
user writes queries or commands. Features of SQL*Plus
include:
⚫ Accepts ad hoc entry of statements at the command line prompt
(i.e., SQL>)
⚫ Accepts SQL statements as files.
⚫ Provides a line editor for modifying SQL queries.
⚫ Provides environment, editor, format, execution, interaction, and
file commands
⚫ Formats query results, and display reports on screen
⚫ Controls environment settings
⚫ Accesses local and remote databases.
WRITING SQL STATEMENTS

SQL statements are not case-sensitive.


SQL statements can be on one or more lines.
Keywords cannot be abbreviated or split across lines.
Clauses are usually placed on separate lines.
Indents are used to enhance readability.
In SQL Developer, SQL statements can optionally be
terminated by a semicolon (;). Semicolons are required
if you execute multiple SQL statements.
In SQL*Plus, you are required to end each SQL
statement with a semicolon (;).
COLUMN HEADING DEFAULTS
SQL Developer:
– Default heading alignment: Center
– Default heading display: Uppercase

SQL*Plus:
– Character and Date column headings are
left-aligned
– Number column headings are right-aligned
– Default heading display: Uppercase
Oracle 10g uses the following types of SQL statements for
command-line queries to communicate with the oracle server
from any tool or application:
✔ Data retrieval: retrieves data from the database (eg:
SELECT)
✔ Data Manipulation Language (DML): inserts new rows,
changes existing rows, and removes unwanted rows (eg:
INSERT, UPDATE, DELETE)
✔ Data Definition Language (DDL): Creates, changes, and
removes a table’s structure (eg: CREATE, ALTER, DROP,
RENAME, TRUNCATE)
✔ Transaction control: Manages and changes logical
transactions. Trasactions are changes made to the data by
DML statements that are grouped together (eg: COMMIT,
SAVEPOINT, ROLLBACK)
✔ Data Control Language (DCL): gives and removes rights
to Oracle objects (eg: GRANT, REVOKE).
DATA DEFINITION
LANGUAGE (DDL)
The DDL Creates, changes, and removes a
table’s structure (eg: CREATE, ALTER, DROP,
RENAME, TRUNCATE)
NAMING RULES AND CONVENTIONS
A table is an object that can store data in oracle database.
When we create a table, following things can be specified:
1. Table Name
2. Name of each column
3. Datatype of the column
4. Size of the column
5. Constraints : like primary/composite key
6. Constraints: like foreign key with reference to primary key in
another table
7. Validations like NULL value or unique value
DATATYPES
The datatypes supported by SQL are:
varchar2, char, date, number.
Varchar2 : The VARCHAR2 type is a character type to
store variable-length alphanumeric data in a column.
✔ The size must be specified with this type. Eg: varchar2(30).
✔ The default and minimum size is 1 character, maximum size
allowed is 4000 bytes in oracle 10g.
✔ If the value smaller than the specified size is entered, only
data value is entered, rest spaces are not added.
✔ If the value larger than the specified size is entered, an error
is generated, larger values are not truncated.
Char : The char is a character data type to store
fixed-length alphanumeric data in a column.
✔ The default and minimum size is 1 character, maximum size
allowed is 2000 bytes in oracle 10g.
✔ If the value entered is smaller than the specified size, remaining
spaces are added to make its length equal to specified length.
✔ If the value is longer then the specified size, error occurs.
✔ The CHAR type is appropriate for fixed-length values.
✔ CHAR data type uses the storage more efficiently and processes
the data faster than VARCHAR2 type.
Number : The number data type is used to store negative,
integer, fixed-decimal and floating point numbers.
✔ NUMBER data type is used for any column that is going to be
employed in mathematical calculations. Eg: salary, price,
commission.
✔ When a number is used for a column, its precision and scale
can be specified. Precision is total number of digits in a
number, both on left and right of decimal point. Scale is total
digits on right of decimal point. Eg: NUMBER (4,2)
Date : The date data type is used for storing date and time
value.
✔ The range of allowed dates is between 01-JAN 4712 B.C to
31-DEC-9999.
✔ The day, month, year, hour, minute and second are stored in
DATE type column.
✔ The default date format is DD-MON-YY and DD-MON-YYYY
(for oracle 9i). The default time format is HH:MM:SS A.M.
✔ To use any other format , the use of TO_DATE function is
required.
ADVANCED DATATYPES
LONG : Variable length character data upto 2 gigabytes
CLOB : The character large object datatype, used to store
single-byte character data up to 4 gigabytes.
BLOB : The binary Large Object data type used to store
binary data up to 4- gigabytes
BFILE : The Binary File type reference to an external
binary file maintained by file system.
ROWID : For Unique row address in hexadecimal format.
CONSTRAINTS
Constraints enforce rules on the tables. There are 2 types of
constraints:
1. Integrity constraint : define both primary key and foreign
key with the table and primary key its references.
2. Value constraints : define if NULL values are disallowed,
if UNIQUE values are required, and f only certain set of
values are allowed in a column.
For user account each constraint name should be unique. A
user cannot create constraints in two different tables with
the same name.<table_name>_<column_name>_<constraint
type> CONSTRAINT ABBRE
VIATIO
N
If you do not name the constraint the
PRIMARY KEY pk
oracle server will generate a name
FOREIGN KEY fk
using SYS_Cn, where n is a unique
UNIQUE uk
number.
Check ck or cc
NOT NULL nn
DEFINING A CONSTRAINT
A constraint can be created at the time of table creation or it
can be added to the table afterwards. There are 2 levels a
constraint can be defined:
1. Column level : The column level constraints refers to a
single column and is defined along with the definition of the
column. All constraints except foreign key and composite
key can be defined at column level.
column datatype [CONSTRAINT constraint_name]
constraint _type
2. Table level : The table level constraint refers one or more
column and is defined separately from the definition of the
column. It is defined after all columns are defined. All
constraints except NOT NULL can be defined at table level
[constraint constraint_name] constraint_type(column,..)
The PRIMARY Key Constraint. The PRIMARY KEY
constraint is also known as the entity integrity constraint.
✔ It creates a primary key for the table. A table can have only
one primary key.
✔ A table can have only one primary key constraint.
✔ A column or combination of columns used as a primary key
cannot have a null value, it can only have unique values.
✔ Eg: The DEPT table used the DeptId column as a primary key.
Column level :
DeptId NUMBER(2) CONSTRAINT dept_deptId_pk PRIMARY KEY (Column
level)
Table level:
CONSTRAINT dept_ deptid_pk PRIMARY KEY (DeptId)
CONSTRAINT dependent_ emp_dep_pk PRIMARY KEY (EmployeeId,DeptId)
(composite primary key)
The FOREIGN Key Constraint. The foreign key constraint is
also known as referential integrity constraint.
✔ It uses a column or columns as foreign key, and establishes a
relationship with the primary key of the same or another table.
✔ Eg: the facutlyId in student table references the primary key
facultyId in the faculty table
✔ To establish a foreign key in a table, the other referenced table
and its primary key must already exist.
✔ The foreign key and referenced primary key need not have the
same name, but the value inside must be the same.
✔ CONSTRAINT student_faculty_fk FOREIGN KEY (FacultyId)
REFERENCES faculty (FacultyId)
✔ Before ending foreign key ON DELETE CASCADE can be
added to allow deletion of a record in parent table and deleting
of dependent rows/records in child table.
✔ Without ON DELETE CASCADE a row in the parent table
cannot be deleted if the child table references it.
The NOT NULL constraint. The NOT NULL
constraint ensures that the column has a value and the
value is not a null (unknown or blank) value.
✔ A space or a numeric zero is not a null value.
✔ There is no need to use the not null constraint for the
primary key column. A foreign key is allowed to have null
values. But sometimes it is given not null constraint.
✔ This constraint cannot be given at table level.
✔ The name column in faculty table is not a key column but
we don’t want to leave it blank so,
Name VARCHAR2(15) CONSTRAINT faculty_name_nn NOT NULL
The UNIQUE constraint. The UNIQUE constraint
requires that every value in a column or set of columns
be unique.
The UNIQUE constraint allows null values unless NOT
NULL is also applied to column.
Eg: The DeptName column in the DEPT table should
not have duplicate values.

Table level:
CONSTRAINT dept_dname_uk UNIQUE (DeptName)

Column level:
DeptName VARCHAR(12) CONSTRAINT dept_dname_uk UNIQUE
The CHECK constraint. The CHECK constraint defines
a condition that every row must satisfy.
There can be more than one CHECK constraint on a
column, and the CHECK constraint is defined at the
column as well as table level.
Column level :
DeptId NUMBER(2) CONSTRAINT dept_deptId_cc CHECK((DeptId>=10) and
(DeptId <=9))
Table level:
CONSTRAINT dept_dept_Id_cc CHECK ((DeptId>=10) and Dept<=99))
The DEFAULT value (It’s not a constraint). The
DEFAULT ensures that a particular column will always
have a value when a new row is inserted.
The default value get overwritten when the user enters
another value. The default value is used if a null value
is inserted.
Eg: City CHAR(3) DEFAULT ‘AHM’
CREATING AN ORACLE TABLE
A Data Definition Language (DDL), SQL statement,
CREATE TABLE is used for table creation.
A table is created as soon as CREATE statement is
successfully executed by the oracle server.
The general syntax of create table is:
CREATE TABLE tablename
(column1 datatype [constraint constraint_name] constraint
type,
column2 datatype [constraint constraint_name] constraint
type,
[constraint constraint_name] constraint_type(column));
When a statement is executed and there are no sysntax
errors, a “Table created” message will be displayed on the
screen.
DISPLAYING TABLE INFORMATION
When a user creates a table in his or her database,
oracle tracks them using its own Data Dictionary.
To find out all the tables created by the user:
select table_name from user_tables;

User_table is an oracle system database table, and


table_name is one of its column.
To get names of all the columns from user_table type:
select * from user_tables;
VIEWING TABLE STRUCTURE
To view the table structure created by a user describe (or
desc) command is used:
Describe employee;
Viewing constraint informaion:
Oracle’s Data Dictionary table USER_CONSTRAINTS
stores information about constraints you have entered
for each column. The table name must be in uppercase
as oracle saves all records in upper case.
Select constraint_name, constraint_type from
user_constraints;

Select constraint_name, constraint_type from


user_constraints where table_name = ‘EMPLOYEE’
ALTERING AN EXISTING TABLE
Modification that are allowed on a table structure
without any restrictions include:
✔ Adding a new column to the table.
✔ Deleting a foreign key constraint from a table
✔ Deleting a primary key constraint from a table, which also
removes any reference from other tables with CASCADE
clause.
✔ Increasing the size of column. Eg: varchar2(15) can be
changes to varchar2(20).
✔ Renaming columns.
✔ Renaming constraints.
Modification that are allowed on a table structure with
restrictions include:
✔ Adding a foreign key, if the current values are null or exist in
the referenced table’s primary key.
✔ Adding a primary key, if the values are not null and are
unique.
✔ Changing the column name and size, if there is no data in it.
Column size can be decreased if current data can be stored with
the new width.
✔ Adding a unique constraint, if the existing value is unique.
✔ Adding a check constraint, if the existing data comply with the
new constraint.
✔ Adding a default value if there is no data in the column.
ADDING NEW COLUMN TO
EXITING TABLE
The general syntax to add a column is
ALTER TABLE tablename
ADD columnname datatype;
Eg:
ALTER TABLE student
ADD remarks varchar2(40)
MODIFYING AN EXISTING
COLUMN
The general syntax to modify an existing column is
ALTER TABLE tablename
MODIFY columnname newdatatype;
Eg:
ALTER TABLE student
MODIFY remarks varchar2(50)
ADDING A CONSTRAINT
The general syntax to add a constraint is:
ALTER TABLE tablename
ADD [CONSTRAINT constraint_name] constraint_type (column)
Eg:
ALTER TABLE employee
ADD CONSTRAINT employee_positionid_fk
FOREIGN KEY (PositionId) REFERENCES Position
(PositionId)
Example for circular reference:
ALTER TABLE course
ADD CONSTRAINT course_preReq_fk FOREIGN KEY
(preReq) REFERENCES course(courseId)
DROPPING A COLUMN
When a column is dropped, it should not contain any data.
There must be at least one column left in the table.
It is not possible to recover the dropped column and its
data.
Eg:
ALTER TABLE tablename DROP COLUMN columnname;
The columns can be marked as unused by the following
command:
ALTER TABLE tablename SET UNUSED (columnname);
All unused columns can be dropped using the following
command:
ALTER TABLE tablename DROP UNUSED COLUMN;
DROPPING A CONSTRAINT
The general syntax for dropping a constraint is :
ALTER TABLE tablename
DROP PRIMARY KEY/UNIQUE(columnname) |
CONSTRAINT constraintname [CASCADE];
Eg:
ALTER TABLE major
DROP PRIMARY KEY CASCADE;

ALTER TABLE employee


DROP CONSTRIANT employee_deptId_fk;
ENABLING / DISABLING
CONSTRAINTS
A newly created constraint are enabled automatically.
A constraint verifies table data as they are added or
updated.
This process slows down the process, hence they can be
disabled is we want to add or update a large volumeof
data.
Eg:
ALTER TABLE tablename
ENABLE / DISABLE CONSTRAINT constraintname;
Primary key Constraint:
ALTER TABLE tablename ENABLE / DISABLE PRIMARY KEY;
RENAMING COMMANDS
Renaming a column :
ALTER TABLE tablename RENAME COLUMN oldname TO
newname;

Renaming a constraint:
ALTER TABLE tablename RENAME CONSTRAINT oldname TO
newname;
DROP AND TRUNCATE A TABLE
Drop a table: When a table is dropped, all the data
(records/rows) and table structure is permanently
deleted.
DROP TABLE tablename [CASCADE CONSTRAINTS];

Truncate a table: When a table is truncated, all the


data (records/rows) are removed but the table structure
remains intact. The truncate statement is not reversible.
TRUNCATE TABLE tablename;

DELETE: The DELETE statement deletes one or


more(or all) rows from a table, and it is reversible as long
as it is not committed.
DATA MANIPULATION
LANGUAGE (DML)

The DML Mainly deals with the records inside


a table (eg: SELECT, INSERT, UPDATE, and
DELETE)
ADDING A NEW RECORD
The Data Manipulation language (DML) statement
INSERT is used to insert a new record into a table.
INSERT INTO tablename (column1, column2, ….)
values (value1, value2, …..);
Eg:
INSERT INTO student (StudentID, LastNm, FirstNm, Street, City,
state, zip, StartTerm, DOB, FacultyId, MajorId, Phone)
VALUES (‘00100’, ‘Paul’, ‘Jose’, ‘Ford Avenue #4’, ‘Hill’, ‘NJ’,
‘123456’, ‘WN03’, ‘12-JUL-1988’, ‘123’, ‘101’, ‘9824242424’);
Values for varchar, char, date are written in single quotes
(‘ ‘), whereas the numeric data does not require any quotes.
To enter the char value having single quote character eg:
‘Tiku’s Pizza corner’, we would enter ‘Tiku’’s Pizza corner’.
The first quotation mark act as an escape character for the
second one.
DATE DATATYPE
To enter a date in different format, TO_DATE
function is used for converting a character value
to the date equivalent. Eg:
TO_DATE(‘11/24/1986’, ‘MM/DD/YYYY’)
TO_DATE(‘NOV 24 1986’, ‘MON DD YYYY’)
The date datatype column can store date and time both.
If only the date value is entered, the time value is set to
the midnight (12:00 A.M). If only time value is entered,
the date is set to the first of the current month
ROUNDING BY INSERT
If the insert value is 543.876 in a number(6,2) column,
the precision is 4, and the scale is 2.
The resulting value will be 543.88, rounded to two
decimal places.
The rounded value will be entered into the column.
ENTERING NULL VALUE
NULL values are allowed in non-primary key columns
that do not have a NOT NULL constraint.
There are two methods for inserting NULL value in a
column:
1. Implicit method: In this method, the column name is
omitted from the column list in the insert statement.
insert into dept (deptId, deptName) values (50,’Sales’);
2. Explicit method: In this method, the null value is used as a
value for numeric column. And an empty string (‘ ‘) is used
for date or char columns.
insert into dept (deptId, deptName, location, EmployeeId)
values (60, ‘IT’, ‘Ahmedabad’, NULL);
ENTERING DEFAULT VALUES
A default value can be inserted with the keyword
DEFAULT in place of a value for a column.
If the default value is assigned to the column during table
creation, that default value is inserted to the column.
If no default value is assigned to the column, the keyword
DEFAULT will result into a null value (only if there is no
NOT NULL constraint on that column).
UPDATING EXISTING ROWS/RECORDS
Once data are added to the table, UPDATE statement is
used to modify the data.
UPDATE tablename SET col1 = newvalue, col2 = new value
WHERE condition;
The conditions are created using column names,
relational operators, and values.

UPDATE student SET majorSubId = 500


WHERE StudId = 102;
DELETING EXISTING ROWS/RECORDS
General syntax to delete a records from a table is:
DELETE from tablename WHERE condition;

The WHERE clause adds the condition to the delete


statement. The condition is optional, but its necessary
to delete only those rows that meet the criteria.
Eg:
DELETE from dept WHERE deptId=103;

A delete statement without a where clause is like a


truncate statement.
RETRIEVING DATA FROM A TABLE
The user retrieves the data from the table using the
SELECT query.
The general syntax is:
SELECT col1,col2,…. FROM tablename;
The column can be listed in any order.
Eg: select firstNm, lastNm, studId from student;
In the output the character data is displayed with left
justification and the numeric data is displayed with
right justification.
If you want to see all columns in a table, no need to list
them all. Just used asterisk (*) in place of column list.
DISTINCT function
THE DISTINCT FUNCTION IS USED TO SUPPRESS
DUPLICATE VALUES. THE WORD DISTINCT IS USED
IMMEDIATELY AFTER WORD SELECT AND BEFORE THE
COLUMN NAME.
SELECT deptNm from
employee SELECT DISTINCT deptNm
from employee
deptNm
HR
deptNm
Finance HR
Sales Finance
Finance Sales
Finance IT
IT
IT
Sales
HR
COLUMN ALIAS
When a select query is executed, column’s name is
column heading.
Column ALIAS allow us to change the column’s heading.
The syntax is:
SELECT columnname AS alias
AS keyword is optional in the above statement.
Eg:
select preReq AS Requirement from student;
CONCATENATION
The word concatenation means it joins or links a
column or character string to another column.
The result is a column that is a string or a sequence of
characters. Two vertical bars or pipe symbols (||) is
used as the concatenation operator.
Eg:
select firstName || LastName from student;

Select firstName || ‘ ‘ || ‘was born on ‘|| dob from student;


WHERE CLAUSE
A WHERE clause is used with a SELECT, UPDATE
and DELETE query to restrict rows that are affected.
A WHERE clause uses a condition. The rows that
satisfies the condition are displayed or changed or
deleted.
Eg:
select empId from employee WHERE dept = ‘Sales’;

Update employee set address2 = ‘Chandkheda’


WHERE empId=‘112’;

Delete from employee WHERE empId = ‘107’;


WHERE CLAUSE EXAMPLES
select * from employee where location = ‘Gandhinagar’;

select firstNm, lastNm, salary, deptId from employee


where salary >= 5000;

select firstNm, lastNm, salary, deptId from employee


where deptNm = ‘Marketing’ AND salary >= 5000;

Select firstNm, lastNm, supervisor from employee


where supervisor IS NULL;

Select firstNm, lastNm, supervisor from employee


where supervisor IS NOT NULL;
SORTING DATA IN A TABLE
The rows retrieved from the table will be sorted in
either ascending or descending order depending on the
condition specified in the select sentence.
General syntax is:
select * from tablename ORDER BY colname;
Eg:
SELECT firstNm, lastNm, salary from employee
WHERE deptId = 130
ORDER BY salary DESC;

Eg:
SELECT firstNm, lastNm, salary from employee
ORDER BY deptId, salary DESC;
USING OPERATORS IN A QUERY
Select product_no, desc, sell_price * 0.05, sell_price*1.5 from
product
select rollNo, studNm, course, percentage from student
where percentage BETWEEN 65 AND 75;

select rollNo, studNm, course, percentage from student


where percentage >= 65 AND percentage <= 75;

select firstNm, lastNm, salary, deptId from employee


where ManagerId = 102 OR ManagerId = 103 OR
ManagerId = 104;

select firstNm, lastNm, salary, deptId from employee


where ManagerId IN (102, 103, 104);
NOT Operator:
select client_no, name, addr1,addr2 from client
WHERE NOT (city = ‘bombay’ or city=‘Delhi’);

select product_no, desc, sell_price from product


WHERE profit NOT BETWEEN 10 AND 15;

select firstNm, lastNm, salary, deptId from employee


where ManagerId NOT IN (102, 103, 104);
Pattern Matching :
select facNm, Phone from faculty where facNm LIKE ‘P%’;
(this will return all faculty names starting with
letter P)
NOT Operator:
select client_no, name, addr1,addr2 from client
WHERE NOT (city = ‘bombay’ or city=‘Delhi’);

select product_no, desc, sell_price from product


WHERE profit NOT BETWEEN 10 AND 15;

select firstNm, lastNm, salary, deptId from employee


where ManagerId NOT IN (102, 103, 104);
Pattern Matching :
select facNm, Phone from faculty where facNm LIKE ‘P%’;
(this will return all faculty names starting with
letter P)
ORACLE FUNCTIONS
Oracle functions serve the purpose of manipulating
data items and returning a result. In oracle’s SQL
there are two types of functions:
1. Scalar Function (Single row function) : Functions
that act on only one value at a time are called scalar
functions. A single row function returns one result for
every row of a queried table or view.
2. Group Function (Aggregate function): Functions
that act on set of values are called group functions. A
group function returns a single result row for a group
of queried rows.
AGGREGATE FUNCTIONS
1. AVG
select avg(sell_price) from employee;
AVG(SELL_PRICE)
-----------
100.1234

2. MIN
select min(sell_price) “minimum sell_price” from
employee;
minimum sell_price
--------------------------
20
AGGREGATE FUNCTIONS
3. MAX
select max(sell_price) “maximum sell_price” from
employee;
maximum sell_price
-----------------------
10000
4. COUNT
select count(product_no) No_OF_Products from
product_master;
NO_OF_PRODUCTS
-----------------------
10
AGGREGATE FUNCTIONS
5. COUNT(*)
select count(*) “total” from product_master;

Returns the no of rows in the table , including


duplicates and those with nulls

6. SUM
select sum(sell_price) “sum of sell_price” from employee;
sum of sell_price
-----------------------
10000
SINGLE ROW FUNCTIONS
Single row functions can be further grouped together
by the data type of their arguments and return value.
There are various types of single row functions:
a. Character functions: Work for String Data type
b. Numeric function: Work for Number Data type.
c. Conversion Functions: Work for conversion of one data
type to another.
d. Date functions: Work for Date Data type.
NUMERIC FUNCTIONS
1. ABS
Select abs(-15) from dual;
Absolute
----------
15
2. POWER
Select power(5,2) “raised” from dual;
raised
----------
25
NUMERIC FUNCTIONS
3. ROUND
Select round(15.19,1) “round” from dual;
round
----------
15.2
4. SQRT
Select sqrt(25) “square root” from dual;
square root
----------
5
CHARACTER FUNCTION

1. LOWER
Select lower(‘WELcome’) “lower” from dual;
lower
--------------
welcome
2. INITCAP
Select INITCAP(‘welCOME Jaimit’) “INITIAL” from
dual;
INITIAL
--------------------
Welcome Jaimit
CHARACTER FUNCTION
3. UPPER
Select upper(‘hello’) “upper” from dual;
upper
--------
HELLO
4. SUBSTR
Select substr(‘hello world’,2,4) “sub string” from dual;
SUBSTR
-----------
ello
CHARACTER FUNCTION
5. LENGTH
Select length (‘Jaimit’) “length” from dual;
Length
--------
5
6. LTRIM
Select ltrim(‘nisha’,’n’) “left” from dual;
Left
-----
isha
CHARACTER FUNCTION
7. RTRIM
Select rtrim(‘nisha’,’a’) “right” from dual;
right
-----
nish
8. LPAD
Select lpad(‘hello’,10,’*’) “ left pad” from dual;
Leftpad
----------
*****hello
CHARACTER FUNCTION
9. RPAD
Select rpad(name,10,’ *’) “ right pad” from
client_master where name =’hello’;
Right pad
------------
hello*****
CONVERSION FUNCTIONS
1. TO_NUMBER
Converts character value containing a number in the
value of the number datatype
select to_number(substr('$100',2,3)) from dual;
TO_NUMBER(SUBSTR('$100',2,3))
--------------------------------------------
100
update product_master set sell_price= sell_price +
to_number(substr('$100',2,3));
Here, the value 100 will be added to every products
selling price in the product master table
CONVERSION FUNCTIONS
2. TO_CHAR (NUMBER CONVERSION)
Number is converted to char values exactly long
enough to hold significant digits
Select to_char(12345,’$099,999’) “ char” from dual’
char
------------
$012,345
CONVERSION FUNCTIONS
3. TO_CHAR (DATE CONVERSION)
select to_char(sysdate,'month dd, yyyy') from
dual;
TO_CHAR(SYSDATE,'M
----------------------------
FEBURARY 24, 2011
DATE CONVERSION FUNCTIONS
Converts character filed to date field
1. TO_DATE

select to_date('30-sep-85 10:55 a.m.','dd-mon-yy hh:mi


a.m.') from dual;
TO_DATE('
---------
30-SEP-85
2. LAST_DAY

select sysdate,last_day(sysdate) from dual;


SYSDATE LAST_DAY(
------------ -------------
24-FEB-11 28-FEB-11
DATE CONVERSION FUNCTIONS
3. ADD_MONTHS
select add_months(sysdate,4) from dual;
ADD_MONTH
-----------------
24-JUN-11
4. MONTHS_BETWWEN
Select months_between(’02-feb-1998’ , ’2-jan-1998’)
“months” from dual;
Months
---------
1
DATE CONVERSION FUNCTIONS
5. NEXT_DAY
select next_day('04-feb-98','sunday') from dual;
NEXT_DAY(
---------
09-FEB-98
GROUP BY AND HAVING CLAUSE
The group by and having clause are parallel to the order
by and where clause, except that they act on record sets,
and not on individual records.
The group functions perform an operation on a group of
rows and return one result.
Eg:
SELECT product_no, SUM(qty_ordered) “Total Qty Ordered”
FROM sales_order_details GROUP BY product_no;

SELECT count(empno),deptno FROM emp GROUP BY deptno


When a column is used in GROUP BY clause, the result is
sorted in ascending order by that column by default. i.e.,
GROUP BY has implied ORDER BY. Still ORDER BY can
be used to explicitly change the implied sorted order.
GROUP BY AND HAVING CLAUSE
The having clause is used to give conditions and filter
the groups created by group by clause.
Eg:
SELECT product_no, SUM(qty_ordered) “Total Qty Ordered”
FROM sales_order_details
GROUP BY product_no
HAVING product_no = ‘P001’ OR product_no = ‘P004’;

SELECT empId, COUNT (deptId)


FROM dependent
GROUP BY empId
HAVING COUNT (deptId)>2;
GROUP BY WITH ROLLUP AND
CUBE OPERATORS
Use ROLLUP or CUBE with GROUP BY to
produce super aggregate rows by
cross-referencing columns.
ROLLUP grouping produces a result set
containing the regular grouped rows and the
subtotal values.
CUBE grouping produces a result set containing
the rows from ROLLUP and cross-tabulation
rows.
ROLLUP
Use the ROLLUP operation to produce subtotal values
ROLLUP enables a SELECT statement to calculate
multiple levels of subtotals across a specified group of
dimensions.
It also calculates a grand total.

Example:
select city_id,dept,count(*),sum(salary) from employee
group by rollup(city_id,dept);
CUBE
Use the CUBE operation to produce cross-tabulation
values
If "n" is the number of columns listed in the CUBE, there
will be 2n subtotal combinations.
It also calculates a grand total.
This is the set of information typically needed for all
cross-tabular reports, so CUBE can calculate a
cross-tabular report with a single SELECT statement.
Example:
select city_id,dept,count(*),sum(salary) from employee
group by cube(city_id,dept);
EXISTS OPERATOR
The EXISTS operator tests for existence of rows in the
results set of the subquery.
If a subquery row value is found:
✔ The search does not continue in the inner query
✔ The condition is flagged TRUE
If a subquery row value is not found:
✔ The condition is flagged FALSE
✔ The search continues in the inner query

⚫ The EXISTS condition can be used in any valid


SQL statement - select, insert, update, or delete.
Syntax:
SELECT columns
FROM tables
WHERE EXISTS ( subquery );

select city_name from city c where


EXISTS(select 1 from employee e where
c.city_id=e.city_id);
NOT EXISTS OPERATOR
The NOT EXISTS operator tests for not existence of
rows in the results set of the subquery.
Syntax:
SELECT columns
FROM tables
WHERE NOT EXISTS ( subquery );

select city_name from city c where NOT EXISTS


(select 1 from employee e where
c.city_id=e.city_id);
JOINS
Joining multiple tables
Sometimes we treat multiple tables as they are a single
entity. Then a single SQL sentence can manipulate data
from all the tables. For this purpose we have to join
tables. Tables are joined on columns that have same data
type and data width in it.
An SQL JOIN clause combines rows from two or more
tables. It creates a set of rows in a temporary table.
A JOIN works on two or more tables if they have at least
one common field and have a relationship between them.
The various types of joins are:
1. Equi join (Also known as Inner join)
2. Non Equi join
3. Outer join
a) Left Outer Join
b) Right Outer Join
c) Full Outer Join
4. Self join
Table Name: EMP Table Name:
PRODUCT
ENO ENAME SALARY
------- ---------- ---------- PID ENO PNAME
1 Jaimit 5500 ----- ------ -----------
2 heli 4000 11 4 Pen
3 nency 6000 12 1 Pencil
4 navya 7000 13 2 Eraser
EQUI JOIN
It is a simple sql join condition which uses the equal sign (=) as
the comparison operator.
The equi join is a join with a join condition involving common
columns from two tables.
Eg: (1)
(ANSI-style)
select firstNm, lastNm, facultyNm, phone from student INNER
JOIN faculty ON student.facultyId = faculty.facultyId;
(Theta-style)
select firstNm, lastNm, facultyNm, phone from student, faculty
where student.facultyId = faculty.facultyId;
Eg: (2) select employee.empNm, dept.detNm, position.dosDesc
from employee, dept, position where emp.deptId = dept.deptId
AND emp.positionId = position.positionId;
Syntax
Select column_list FROM table1, table2.... WHERE
table1.column_name = table2.column_name;

An SQL INNER JOIN is same as JOIN clause,


combining rows from two or more tables.
Syntax
Select * FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
Syntax(OR )
Select * FROM table1 JOIN table2
ON table1.column_name = table2.column_name;
Equi join
select e.eno,ename,pname from employee e,product p
where e.eno=p.eno;

ENO ENAME PNAME


----- ------------ --------
1 heli Eraser
1 Jaimit Pencil
4 navya Pen
NON EQUI JOIN
The SQL NON EQUI JOIN uses comparison operator
instead of the equal sign like >, <, >=,
<=,IN,BETWEEN,LIKE,etc… along with conditions.
Syntax
Select * FROM table_name1, table_name2
WHERE table_name1.column [> | < | >= | <= ]
table_name2.column;
select e.ename,e.salary,g.grade
from empgrade e JOIN gradepoint g
ON e.salary between g.lowsal AND g.highsal;
OR
select e.ename,e.salary,g.grade
from empgrade e,gradepoint g
where e.salary between g.lowsal AND g.highsal;
OR
select e.ename,e.salary,g.grade
from empgrade e,gradepoint g
where e.salary>=g.lowsal AND e.salary<=g.highsal;

select e.ename,e.city_id,c.city_name
From employee e,city c
where c.city_name IN('Ahmedabad','Surat') AND e.city_id=c.city_id;
OUTER JOIN
The SQL OUTER JOIN returns all rows from both the
participating tables which satisfy the join condition
along with rows which do not satisfy the join condition.
The table that does not contain the matching value is
known as the deficient table. In eg: (1) the deficient
table is the student table, because it does not contain all
faculty ids.
The outer join uses the (+) operator in the join condition
on the deficient side. The (+) operator can be used on
any side of the join condition.
Syntax
select table1.colName, table2.colName table1, table2
where table1.colname (+) = table2.colName;
Left Outer Join: Here left means first table.it reurns all the rows
from the first table even though it does not have the matchs in
Second table.But it returns only the matched rows from the
second table.
select e.eno,ename,pname from employee e left join product p on
e.eno=p.eno; ----------------------(Ansi-style)
OR
select e.eno,ename,pname from employee e,product p where
e.eno=p.eno(+); ----------------------(Theta-style)

Right Outer Join: Here Right means Second table.it returns all
the rows from the second table even though it does not have the
matchs in First table.But it returns only the matched rows from
the First table.
select e.eno,ename,pname from employee e right join product p on
e.eno=p.eno; ----------------------(Ansi-style)
OR
select e.eno,ename,pname from employee e,product p where
e.eno(+)=p.eno; ----------------------(Theta-style)
RIGHT OUTER JOIN Left Outer Join

ENO ENAME ENO ENAME PNAME


PNAME ------ ----------- ----------
----- ------------ -------- 4 navya Pen
1 Jaimit Eraser 1 Jaimit Pencil
1 Jaimit Pencil 1 Jaimit Eraser
4 navya Pen 3 nency
2 heli
Book
FULL Outer Join :
The FULL OUTER JOIN will return all rows from both the
participating tables and does not select either the LEFT or
RIGHT table from the JOIN key word.
The FULL OUTER JOIN combines the results of both left and
right outer joins. When no matching rows exist for rows on the
left side of the JOIN key word, NULL values will be returned
from the result set on the right. On the other hand , when no
matching rows exist for rows on the right side of the JOIN key
word, NULL values will be returned from the result set on the
left.
FULL OUTER JOIN
select e.eno,ename,pname select p.eno,ename,pname
from emp2 e FULL from emp2 e FULL
OUTER JOIN product p OUTER JOIN product p
on e.eno=p.eno; on e.eno=p.eno;

ENO ENAME PNAME ENO ENAME PNAME


------ ----------- ---------- ------ ----------- ----------
4 navya Pen 4 navya Pen
1 Jaimit Pencil 1 Jaimit Pencil
1 Jaimit Eraser 1 Jaimit Eraser
3 nency nency
2 heli heli
Book 6 Book
Equi Join Outer Join
select firstNm || lastNm select firstNm || lastNm
STUDENT, facultyNm from STUDENT, facultyNm from
student s, faculty f where student s, faculty f where
s.facultyId = f.facultyId; s.facultyId (+) = f.facultyId;

STUDENT FACULTYNM STUDENT FACULTYNM


------------------- ------------------- --------------- ------------------
PallaviPatel Parul Rawal PallaviPatel Parul Rawal
YashPatel Bharat Patel YashPatel Bharat Patel
Rutu Patel Bhavesh Patel Alpesh Patel
MalayShah Jignesh Patel Hitesh More
Hinal Dave Jaimit Pancholi Rutu Patel Bhavesh Patel
MalayShah Jignesh Patel
Kaushik Raj
Hinal Dave Jaimit Pancholi
SELF JOIN
Self join is joining a table to itself.
Particularly when the table has a FOREIGN KEY that
references its own PRIMARY KEY. It is necessary to
ensure that the join statement defines an alias for both
copies of the table to avoid column ambiguity.

select e.empNm employee, m.empNm manager from employee e,


employee m where e.manager = m.employeeId
Natural join
The SQL NATURAL JOIN is a type of equi-join and is
structured in such a way that, columns with same name
of associate tables will appear once only.
Syntax
Select * FROM table1 NATURAL JOIN table2;
Cross join
The SQL CROSS JOIN produces a result set which is the
number of rows in the first table multiplied by the
number of rows in the second table
Syntax
Select * FROM table1 CROSS JOIN table2;
If, WHERE clause is used with CROSS JOIN, it
functions like an INNER JOIN.
SET OPERATORS
The various set operators are: union, unionall, intersect,
minus.
The general syntax for any set operation is:
SELECT Query 1 set operator SELECT query 2
The set operator is one of the four set operators described:

Set User
Operator
UNION It returns all rows from both queries, but duplicate
rows are not repeated.
UNION ALL IT returns all rows from both queries, and it displays
all duplicate rows.
INTERSECT It returns all rows that appear in both queries’
results
MINUS It returns rows that are returned by the first query
minus rows that are returned by the second query.
UNION INTERSECT

MINUS
UNION
The UNION operator takes output from two queries
and returns all rows from both results.
The duplicate rows are displayed only once.
If you perform union on two very large tables , use a
WHERE clause to filter rows.
Eg:
select studId, last, first from student
UNION
select workerID, last, first from worker;
UNION ALL
The UNION ALL operation is similar to the UNION
operation. The only difference is that UNION ALL
operation also displays duplicate rows.
Eg:
select studId, last, first from student
UNION ALL
select workerId, last,first from worker
INTERSECT
The INTERSECT operator works on output from two
separate queries and returns rows that appear in both
outputs.
Eg:
select studId, last, first from student
INTERSECT
select workerId, last,first from worker
MINUS
When MINUSis performed on output of two queries,
the result is the rows in the first query’s result that
are not in the second query’s result
Eg:
select studId, last, first from student
MINUS
select workerId, last,first from worker
In the above example student table MINUS worker
table is not the same as worker table MINUS student
table. i.e., students who are not workers.
SUBQUERY
Subqueries are also known as nested queries.
A subquery is usually a SELECT query within one of
the clauses in another SELECT query.
A subquery is very useful when a query based on a
table depends on the data in that subquery itself.
The subquery can be used within a WHERE, HAVING,
or FROM clause of another SELECT query.
The subquery (inner query) executes once before
the main query (outer query).
The result of the subquery is used by the main
query.
Certain rules for creating subquery

The subquery must be enclosed within a pair of


parentheses.
The subquery is used on the right side of the condition.
The ORDER BY clause cannot be used in the subquery.
Use single-row operators with single-row subqueries,
and use multiple-row operators with multiple-row
subqueries.
Types of Subqueries

Single-row subquery:- a subquery that returns only


one row of data; it is also known as a scalar subqury.
Multiple-row subquery:- a subquery that returns
more than one row of data.
Single-Row Subqueries:-
Return only one row
Use single-row comparison operators

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
Subquery using one table:-
select eno,ename,salary,city_id from employee
where eno>(select eno from employee where eno=3);

Subquery using two table:-


select eno,ename,salary,city_id from employee
where city_id=(select city_id from city where
city_name='Ahmedabad');
Using Group Functions in a Subquery:-
select eno,ename,salary,dept from employee
where salary=(select min(salary) from employee);

The HAVING Clause with Subqueries:-


select city_id,min(salary) from employee group by
city_id having min(salary)>(select min(salary) from
employee where city_id=11);

ERROR:- single-row subquery returns more than one


row
select eno,ename from employee where salary=(select
min(salary) from employee group by city_id)
Multiple-row subquery:-
Return more than one row
Use multiple-row comparison operators

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the
subquery
ALL Compare value to every value returned by the
subquery
IN Operator:-
select eno,ename,salary,city_id,dept from employee where
city_id in(select city_id from employee where dept='Sales');
ANY Operator:-
✔ <ANY means less than the maximum value in the list.

✔ =ANY means equal to any value in the list(similar to IN).

✔ >ANY means higher than the minimum value in the list.

ALL Operator:-
✔ >ALL means more than the maximum value.

✔ <ALL means less than the minimum value.

✔ =ALL is meaningless, because no value can be equal to all


values in list.
ANY Operator:-
✔ <ANY means less than the maximum value in the list.

select eno,ename,salary,city_id from employee where salary


<any(select salary from employee where city_id=22);

✔ =ANY means equal to any value in the list(similar to IN).


select eno,ename,salary,city_id,dept from employee where
city_id=any(select city_id from employee where
dept='Sales');

✔ >ANY means higher than the minimum value in the list.


select eno,ename,salary,city_id from employee where
salary>any( select salary from employee where city_id=22);
All Operator:-
✔ <ALL means less than the maximum value in the list.

select eno,ename,salary,city_id,dept from employee where


salary<all(select avg(salary)from employee group by
city_id);

✔ >ALL means higher than the minimum value in the list.


select eno,ename,salary,city_id,dept from employee where
salary>all(select avg(salary)from employee group by
city_id);

You might also like