SQL Chapter 3
SQL Chapter 3
SQL Chapter 3
SQL stands for Structured Query Language. It is a query language used for accessing and
modifying information in the database. IBM first developed SQL in 1970s. Also it is an
ANSI/ISO standard. It has become a Standard Universal Language used by most of the
relational database management systems (RDBMS). Some of the RDBMS systems are:
Oracle, Microsoft SQL server, Sybase etc.
Few of the SQL commands used in SQL programming are SELECT Statement, UPDATE
Statement, INSERT INTO Statement, DELETE Statement, WHERE Clause, ORDER BY
Clause, GROUP BY Clause, ORDER Clause, Joins, GROUP Functions etc.
In a simple manner, SQL is a non-procedural, English-like language that processes data in
groups of records rather than one record at a time. Few functions of SQL are:
store data
modify data
retrieve data
delete data
Insert Statement
Update Statement
Delete Statement
Example
Now we want to create a table called "student" that contains five columns: Reg, Name, Dob,
Address, and Income
Name
Dob
Address
Income
Reg
Name
Dob
Address
Income
101
Usha
03-Mar-90
Shimoga
50000
Name
Dob
Address
Income
101
Usha
03-Mar-90
Shimoga
50000
104
Ravi
Integrity Constraints
Constraints are rules that are used to control the invalid data entry in a column. Integrity
Constraints are used to apply business rules for the database tables. The constraints available in
SQL are Primary key, Foreign Key, Null/Not Null, Unique, Check, Default
2) The constraints can be specified after all the columns are defined. This is called table-level
definition.
Primary key:
The Primary key constraint uniquely identifies each record in a database table. Primary keys
must contain unique values. A primary key column cannot contain NULL values. Each table
should have a primary key, and each table can have only ONE primary key.
name varchar2(20),
dept varchar2(20),
age number(2),
salary number(10),
location varchar2(20)
);
Foreign key :
This constraint identifies any column referencing the PRIMARY KEY in another table. It
establishes a relationship between two columns in the same table or between different tables.
For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the
table which it is referring. One or more columns can be defined as Foreign key.
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn
Sandnes
Svendson
Tove
Borgvn
Sandnes
Pettersen
Kari
Storgt
Stavanger
OrderNo
P_Id
77895
44678
22456
24562
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
5
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
value entered in
Check
Check constraint ensure that when data is entered, the data in the column is limited to specific
values.
eg: category varchar2(5) check(category in ('SC','ST'));
Default Constraint:
At the time of table creation a default value can be assigned to a column. When the user is
entering the values and leaves this column empty the oracle will automatically load this column
with the default value. The datatype of the default value should match the datatype of the
column.
eg: Age Number(3) Default 21;
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name MODIFY COLUMN column_name datatype
Ex:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
DateOfBirth
Hansen
Ola
Timoteivn 10
Sandnes
SELECT Statement
It is DML statement. The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s) FROM table_name
SELECT * FROM table_name
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
Now we want to select all the columns from the "Persons" table.
SELECT * FROM Persons
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Aggregate Functions
Group 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
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.
Ex: If you want the number of employees in a particular department, the query would be:
SELECT COUNT (*) FROM employee WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the
form:
SELECT COUNT (*) FROM employee;
DISTINCT: This function is used to select the distinct rows.
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;
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;
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;
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;
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;
SQL Clauses
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
WHERE clause can be used along with SELECT, DELETE, UPDATE statements (The WHERE
clause is used to filter records.)
Now we want to select only the persons living in the city "Sandnes" from the table above.
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Equal
<>
Not equal
>
Greater than
<
Less than
>=
<=
IN
If you know the exact value you want to return for at least one of the columns
10
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Tom
Vingvn 23
Stavanger
Now we want to select all the persons from the table above, however, we want to sort the persons
by their last name.
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Nilsen
Tom
Vingvn 23
Stavanger
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
11
The GROUP BY Clause is used in conjunction with the aggregate functions to group the resultset by one or more columns.
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
SUM(OrderPrice)
Hansen
2000
Nilsen
1700
Jensen
2000
13
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
Now we want to find if any of the customers have a total order of less than 2000.
Customer
SUM(OrderPrice)
Nilsen
1700
15
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Nissestien 67
Sandnes
16
17
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Nissestien 67
Sandnes
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
18
19
E_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10 Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons living in a city that starts with "s" from the table.
SELECT * FROM Persons WHERE City LIKE 's%'
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and
after the pattern.
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.
SELECT * FROM Persons WHERE City LIKE '%s'
Next, we want to select the persons living in a city that contains the pattern "tav" from the
"Persons" table.
20
LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
It is also possible to select the persons living in a city that does NOT contain the pattern "tav"
from the "Persons" table, by using the NOT keyword.
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
The IN Operator
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen".
21
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
22
The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons with a last name alphabetically between "Hansen" and
"Pettersen".
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Example:
To display the persons outside the range in the previous example, use NOT BETWEEN:
SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
P_Id
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
23
DROP Table Statement :DROP TABLE statement is used to remove one or more tables in the
database
Syntax: DROP TABLE tb_name
24
SQL Joins
A join is a SQL query that is used to select the data from more than one table. When you define
multiple tables in the FROM clause of a query the SQL performs a join that linking the rows
from multiple tables together.
Types of Joins:
INNER Joins
OUTER Joins
We are going to describe you the Join with the help of following two tables:
SQL> SELECT * from CLIENT;
C_ID
1
2
3
4
Name
Adithya Ltd
V K Associate
R K India
Param Infotech
City
Mangalore
Mysore
Banglore
Shimoga
Pro_Detail
Monitor
Camera
Hard Disk
RAM
CPU
C_ID
1
2
2
3
5
INNER Joins
The INNER join is considered as the default Join type. Inner join returns the column values from
one row of a table combined with the column values from one row of another table that satisfy
the search condition for the join.
Name
Adithya Ltd
V K Associate
V K Associate
R K India
City
Mangalore
Mysore
Mysore
Banglore
Prod_ID
11
12
13
14
Pro_Detail
Monitor
Camera
Hard disk
RAM
C_ID
1
2
2
3
25
OUTER Joins: Outer Join are divided in two types : Left Outer Join, Right Outer Join
Left Outer Join
LEFT OUTER Join is used to returns all the rows that returned by an INNER JOIN plus all the
rows from first table that did not match with any row from the second table but with the NULL
values for each column from second table.
Name
Adithya Ltd
V K Associate
V K Associate
R K India
Param Infotech
City
Mangalore
Mysore
Mysore
Banglore
Shimoga
Prod_ID
11
12
13
14
Null
Pro_Detail
Monitor
Camera
Hard disk
RAM
C_ID
1
2
2
3
Null
In the result of LEFT OUTER Join "Param Infotech" is included even though it has no rows in
the Products table.
Right Outer Join
RIGHT OUTER Join is same as the LEFT OUTER JOIN. But RIGHT OUTER Join is used to
returns all the rows that returned by an INNER Join plus all the rows from second table that did
not match with any row from the first table but with the NULL values for each column from first
table.
Name
Adithya Ltd
V K Associate
V K Associate
R K India
City
Mangalore
Mysore
Mysore
Banglore
Prod_ID
11
12
13
14
15
Pro_Detail
Monitor
Camera
Hard disk
RAM
CPU
C_ID
1
2
2
3
5
26
TRUNCATE Statement
TRUNCATE Statement is also used to empty the table completely.
Syntax: TRUNCATE tb_name;
Logically TRUNCATE Statement is same as DELETE Statement, which deletes all rows. But practically
they have some differences :
TRUNCATE command drop the table and recreate the definition of table, which is much faster
than deleting the rows one by one.
If table format file tbl_name.frm is valid, then the table can be recreated if its empty by the
TRUNCATE command even if the data or index files have become corrupted.
27
SQL Alias You can give a table or a column another name by using an alias. This can be a good
thing to do if you have very long or complex table names or column names.
SQL supports two types of alias which are known as column alias and table alias.
For Example: To select the first name of all the students, the query would be like:
In the above query, the column first_name is given a alias as 'name'. So when the result is
displayed the column name appears as 'Name' instead of 'first_name'.
Output:
Name
---------Rahul
Anjali
Priya Chandra
29
SQL QUERY
1. Create a table Employee' with the following fields
Empno
number
5(primary key)
name
varchar2
20(not null)
Dept
varchar2
15
Doj
date
salary
number
(9,2)
comm
number
(7,2)
SQL> CREATE TABLE Employee
(
Empno
number(5) primary key,
Name
varchar2(20) not null,
Dept
varchar2(15),
Doj
date,
Desig
varchar2(15),
Place
varchar2(15),
Salary
number(8,2),
);
2. Describe the table Employee
SQL> Desc Emp;
3. Insert data into the table Employee'
Insert into employee values (001, 'Adithya, 'Commerce', '15-Dec-02', Lecturer, Shimoga,
35000.00);
4. Display all records from Employee table
SQL> select * from employee;
5. Display name, desig, place and salary from employee table
SQL> select name, desig, place, salary from employee;
6. Display all records who have a salary less than Rs.30000 from employee table
SQL> select * from employee where salary < 30000;
7. Display all the record whose name starts with the letter 'K' from employee table.
SQL> select * from employee where name like 'K%';
8. Display all records of the employee working in department Commerce.
SQL> select * from employee where dept ='Commerce;
9. List all employee whose name start with 'A' and end with 'd' from employee table.
SQl> select * from employee where name like 'A%d';
10. List all Professors in the department Kannada with salary more than 50000 from employee
table.
SQL> select * from employee where (Desig = 'Professor and Dept = 'Kannada') and salary
>=50000;
11. Display all the employee names in the ascending order from employee table.
30
32
declare
n number;
r number :=1;
begin
n:=&number;
for r in 1..n
loop
if mod(r,2)=0 then
dbms_output.put_line('Even No :' || r);
end if;
end loop;
end;
SQL> /
Multiplication Table
DECLARE
n number := &n;
prod number;
BEGIN
for i in 1..10 loop
prod := n * i;
dbms_output.put_line(n||' * '||lpad(i,2,' ')
||' = '||lpad(prod,3,' '));
end loop;
END;
r
Number;
p
Number:= 3.142;
area Number;
cir
Number;
Begin
r := &r;
area := p*r*r;
cir := 2*p*r;
dbms_output.put_line ('Area of circle is : ' || area);
dbms_output.put_line ('Circumference of circle is : ' || cir);
End;
3. PL/SQL Program to simple interest
Declare
p number;
r number;
t number;
si number;
tot number;
begin
p:=&p;
r:=&r;
t:=&t;
si :=(p*r*t)/100;
tot:=si+p;
dbms_output.put_line('Simple interest is : ' || si);
dbms_output.put_line('Total amount is : ' || tot);
end;
4. PL/SQL Program to compound interest
Declare
p number;
r number;
t number;
ci number;
tot number;
begin
p:=&p;
r:=&r;
t:=&t;
ci :=p*(1+r/100)**t-p;
tot:=ci+p;
dbms_output.put_line('Compound interest is : ' || ci);
dbms_output.put_line('Total amount is : ' || tot);
end;
35
'|| n );
dbms_output.put_line(c||'is greater');
end if;
end;
14. PL/SQL Program to calculate Factorial of number
Declare
num number :=#
fact number :=1;
begin
for i in 1..v_num
loop
fact:=fact*i;
end loop;
dbms_output.put_line('fact of '||num||' is '||fact);
end;
15. Program to calculate Even or odd Number
declare
n number;
r number :=1;
begin
n:=&number;
for r in 1..n
loop
if mod(r,2)=0 then
dbms_output.put_line('Even No :' || r);
end if;
end loop;
end;
16. Multiplication Table
DECLARE
n number := &n;
prod number;
BEGIN
for i in 1..10 loop
prod := n * i;
dbms_output.put_line(n||' * '||lpad(i,2,' ') ||' = '||lpad(prod,3,' '));
end loop;
END;
39
Transaction control statements manage changes made by DML statements. A transaction is a set
of SQL statements which Oracle treats as a Single Unit. i.e. all the statements should execute
successfully or none of the statements should execute.
To control transactions Oracle does not made permanent any DML statements unless you ommit
it. If you dont commit the transaction and power goes off or system crashes then the transaction
is roll backed.
COMMIT
To make the changes done in a transaction permanent.
Example
INSERT INTO EMP VALUES (101,ABID,2300);
Commit;
ROLLBACK
To rollback the changes done in a transaction give rollback statement. Rollback restore the state
of the database to the last commit point.
40
Example :
DELETE FROM EMP;
ROLLBACK;
SAVEPOINT
Specify a point in a transaction to which later you can roll back.
Example
insert into emp values (109,Sami,3000);
savepoint a;
Roolback to a;
41