Sinhgad Institutes
• SQL is an ANSI and ISO standard computer
language for creating and manipulating
databases.
* SQL allows the user to create, update,
delete, and retrieve data from a database.
*SQL is very simple and easy to learn.
*SQL works with database programs like DB2,
Oracle, MS Access, Sybase, MS SQL Sever etc.
Characteristics of SQL:
1
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• Advantages of SQL:
* High Speed:
SQL Queries can be used to retrieve large amounts of records from a database
quickly and efficiently.
• * Well Defined Standards Exist:
SQL databases use long-established standard,which is being adopted by ANSI & ISO.
Non-SQL databases do not adhere to any clear standard.
* No Coding Required:
Using standard SQL it is easier to manage database systems without having to write
substantial amount of code.
• * Emergence of ORDBMS:
Previously SQL databases were synonymous with relational database. With the
emergence of Object Oriented DBMS, object storage capabilities are extended to
relational databases.
Advantages & Disadvantages
2
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• * Difficulty in Interfacing:
Interfacing an SQL database is more complex
than adding a few lines of code.
* More Features Implemented in Proprietary
way:
Although SQL databases conform to ANSI &
ISO standards, some databases go for
proprietary extensions to standard SQL to
ensure vendor lock-in.
Disadvantages of SQL
3
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• DDL
• DML
• DCL
• TCL
Data Languages
4
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• A data definition language or data description language (DDL) is a syntax
similar to a computer programming language for defining data structures,
especially database schemas.
• CREATE statement
• The CREATE command is used to establish a new database, table, index, or
stored procedure.
• The CREATE statement in SQL creates a component in a relational
database management system (RDBMS). In the SQL 1992 specification, the
types of components that can be created are schemas, tables, views,
domains, character sets, collations, translations, and assertions. Many
implementations extend the syntax to allow creation of additional
elements, such as indexes and user profiles. Some systems, such as
PostgreSQL, allow CREATE, and other DDL commands, inside a database
transaction and thus they may be rolled back.
CREATE statement
UNIT-2 SQL & 5
Sinhgad Institutes
• CREATE TABLE statement
• A commonly used CREATE command is the CREATE TABLE
command. The typical usage is:
• CREATE TABLE [table name] ( [column definitions] ) [table
parameters]
• The column definitions are:
• A comma-separated list consisting of any of the following
• Column definition: [column name] [data type] {NULL | NOT
NULL} {column options}
• Primary key definition: PRIMARY KEY ( [comma separated
column list] )
• Constraints: {CONSTRAINT} [constraint definition]
• RDBMS specific functionality
• An example statement to create a table named employees
with a few columns is:
UNIT-2 SQL & 6
Sinhgad Institutes
• CREATE TABLE employees (
• id INTEGER PRIMARY KEY,
• first_name VARCHAR(50) not null,
• last_name VARCHAR(75) not null,
• fname VARCHAR(50) not null,
• dateofbirth DATE not null
• );
•
UNIT-2 SQL & 7
Sinhgad Institutes
•
• Once data has been inserted into a table, the next most logical operation would be to view what has been
inserted. The SELECT SQL verb is used to achieve this.
•
• All Rows and All Columns
• Syntax: SELECT * FROM Table_name;
• eg: Select * from Student; It will show all the table records.
•
• SELECT First_name, DOB FROM STUDENT WHERE Reg_no = 'S101'; Cover it by single inverted comma if
its datatype is varchar or char.
• This Command will show one row. because you have given condition for only one row and particular
records. If condition which has given in WHERE Clause is true then records will be fetched otherwise it will
show no records selected.
• Eliminating Duplicates:
•
• A table could hold duplicate rows. In such a case, you can eliminate duplicates.
• Syntax: SELECT DISTINCT col, col, .., FROM table_name;
•
• eg : SELECT DISTINCT * FROM Student;
•
• or : SELECT DISTINCT first_name, city, pincode FROM Student;
•
Viewing Data in the Table (Select Command)
UNIT-2 SQL & 8
Sinhgad Institutes
• More than one are there to Insert data into a table
• eg: INSERT INTO student (reg_no, first_name, last_name, dob,address,
pincode)
• VALUES('A101', 'Mohd', 'Imran', '01-MAR-89','Allahabad', 211001);
•
• eg : INSERT INTO student VALUES('A101', 'Mohd', 'Imran', '01-MAR-
89','Allahabad', 211001);
• Note : Character expression placed within the insert into statement must be
enclosed in single quotes (').
• Inserting data into a table from another table:
• In addition to inserting data one row at a time into a table, it is quite possible to
populate a table with data that already exist in another table. You can store same
record in a table that already stored in another table.
• Eg : suppose you want to insert data from course table to university table then
use this example:
• INSERT INTO university SELECT course_id, course_name FROM course;
• Data will be inserted into university table automatically, what will be in course
table.
• you can give condition also in WHERE clause.
INSERT
UNIT-2 SQL & 9
Sinhgad Institutes
• A DBA can make changes to the table structure or column definitions after the
table has been created in the database.The DDL command ALTER TABLE is used to
perform such actions.Alter command provides multiple utilities exclusive for
schema objects.The ALTER TABLE statement is used to add, drop, rename, and
modify a column in a table.
• The below ALTER TABLE statement renames the table EMP to EMP_NEW.
• ALTER TABLE EMP RENAME TO EMP_NEW;
• The below ALTER TABLE statement adds a new column TESTCOL to the EMP_NEW
table
• ALTER TABLE EMP_NEW ADD (TESTCOL VARCHAR2 (100))
• The below ALTER TABLE statement renames the column TESTCOL to TESTNEW.
• ALTER TABLE EMP_NEW RENAME COLUMN TESTCOL TO TESTNEW
• The below ALTER TABLE statement drop the column TESTNEW from EMP_NEW
table
• ALTER TABLE EMP_NEW DROP COLUMN TESTNEW;
• The below ALTER TABLE statement adds primary key on the EMPLOYEE_ID column.
• ALTER TABLE EMP_NEW ADD PRIMARY KEY (EMPLOYEE_ID)
ALTER TABLE statement
UNIT-2 SQL & 1
Sinhgad Institutes
• The below ALTER TABLE statement drop the primary key.
• ALTER TABLE EMP_NEW DROP PRIMARY KEY;
• The below ALTER TABLE statement switches the table mode to read only.
• ALTER TABLE EMP_NEW READ ONLY;
• Read Only Tables
• Read only tables came as an enhancement in Oracle 11g.It allows the tables to be used for
read only purpose. In earlier oracle versions, tables were made read only by granting SELECT
privilege to the other users, but owner still had the read write privilege.But now,if a table is
set as Read only,even owner doesn't have access on data manipulation.
• Syntax:
• ALTER TALE [TABLE NAME] READ ONLY
• ALTER TALE [TABLE NAME] READ WRITE
• Illustration
• SQL>CREATE TABLE ORATEST (id NUMBER)
• SQL>INSERT INTO ORATEST VALUES (1);
• SQL>ALTER TABLE ORATEST READ ONLY;
•
UNIT-2 SQL & 1
Sinhgad Institutes
• SQL> INSERT INTO ORATEST VALUES (2);
• INSERT INTO ORATEST VALUES (2)
• *
• ERROR at line 1:
• ORA-12081: update operation not allowed on table "TEST"."ORATEST"
• SQL> ALTER TABLE ORATEST READ WRITE;
•
• Table altered.
•
• SQL> DELETE FROM ORATEST;
•
• 1 row deleted.
UNIT-2 SQL & 1
Sinhgad Institutes
• With RENAME statement you can rename a table.
• Some of the relational database management system
(RDBMS) does not support this command, because this is not
standardizing statement.
• For example renaming a table through MS SQL Server you
must use storage procedure SP_RENAME.
• Syntax for SQL RENAME is:
• RENAME TABLE {tbl_name} TO {new_tbl_name};
• Where {tbl_name} table that exists in the current database,
and {new_tbl_name} is new table name.
• As for Oracle may also be use the following option:
• ALTER TABLE {tbl_name} RENAME TO {new_tbl_name};
UNIT-2 SQL & 1
Rename
Sinhgad Institutes
• As Example
• CREATE TABLE employees
( id NUMBER(6),
name VARCHAR(20)
);
INSERT INTO employees( id, name ) values( 1, 'name 1');
INSERT INTO employees( id, name ) values( 2, 'name 2');
INSERT INTO employees( id, name ) values( 3, 'name 3');
• SELECT * FROM employees;
RENAME TABLE employees TO employees_new;
SELECT * FROM employees_new;
UNIT-2 SQL & 1
Sinhgad Institutes
• The DELETE command can remove all the rows from the table or a set of
rows from the table.
•
• eg: DELETE FROM student; It will DELETE all the rows from student table.
•
• eg: DELETE FROM student WHERE reg_no='A101'; If condition will be
satisfied then it will delete a row from the table Register number A101 will
be deleted from the table
•
• If you want to delete table column then use ALTER TABLE command.
•
• eg : ALTER TABLE student DROP COLUMN dob; The DOB column will be
deleted from the student table.
DELETE Operation:
UNIT-2 SQL & 1
Sinhgad Institutes
• The UPDATE command is used to change or modify data values
in a table and UPDATE command can Update all the rows from
the table or a set of rows from the table.
• eg : UPDATE Student SET course='MCA';
• Course is a column name, suppose ant time you want to update
something like that in the student table course should be MCA
for all students then you can use this type of query. It will update
all the rows in the table all rows will have MCA course.
• Now, if you want update particular row then see below.
•
• UPDATE Student SET course='MCA' where reg_no='A101';
• it will update only one row that will have Register no. A101.
UPDATE Operation:
UNIT-2 SQL & 1
Sinhgad Institutes
• you can use different-different types of condition in WHERE
clause,
• eg salary updation, if salary has increased someone's then
simply multiply, addition you can do in salary column.
•
• I will show example. Suppose someone's has increased salary
by 10% then what should to do. See example:
•
• UPDATE employee SET salary= salary+salary*0.1 WHERE
employee_id='E101';
• Salary will be automatically increased by 10% of salary.
•
UNIT-2 SQL & 1
Sinhgad Institutes
• The DROP TABLE statement is used to remove a table from the
database. The dropped table and its data remain no longer
available for selection.Dropped table can be recovered using
FLASHBACK utility,if available in recyclebin.Dropping a table
drops the index and triggers associated with it.
• Syntax:
• DROP TABLE [TABLE NAME] []
• The below statement will drop the table and place it into the
recyclebin.
• DROP TABLE emp_new;
• The below statement will drop the table and flush it out from
the recyclebin also.
• DROP TABLE emp_new PURGE;
DROP TABLE statement
UNIT-2 SQL &
PLSQL 1
Sinhgad Institutes
19
Views
View in SQL are kind of virtual tables.
A view also has rows and column as they are in real table in
the database.
We can create view by selecting fields fom one or more table
present in the database.
A view can either have all the rows of table or specific rows
based on certain condition.
Creating view:
We can create view using create view statement.
Syntax:
Create view nam of view AS
Select column1,column2……
From table_name1,table_name2…
Where condition;
Sinhgad Institutes
• Rules for updating the views:
• The view can be defined based on one and
only one table
• The view should not have all NOT NULL values.
• The view should not be created from nested
and complex queries.
• The view should not have any field made out
of aggregate function.
• The select statement should not have
DISTINCT keyword.
UNIT-2 SQL & PLSQL 20
Sinhgad Institutes
• The following commands are used to control
transactions.
• COMMIT − to save the changes.
• ROLLBACK − to roll back the changes.
• SAVEPOINT − creates points within the groups
of transactions in which to ROLLBACK.
• SET TRANSACTION − Places a name on a
transaction.
Transaction Control
22
UNIT-2 SQL & PLSQL
Sinhgad Institutes
 Transactional control commands are only used with the
DML Commands such as - INSERT, UPDATE and DELETE
only. They cannot be used while creating tables or dropping
them because these operations are automatically
committed in the database.
 The COMMIT Command
 The COMMIT command is the transactional command used
to save changes invoked by a transaction to the database.
 The COMMIT command saves all the transactions to the
database since the last COMMIT or ROLLBACK command.
 The syntax for the COMMIT command is as follows.
 COMMIT;
Transactional Control Commands
23
UNIT-2 SQL & PLSQL
Sinhgad Institutes
 There are two type of Operators, namely Comparison
Operators and Logical Operators. These operators are
used mainly in the WHERE clause, HAVING clause to
filter the data to be selected.

Comparison Operators:
 Comparison operators are used to compare the
column data with specific values in a condition.
 Comparison Operators are also used along with the
SELECT statement to filter data based on specific
conditions.
SQL Operators
24
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• Comparison Operators
• = equal to
• <>, != is not equal to
• < less than
• > greater than
• >= greater than or equal to
• <= less than or equal to
Comparison operator.
25
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• 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 Operators
26
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• OR:- For the row to be selected at least one of
the conditions must be true.
• AND :-For a row to be selected all the
specified conditions must be true.
• NOT:- For a row to be selected the specified
condition must be false.
Logical Operators Description
27
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• If you want to select rows that satisfy at least
one of the given conditions, you can use the
logical operator, OR.
• For example: if you want to find the names of
students who are studying either Maths or
Science, the query would be like,
• SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'Maths' OR subject =
'Science'
OR" Logical Operator:
28
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• If you want to select rows that must satisfy all
the given conditions, you can use the logical
operator, AND.
• For Example: To find the names of the
students between the age 10 to 15 years, the
query would be like:
• SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;
AND" Logical Operator:
29
UNIT-2 SQL & PLSQL
Sinhgad Institutes
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.
For example: If you want to find out the names
of the students who do not play football, the
query would be like:
SELECT first_name, last_name, games
FROM student_details
WHERE NOT games = 'Football'
NOT" Logical Operator:
30
UNIT-2 SQL & PLSQL
Sinhgad Institutes
 An aggregate functions are built-in SQL functions that
operate on groups of rows and return one value for the
entire group. These functions are: COUNT, MAX, MIN, AVG,
SUM, DISTINCT
 SQL COUNT (): This function returns the number of rows in
the table that satisfies the condition specified in the
WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the
table.
 For Example: If you want the number of employees in a
particular department, the query would be:
 SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
SQL Aggregate Functions
31
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• SQL DISTINCT(): This function is used to select
the distinct rows.
• For Example: If you want to select all distinct
department names from employee table, the
query would be:
• SELECT DISTINCT dept FROM employee;
• To get the count of employees with unique
name, the query would be:
• SELECT COUNT (DISTINCT name) FROM
employee;
Cntu..
32
UNIT-2 SQL & PLSQL
Sinhgad Institutes
 SQL MAX(): This function is used to get the maximum value from a column.
 To get the maximum salary drawn by an employee, the query would be:
 SELECT MAX (salary) FROM employee;

SQL MIN(): This function is used to get the minimum value from a column.
 To get the minimum salary drawn by an employee, he query would be:
 SELECT MIN (salary) FROM employee;

SQL AVG(): This function is used to get the average value of a numeric column.
 To get the average salary, the query would be
 SELECT AVG (salary) FROM employee;

SQL SUM(): This function is used to get the sum of a numeric column
 To get the total salary given out to the employees,
 SELECT SUM (salary) FROM employee;
Cntu..
33
UNIT-2 SQL & PLSQL
Sinhgad Institutes
 Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but is used with group functions.
 Group functions cannot be used in WHERE Clause but can be used in HAVING
clause.
 SQL HAVING Clause Example
 If you want to select the department that has total salary paid for its employees
more than 25000, the sql query would be like;
 SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000
 The output would be like:
 dept salary
 ------------- -------------
 Electronics 55000
 Aeronautics 35000
 InfoTech 30000
SQL HAVING Clause
34
UNIT-2 SQL & PLSQL
Sinhgad Institutes
• When WHERE, GROUP BY and HAVING clauses
are used together in a SELECT statement, the
WHERE clause is processed first, then the rows
that are returned after the WHERE clause is
executed are grouped based on the GROUP BY
clause.
• Finally, any conditions on the group functions
in the HAVING clause are applied to the
grouped rows before the final output is
displayed.
Cntu..
35
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Join function
Sinhgad Institutes
Joins
• SQL Join is used to fetch data from two or more
tables, which is joined to appear as single set of
data. SQL Join is used for combining column
from two or more tables by using values
common to both tables.
37
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Types of join
The following are the types of JOIN that we
can use in SQL.
• Inner
• Outer
• Left
• Right
38
UNIT-2 SQL & PLSQL
Sinhgad Institutes
INNER Join or EQUI Join
• This is a simple JOIN in which the result is
based on matched data as per the equality
condition specified in the query.
• Inner Join Syntax is,
• SELECT column-name-list from table-name1
INNER JOIN table-name2 WHERE table-
name1.column-name = table-name2.column-
name;
39
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Example for INNER Join
• The class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID Address
The class_info table,
40
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Example for INNER Join
• Inner JOIN query will be,
• SELECT * from class, class_info where class.id
= class_info.id;
• The result table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
41
UNIT-2 SQL & PLSQL
Sinhgad Institutes
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.
• Natural Join Syntax is,
• SELECT * from table-name1 NATURAL JOIN
table-name2;
42
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Natural join
The class_info table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
The class table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
43
UNIT-2 SQL & PLSQL
Sinhgad Institutes
Example of natural join
• Natural join query will be,
• SELECT * from class NATURAL JOIN class_info;
• The result table will look like,
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
Note: In the above example, both the tables being joined have ID
column(same name and same data type), hence the records for
which value of ID matches in both the tables will be the result of
Natural Join of these two tables. 4
UNIT-2 SQL &
Sinhgad Institutes
Outer join
• Outer Join is based on both matched and
unmatched data. Outer Joins subdivide
further into,
• Left Outer Join
• Right Outer Join
• Full Outer Join
4
UNIT-2 SQL &
Sinhgad Institutes
Left outer join
• 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.
• Left Outer Join syntax is,
• SELECT column-name-list from table-name1 LEFT
OUTER JOIN table-name2 on table-
name1.column-name = table-name2.column-
name; (or)
• select column-name-list from table-name1, table-
name2 on table-name1.column-name = table-
name2.column-name(+);
4
UNIT-2 SQL &
Sinhgad Institutes
Example of Left Outer Join
The class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
The class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
4
UNIT-2 SQL &
Sinhgad Institutes
Example of Left Outer Join
• Left Outer Join query will be,
• SELECT * FROM class LEFT OUTER JOIN
class_info ON (class.id=class_info.id);
• The result table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
4
UNIT-2 SQL &
Sinhgad Institutes
Right Outer Join
• 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.
• Right Outer Join Syntax is,
• select column-name-list from table-
name1 RIGHT OUTER JOIN table-name2
on table-name1.column-name = table-
name2.column-name; (or)
• select column-name-list from table-
name1, table-name2 on table- 4
UNIT-2 SQL &
Sinhgad Institutes
Example of Right Outer Join
The class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
The class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
5
UNIT-2 SQL &
Sinhgad Institutes
Example of Right Outer Join
• Right Outer Join query will be,
• SELECT * FROM class RIGHT OUTER JOIN
class_info on (class.id=class_info.id);
• The result table will look like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT
5
UNIT-2 SQL &
Sinhgad Institutes
Full Outer Join
• 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.
• Full Outer Join Syntax is,
• select column-name-list from table-
name1 FULL OUTER JOIN table-name2 on
table-name1.column-name = table-
name2.column-name;
5
UNIT-2 SQL &
Sinhgad Institutes
Example of Full outer join
The class table,
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
The class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
5
UNIT-2 SQL &
Sinhgad Institutes
Example of Full outer join
• Full Outer Join query will be like,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
null null 7 NOIDA
null null 8 PANIPAT
5
UNIT-2 SQL &
Sinhgad Institutes
PL/SQL
• PL SQL basically stands for "Procedural Language
SQL".
• This is the extension of Structured Query
Language (SQL) that is used in Oracle.
• Data manipulation power of SQL + Processing power
of procedural language
• Allows the programmers to instruct the compiler
'what to do' through SQL and 'how to do' through its
procedural way.
• Gives more control to the programmers by the use of
loops, conditions and object oriented concepts.
5
UNIT-2 SQL &
Sinhgad Institutes
1.Support for SQL
Support all functionality of SQL.
Efficient database handling.
2.Improved performance
SQL processing:single statement
PL/SQL processing: Block of statements
Reduces overheads to improve performance.
UNIT-2 SQL & 5
ADVANTAGE OF PL/SQL
Sinhgad Institutes
3.Block structure:
PL/SQL is a block structured language.
Programs can be divided ino logical blocks of code.
4.Higher productivity:
Procedural constructs.
PL/SQL can be used with
Oracle database server
Oracle tools like Forms,Reports etc.
5.Portability:
Application written in PL/SQL are portable to
Any computer hardware
Any OS Environment where Oracle RDMBS is running.
UNIT-2 SQL & 5

UNIT2.ppt

  • 1.
    Sinhgad Institutes • SQLis an ANSI and ISO standard computer language for creating and manipulating databases. * SQL allows the user to create, update, delete, and retrieve data from a database. *SQL is very simple and easy to learn. *SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc. Characteristics of SQL: 1 UNIT-2 SQL & PLSQL
  • 2.
    Sinhgad Institutes • Advantagesof SQL: * High Speed: SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently. • * Well Defined Standards Exist: SQL databases use long-established standard,which is being adopted by ANSI & ISO. Non-SQL databases do not adhere to any clear standard. * No Coding Required: Using standard SQL it is easier to manage database systems without having to write substantial amount of code. • * Emergence of ORDBMS: Previously SQL databases were synonymous with relational database. With the emergence of Object Oriented DBMS, object storage capabilities are extended to relational databases. Advantages & Disadvantages 2 UNIT-2 SQL & PLSQL
  • 3.
    Sinhgad Institutes • *Difficulty in Interfacing: Interfacing an SQL database is more complex than adding a few lines of code. * More Features Implemented in Proprietary way: Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary extensions to standard SQL to ensure vendor lock-in. Disadvantages of SQL 3 UNIT-2 SQL & PLSQL
  • 4.
    Sinhgad Institutes • DDL •DML • DCL • TCL Data Languages 4 UNIT-2 SQL & PLSQL
  • 5.
    Sinhgad Institutes • Adata definition language or data description language (DDL) is a syntax similar to a computer programming language for defining data structures, especially database schemas. • CREATE statement • The CREATE command is used to establish a new database, table, index, or stored procedure. • The CREATE statement in SQL creates a component in a relational database management system (RDBMS). In the SQL 1992 specification, the types of components that can be created are schemas, tables, views, domains, character sets, collations, translations, and assertions. Many implementations extend the syntax to allow creation of additional elements, such as indexes and user profiles. Some systems, such as PostgreSQL, allow CREATE, and other DDL commands, inside a database transaction and thus they may be rolled back. CREATE statement UNIT-2 SQL & 5
  • 6.
    Sinhgad Institutes • CREATETABLE statement • A commonly used CREATE command is the CREATE TABLE command. The typical usage is: • CREATE TABLE [table name] ( [column definitions] ) [table parameters] • The column definitions are: • A comma-separated list consisting of any of the following • Column definition: [column name] [data type] {NULL | NOT NULL} {column options} • Primary key definition: PRIMARY KEY ( [comma separated column list] ) • Constraints: {CONSTRAINT} [constraint definition] • RDBMS specific functionality • An example statement to create a table named employees with a few columns is: UNIT-2 SQL & 6
  • 7.
    Sinhgad Institutes • CREATETABLE employees ( • id INTEGER PRIMARY KEY, • first_name VARCHAR(50) not null, • last_name VARCHAR(75) not null, • fname VARCHAR(50) not null, • dateofbirth DATE not null • ); • UNIT-2 SQL & 7
  • 8.
    Sinhgad Institutes • • Oncedata has been inserted into a table, the next most logical operation would be to view what has been inserted. The SELECT SQL verb is used to achieve this. • • All Rows and All Columns • Syntax: SELECT * FROM Table_name; • eg: Select * from Student; It will show all the table records. • • SELECT First_name, DOB FROM STUDENT WHERE Reg_no = 'S101'; Cover it by single inverted comma if its datatype is varchar or char. • This Command will show one row. because you have given condition for only one row and particular records. If condition which has given in WHERE Clause is true then records will be fetched otherwise it will show no records selected. • Eliminating Duplicates: • • A table could hold duplicate rows. In such a case, you can eliminate duplicates. • Syntax: SELECT DISTINCT col, col, .., FROM table_name; • • eg : SELECT DISTINCT * FROM Student; • • or : SELECT DISTINCT first_name, city, pincode FROM Student; • Viewing Data in the Table (Select Command) UNIT-2 SQL & 8
  • 9.
    Sinhgad Institutes • Morethan one are there to Insert data into a table • eg: INSERT INTO student (reg_no, first_name, last_name, dob,address, pincode) • VALUES('A101', 'Mohd', 'Imran', '01-MAR-89','Allahabad', 211001); • • eg : INSERT INTO student VALUES('A101', 'Mohd', 'Imran', '01-MAR- 89','Allahabad', 211001); • Note : Character expression placed within the insert into statement must be enclosed in single quotes ('). • Inserting data into a table from another table: • In addition to inserting data one row at a time into a table, it is quite possible to populate a table with data that already exist in another table. You can store same record in a table that already stored in another table. • Eg : suppose you want to insert data from course table to university table then use this example: • INSERT INTO university SELECT course_id, course_name FROM course; • Data will be inserted into university table automatically, what will be in course table. • you can give condition also in WHERE clause. INSERT UNIT-2 SQL & 9
  • 10.
    Sinhgad Institutes • ADBA can make changes to the table structure or column definitions after the table has been created in the database.The DDL command ALTER TABLE is used to perform such actions.Alter command provides multiple utilities exclusive for schema objects.The ALTER TABLE statement is used to add, drop, rename, and modify a column in a table. • The below ALTER TABLE statement renames the table EMP to EMP_NEW. • ALTER TABLE EMP RENAME TO EMP_NEW; • The below ALTER TABLE statement adds a new column TESTCOL to the EMP_NEW table • ALTER TABLE EMP_NEW ADD (TESTCOL VARCHAR2 (100)) • The below ALTER TABLE statement renames the column TESTCOL to TESTNEW. • ALTER TABLE EMP_NEW RENAME COLUMN TESTCOL TO TESTNEW • The below ALTER TABLE statement drop the column TESTNEW from EMP_NEW table • ALTER TABLE EMP_NEW DROP COLUMN TESTNEW; • The below ALTER TABLE statement adds primary key on the EMPLOYEE_ID column. • ALTER TABLE EMP_NEW ADD PRIMARY KEY (EMPLOYEE_ID) ALTER TABLE statement UNIT-2 SQL & 1
  • 11.
    Sinhgad Institutes • Thebelow ALTER TABLE statement drop the primary key. • ALTER TABLE EMP_NEW DROP PRIMARY KEY; • The below ALTER TABLE statement switches the table mode to read only. • ALTER TABLE EMP_NEW READ ONLY; • Read Only Tables • Read only tables came as an enhancement in Oracle 11g.It allows the tables to be used for read only purpose. In earlier oracle versions, tables were made read only by granting SELECT privilege to the other users, but owner still had the read write privilege.But now,if a table is set as Read only,even owner doesn't have access on data manipulation. • Syntax: • ALTER TALE [TABLE NAME] READ ONLY • ALTER TALE [TABLE NAME] READ WRITE • Illustration • SQL>CREATE TABLE ORATEST (id NUMBER) • SQL>INSERT INTO ORATEST VALUES (1); • SQL>ALTER TABLE ORATEST READ ONLY; • UNIT-2 SQL & 1
  • 12.
    Sinhgad Institutes • SQL>INSERT INTO ORATEST VALUES (2); • INSERT INTO ORATEST VALUES (2) • * • ERROR at line 1: • ORA-12081: update operation not allowed on table "TEST"."ORATEST" • SQL> ALTER TABLE ORATEST READ WRITE; • • Table altered. • • SQL> DELETE FROM ORATEST; • • 1 row deleted. UNIT-2 SQL & 1
  • 13.
    Sinhgad Institutes • WithRENAME statement you can rename a table. • Some of the relational database management system (RDBMS) does not support this command, because this is not standardizing statement. • For example renaming a table through MS SQL Server you must use storage procedure SP_RENAME. • Syntax for SQL RENAME is: • RENAME TABLE {tbl_name} TO {new_tbl_name}; • Where {tbl_name} table that exists in the current database, and {new_tbl_name} is new table name. • As for Oracle may also be use the following option: • ALTER TABLE {tbl_name} RENAME TO {new_tbl_name}; UNIT-2 SQL & 1 Rename
  • 14.
    Sinhgad Institutes • AsExample • CREATE TABLE employees ( id NUMBER(6), name VARCHAR(20) ); INSERT INTO employees( id, name ) values( 1, 'name 1'); INSERT INTO employees( id, name ) values( 2, 'name 2'); INSERT INTO employees( id, name ) values( 3, 'name 3'); • SELECT * FROM employees; RENAME TABLE employees TO employees_new; SELECT * FROM employees_new; UNIT-2 SQL & 1
  • 15.
    Sinhgad Institutes • TheDELETE command can remove all the rows from the table or a set of rows from the table. • • eg: DELETE FROM student; It will DELETE all the rows from student table. • • eg: DELETE FROM student WHERE reg_no='A101'; If condition will be satisfied then it will delete a row from the table Register number A101 will be deleted from the table • • If you want to delete table column then use ALTER TABLE command. • • eg : ALTER TABLE student DROP COLUMN dob; The DOB column will be deleted from the student table. DELETE Operation: UNIT-2 SQL & 1
  • 16.
    Sinhgad Institutes • TheUPDATE command is used to change or modify data values in a table and UPDATE command can Update all the rows from the table or a set of rows from the table. • eg : UPDATE Student SET course='MCA'; • Course is a column name, suppose ant time you want to update something like that in the student table course should be MCA for all students then you can use this type of query. It will update all the rows in the table all rows will have MCA course. • Now, if you want update particular row then see below. • • UPDATE Student SET course='MCA' where reg_no='A101'; • it will update only one row that will have Register no. A101. UPDATE Operation: UNIT-2 SQL & 1
  • 17.
    Sinhgad Institutes • youcan use different-different types of condition in WHERE clause, • eg salary updation, if salary has increased someone's then simply multiply, addition you can do in salary column. • • I will show example. Suppose someone's has increased salary by 10% then what should to do. See example: • • UPDATE employee SET salary= salary+salary*0.1 WHERE employee_id='E101'; • Salary will be automatically increased by 10% of salary. • UNIT-2 SQL & 1
  • 18.
    Sinhgad Institutes • TheDROP TABLE statement is used to remove a table from the database. The dropped table and its data remain no longer available for selection.Dropped table can be recovered using FLASHBACK utility,if available in recyclebin.Dropping a table drops the index and triggers associated with it. • Syntax: • DROP TABLE [TABLE NAME] [] • The below statement will drop the table and place it into the recyclebin. • DROP TABLE emp_new; • The below statement will drop the table and flush it out from the recyclebin also. • DROP TABLE emp_new PURGE; DROP TABLE statement UNIT-2 SQL & PLSQL 1
  • 19.
    Sinhgad Institutes 19 Views View inSQL are kind of virtual tables. A view also has rows and column as they are in real table in the database. We can create view by selecting fields fom one or more table present in the database. A view can either have all the rows of table or specific rows based on certain condition. Creating view: We can create view using create view statement. Syntax: Create view nam of view AS Select column1,column2…… From table_name1,table_name2… Where condition;
  • 20.
    Sinhgad Institutes • Rulesfor updating the views: • The view can be defined based on one and only one table • The view should not have all NOT NULL values. • The view should not be created from nested and complex queries. • The view should not have any field made out of aggregate function. • The select statement should not have DISTINCT keyword. UNIT-2 SQL & PLSQL 20
  • 21.
    Sinhgad Institutes • Thefollowing commands are used to control transactions. • COMMIT − to save the changes. • ROLLBACK − to roll back the changes. • SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK. • SET TRANSACTION − Places a name on a transaction. Transaction Control 22 UNIT-2 SQL & PLSQL
  • 22.
    Sinhgad Institutes  Transactionalcontrol commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.  The COMMIT Command  The COMMIT command is the transactional command used to save changes invoked by a transaction to the database.  The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command.  The syntax for the COMMIT command is as follows.  COMMIT; Transactional Control Commands 23 UNIT-2 SQL & PLSQL
  • 23.
    Sinhgad Institutes  Thereare two type of Operators, namely Comparison Operators and Logical Operators. These operators are used mainly in the WHERE clause, HAVING clause to filter the data to be selected.  Comparison Operators:  Comparison operators are used to compare the column data with specific values in a condition.  Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions. SQL Operators 24 UNIT-2 SQL & PLSQL
  • 24.
    Sinhgad Institutes • ComparisonOperators • = equal to • <>, != is not equal to • < less than • > greater than • >= greater than or equal to • <= less than or equal to Comparison operator. 25 UNIT-2 SQL & PLSQL
  • 25.
    Sinhgad Institutes • Thereare 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 Operators 26 UNIT-2 SQL & PLSQL
  • 26.
    Sinhgad Institutes • OR:-For the row to be selected at least one of the conditions must be true. • AND :-For a row to be selected all the specified conditions must be true. • NOT:- For a row to be selected the specified condition must be false. Logical Operators Description 27 UNIT-2 SQL & PLSQL
  • 27.
    Sinhgad Institutes • Ifyou want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR. • For example: if you want to find the names of students who are studying either Maths or Science, the query would be like, • SELECT first_name, last_name, subject FROM student_details WHERE subject = 'Maths' OR subject = 'Science' OR" Logical Operator: 28 UNIT-2 SQL & PLSQL
  • 28.
    Sinhgad Institutes • Ifyou want to select rows that must satisfy all the given conditions, you can use the logical operator, AND. • For Example: To find the names of the students between the age 10 to 15 years, the query would be like: • SELECT first_name, last_name, age FROM student_details WHERE age >= 10 AND age <= 15; AND" Logical Operator: 29 UNIT-2 SQL & PLSQL
  • 29.
    Sinhgad Institutes If youwant 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. For example: If you want to find out the names of the students who do not play football, the query would be like: SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football' NOT" Logical Operator: 30 UNIT-2 SQL & PLSQL
  • 30.
    Sinhgad Institutes  Anaggregate functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT  SQL COUNT (): This function returns the number of rows in the table that satisfies the condition specified in the WHERE condition. If the WHERE condition is not specified, then the query returns the total number of rows in the table.  For Example: If you want the number of employees in a particular department, the query would be:  SELECT COUNT (*) FROM employee WHERE dept = 'Electronics'; SQL Aggregate Functions 31 UNIT-2 SQL & PLSQL
  • 31.
    Sinhgad Institutes • SQLDISTINCT(): This function is used to select the distinct rows. • For Example: If you want to select all distinct department names from employee table, the query would be: • SELECT DISTINCT dept FROM employee; • To get the count of employees with unique name, the query would be: • SELECT COUNT (DISTINCT name) FROM employee; Cntu.. 32 UNIT-2 SQL & PLSQL
  • 32.
    Sinhgad Institutes  SQLMAX(): This function is used to get the maximum value from a column.  To get the maximum salary drawn by an employee, the query would be:  SELECT MAX (salary) FROM employee;  SQL MIN(): This function is used to get the minimum value from a column.  To get the minimum salary drawn by an employee, he query would be:  SELECT MIN (salary) FROM employee;  SQL AVG(): This function is used to get the average value of a numeric column.  To get the average salary, the query would be  SELECT AVG (salary) FROM employee;  SQL SUM(): This function is used to get the sum of a numeric column  To get the total salary given out to the employees,  SELECT SUM (salary) FROM employee; Cntu.. 33 UNIT-2 SQL & PLSQL
  • 33.
    Sinhgad Institutes  Havingclause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions.  Group functions cannot be used in WHERE Clause but can be used in HAVING clause.  SQL HAVING Clause Example  If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like;  SELECT dept, SUM (salary) FROM employee GROUP BY dept HAVING SUM (salary) > 25000  The output would be like:  dept salary  ------------- -------------  Electronics 55000  Aeronautics 35000  InfoTech 30000 SQL HAVING Clause 34 UNIT-2 SQL & PLSQL
  • 34.
    Sinhgad Institutes • WhenWHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. • Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed. Cntu.. 35 UNIT-2 SQL & PLSQL
  • 35.
  • 36.
    Sinhgad Institutes Joins • SQLJoin is used to fetch data from two or more tables, which is joined to appear as single set of data. SQL Join is used for combining column from two or more tables by using values common to both tables. 37 UNIT-2 SQL & PLSQL
  • 37.
    Sinhgad Institutes Types ofjoin The following are the types of JOIN that we can use in SQL. • Inner • Outer • Left • Right 38 UNIT-2 SQL & PLSQL
  • 38.
    Sinhgad Institutes INNER Joinor EQUI Join • This is a simple JOIN in which the result is based on matched data as per the equality condition specified in the query. • Inner Join Syntax is, • SELECT column-name-list from table-name1 INNER JOIN table-name2 WHERE table- name1.column-name = table-name2.column- name; 39 UNIT-2 SQL & PLSQL
  • 39.
    Sinhgad Institutes Example forINNER Join • The class table, ID NAME 1 abhi 2 adam 3 alex 4 anu ID Address 1 DELHI 2 MUMBAI 3 CHENNAI ID Address The class_info table, 40 UNIT-2 SQL & PLSQL
  • 40.
    Sinhgad Institutes Example forINNER Join • Inner JOIN query will be, • SELECT * from class, class_info where class.id = class_info.id; • The result table will look like, ID NAME ID Address 1 abhi 1 DELHI 2 adam 2 MUMBAI 3 alex 3 CHENNAI 41 UNIT-2 SQL & PLSQL
  • 41.
    Sinhgad Institutes 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. • Natural Join Syntax is, • SELECT * from table-name1 NATURAL JOIN table-name2; 42 UNIT-2 SQL & PLSQL
  • 42.
    Sinhgad Institutes Natural join Theclass_info table, ID NAME 1 abhi 2 adam 3 alex 4 anu The class table, ID Address 1 DELHI 2 MUMBAI 3 CHENNAI 43 UNIT-2 SQL & PLSQL
  • 43.
    Sinhgad Institutes Example ofnatural join • Natural join query will be, • SELECT * from class NATURAL JOIN class_info; • The result table will look like, ID NAME Address 1 abhi DELHI 2 adam MUMBAI 3 alex CHENNAI Note: In the above example, both the tables being joined have ID column(same name and same data type), hence the records for which value of ID matches in both the tables will be the result of Natural Join of these two tables. 4 UNIT-2 SQL &
  • 44.
    Sinhgad Institutes Outer join •Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into, • Left Outer Join • Right Outer Join • Full Outer Join 4 UNIT-2 SQL &
  • 45.
    Sinhgad Institutes Left outerjoin • 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. • Left Outer Join syntax is, • SELECT column-name-list from table-name1 LEFT OUTER JOIN table-name2 on table- name1.column-name = table-name2.column- name; (or) • select column-name-list from table-name1, table- name2 on table-name1.column-name = table- name2.column-name(+); 4 UNIT-2 SQL &
  • 46.
    Sinhgad Institutes Example ofLeft Outer Join The class table, ID NAME 1 abhi 2 adam 3 alex 4 anu 5 ashish The class_info table, ID Address 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 8 PANIPAT 4 UNIT-2 SQL &
  • 47.
    Sinhgad Institutes Example ofLeft Outer Join • Left Outer Join query will be, • SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id); • The result table will look like, ID NAME ID Address 1 abhi 1 DELHI 2 adam 2 MUMBAI 3 alex 3 CHENNAI 4 anu null null 5 ashish null null 4 UNIT-2 SQL &
  • 48.
    Sinhgad Institutes Right OuterJoin • 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. • Right Outer Join Syntax is, • select column-name-list from table- name1 RIGHT OUTER JOIN table-name2 on table-name1.column-name = table- name2.column-name; (or) • select column-name-list from table- name1, table-name2 on table- 4 UNIT-2 SQL &
  • 49.
    Sinhgad Institutes Example ofRight Outer Join The class table, ID NAME 1 abhi 2 adam 3 alex 4 anu 5 ashish The class_info table, ID Address 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 8 PANIPAT 5 UNIT-2 SQL &
  • 50.
    Sinhgad Institutes Example ofRight Outer Join • Right Outer Join query will be, • SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id); • The result table will look like, ID NAME ID Address 1 abhi 1 DELHI 2 adam 2 MUMBAI 3 alex 3 CHENNAI null null 7 NOIDA null null 8 PANIPAT 5 UNIT-2 SQL &
  • 51.
    Sinhgad Institutes Full OuterJoin • 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. • Full Outer Join Syntax is, • select column-name-list from table- name1 FULL OUTER JOIN table-name2 on table-name1.column-name = table- name2.column-name; 5 UNIT-2 SQL &
  • 52.
    Sinhgad Institutes Example ofFull outer join The class table, ID NAME 1 abhi 2 adam 3 alex 4 anu 5 ashish The class_info table, ID Address 1 DELHI 2 MUMBAI 3 CHENNAI 7 NOIDA 8 PANIPAT 5 UNIT-2 SQL &
  • 53.
    Sinhgad Institutes Example ofFull outer join • Full Outer Join query will be like, ID NAME ID Address 1 abhi 1 DELHI 2 adam 2 MUMBAI 3 alex 3 CHENNAI 4 anu null null 5 ashish null null null null 7 NOIDA null null 8 PANIPAT 5 UNIT-2 SQL &
  • 54.
    Sinhgad Institutes PL/SQL • PLSQL basically stands for "Procedural Language SQL". • This is the extension of Structured Query Language (SQL) that is used in Oracle. • Data manipulation power of SQL + Processing power of procedural language • Allows the programmers to instruct the compiler 'what to do' through SQL and 'how to do' through its procedural way. • Gives more control to the programmers by the use of loops, conditions and object oriented concepts. 5 UNIT-2 SQL &
  • 55.
    Sinhgad Institutes 1.Support forSQL Support all functionality of SQL. Efficient database handling. 2.Improved performance SQL processing:single statement PL/SQL processing: Block of statements Reduces overheads to improve performance. UNIT-2 SQL & 5 ADVANTAGE OF PL/SQL
  • 56.
    Sinhgad Institutes 3.Block structure: PL/SQLis a block structured language. Programs can be divided ino logical blocks of code. 4.Higher productivity: Procedural constructs. PL/SQL can be used with Oracle database server Oracle tools like Forms,Reports etc. 5.Portability: Application written in PL/SQL are portable to Any computer hardware Any OS Environment where Oracle RDMBS is running. UNIT-2 SQL & 5

Editor's Notes