SQL.ppt
SQL.ppt
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*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;
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];
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;
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;
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
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
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
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
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);
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.
ALL Operator:-
✔ >ALL means more than the maximum value.