Вы находитесь на странице: 1из 41

SQL Introduction

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

create tables and other database objects


What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data
Definition Language (DDL).
Data Definition Language (DDL)
The Data Definition Language is used to create, remove and alter the structure of database
objects. The DDL is used for table definition and can be classified into 4 categories.
(i) Create table command
(ii) Alter table command
(iii) Truncate table command
(iv) Drop table command
Data Manipulation Language (DML)
Data Manipulation Statement is used to retrieve, insert, update and delete the records in a
database. All database users will use these commands during routine operation of the database. In
this section we are describing the following Data Manipulation Statements:
Select Statement
1

Insert Statement
Update Statement
Delete Statement

Data Control Language(DCL)


Data Control Language is used to control the kind of a data access to the database and
transaction control. The owner can allow other database users access to the database objects as
per his/her direction.
Eg:
grant, revoke are used for data access control.
commit, rollback and save point are transaction control commands.

CREATE DATABASE - creates a new database


ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

Rules for table and column names


* Names can be upto 30 characters.
* Names must begin with an alphabet.
* Names cannot contain quotes.
* Names are not case sensitive.
* Names can contain characters a-z, 0-9, _, $ and #.
* Names cannot be reserve words.

CREATE TABLE Statement


It is DDL command. The CREATE TABLE statement is used to create a new database table.
Integrity Constraints like primary key, foreign key can be defined for the columns while creating
the table. The integrity constraints can be defined at column level or table level.
Syntax:
CREATE TABLE table_name
(
column_name1 data_type(width),
column_name2 data_type(width),
column_name3 data_type(width),
....
);
2

table_name - is the name of the table.


column_name1, column_name2.... is the name of the columns
datatype - is the datatype for the column like char, date, number etc.

Example
Now we want to create a table called "student" that contains five columns: Reg, Name, Dob,
Address, and Income

SQL> CREATE TABLE Student


(
Reg Number(8),
Name varchar2(20),
Dob Date,
Address varchar2(25),
Income Number(7,2)
);

"Student" table will now look like this:


Reg

Name

Dob

Address

Income

INSERT INTO statement


It is DML command. The INSERT INTO statement is used to insert new records (rows) into a
table. We can use insert into statement in following ways.
* We can insert values into the table directly by using the following syntax.
Syntax:
INSERT INTO tablename VALUES (value1,value2,....);
Example:
INSERT INTO student values (101,'Usha','03-Mar-90','Shimoga, 50000);
* We can also specify the columns for which we want to insert the data.
Syntax:
INSERT INTO tablename (column1,column2) values(value1,value2);
Example:
3

INSERT INTO student (Reg, name) VALUES (102, 'Suma');

Reg

Name

Dob

Address

Income

101

Usha

03-Mar-90

Shimoga

50000

Insert Data Only in Specified Columns


INSERT INTO Student (Reg, Name) VALUES (105, 'Ravi);
Reg

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

Constraints can be defined in two ways


1) The constraints can be specified immediately after the column definition. This is called
column-level definition.

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.

CREATE TABLE employee


( id number(5) Primary Key,
4

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.

FOREIGN KEY Constraint


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn

Sandnes

Svendson

Tove

Borgvn

Sandnes

Pettersen

Kari

Storgt

Stavanger

The "Orders" table:


O_Id

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.

create table customer(cust_no number(10) primary key,


name varchar2(50),
address varchar2(50),
city varchar2(50),
state varchar2(50),
pin number(6));
Null:
If in a record any field that is created as nullable (not having value) then oracle will replace a
null value in that column. Null value is not equivalent to zero or blank. Null values can be
inserted into the columns of any datatype.
Not Null:
The not null constraint ensures that the users always type the value for that column becomes a
mandatory column. Not null constraint can be applied at column level only.
Unique Key
Unique key constraint ensures that information in the columns is unique i.e
unique column must not be repeated across the columns.

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;

ALTER TABLE Statement


It is DDL statement. The ALTER TABLE statement is used to add, delete, or modify columns in
an existing table.

To add a column in a table, use the following syntax:


ALTER TABLE table_name ADD column_name datatype

To delete a column in a table, use the following syntax:


ALTER TABLE table_name DROP COLUMN column_name

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

ALTER TABLE Persons ADD DateOfBirth date


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

DateOfBirth

ALTER TABLE Persons DROP COLUMN DateOfBirth


P_Id LastName
FirstName Address
City
1

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

The "Persons" table:


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

SELECT LastName, FirstName FROM Persons


LastName

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.)

Syntax: SELECT column_name(s) FROM table_name WHERE column_name operator


value
Syntax: SELECT column_list FROM table-name WHERE condition;
Example: SELECT first_name, last_name FROM student_details WHERE id = 100;

Now we want to select only the persons living in the city "Sandnes" from the table above.

SELECT * FROM Persons WHERE City='Sandnes'

P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Operators Allowed in the WHERE Clause


Operator Description
=

Equal

<>

Not equal

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

BETWEEN Between an inclusive range


LIKE

Search for a pattern

IN

If you know the exact value you want to return for at least one of the columns

Note: In some versions of SQL the <> operator may be written as !=

10

The ORDER BY Clause


The ORDER BY Clause is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.

Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|


DESC
Example, "Persons" table:
P_Id

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.

SELECT * FROM Persons ORDER BY LastName

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

The GROUP BY Clause is used in conjunction with the aggregate functions to group the resultset by one or more columns.

Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name


GROUP BY column_name
Example, We have the following "Orders" table:
O_Id

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 the total sum of each customer.


SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
Customer

SUM(OrderPrice)

Hansen

2000

Nilsen

1700

Jensen

2000

SELECT dept, SUM (salary) FROM employee GROUP BY dept;

The output would be like:


dept
salary
---------------- -------------Electrical
25000
Electronics 55000
Aeronautics 35000
InfoTech
30000
12

13

The HAVING Clause


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.

Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name


[WHERE column_name operator value] GROUP BY column_name
HAVING aggregate_function(column_name) operator value
For 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
Example "Orders" table:
O_Id

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.

SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING


SUM(OrderPrice)<2000

The result-set will look like this:


14

Customer

SUM(OrderPrice)

Nilsen

1700

15

The UPDATE Statement


The UPDATE statement is used to update existing records in a table.

Syntax: UPDATE table_name SET column1=value, column2=value2,...


WHERE some_column=some_value

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!

Example, The "Persons" table:


P_Id

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:

UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem'


AND FirstName='Jakob'

The "Persons" table will now look like this:


P_Id

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

The DELETE Statement


The DELETE statement is used to delete rows in a table.

Syntax: DELETE FROM table_name WHERE some_column=some_value

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!

Example, The "Persons" table:


P_Id

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.

DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

Nilsen

Johan

Bakken 2

Stavanger

Delete All Rows


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

18

DELETE FROM table_name


Note: Be very careful when deleting records. You cannot undo this statement!

19

The LIKE Operator


The LIKE operator is used to search for a specified pattern in a column.

Syntax: SELECT column_name(s) FROM table_name WHERE column_name LIKE


pattern

Example The "Persons" table:

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

SELECT * FROM Persons WHERE City LIKE '%tav%'


P_Id

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.

SELECT * FROM Persons WHERE City NOT LIKE '%tav%'


The result-set will look like this:
P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

The IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

Syntax: SELECT column_name(s) FROM table_name WHERE column_name IN


(value1,value2,...)

Example The "Persons" table:

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

SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen');


P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

22

The BETWEEN Operator

The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.

Syntax: SELECT column_name(s)FROM table_name WHERE column_name


BETWEEN value1 AND value2
Example
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 alphabetically between "Hansen" and
"Pettersen".

SELECT * FROM Persons WHERE LastName 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

SQL> SELECT * from PRODUCTS;


Pro_ID
11
12
13
14
15

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.

Syntax: SELECT column_names FROM tbl_name


INNER JOIN tbl_name ON join_conditions
The following example takes all the records from table Client and finds the matching records in
table Product. But if no match is found then the record from table Client is not included in the
results. But if multiple results are found in table Product with the given condition then one row
will be return for each.
SQL> Select * From Client INNER JOIN Products ON Client.C_ID = Products.C_ID;
C_ID
1
2
2
3

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.

Syntax: SELECT column_names FROM tbl_name


LEFT OUTER JOIN tbl_name ON join_conditions
In the following example we are selected every row from the Client table which dont have a
match in the Products Table.
SQL> SELECT * From Client LEFT OUTER JOIN Products
ON Client.C_ID = Products.C_ID;
C_ID
1
2
2
3
4

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.

Syntax: SELECT column_names FROM tbl_name


RIGHT OUTER JOIN tbl_name ON join_conditions
In the following example we are selected every row from the Products table which dont have a
match in the Client Table.
SQL> SELECT * From Client RIGHT OUTER JOIN Products
ON Client.C_ID = Products.C_ID;
C_ID
1
2
2
3
Null

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.

TRUNCATE command operation are not transaction safe.

TRUNCATE command does not return the number of deleted rows.

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.

In the following example we truncating the Emp1 table.


mysql> select * from Emp1;
+--------+--------+--------+-----------+------+------+--------+-------+
| emp_id | f_name | l_name | title
| age | yos | salary | perks |
+--------+--------+--------+-----------+------+------+--------+-------+
| 1
| Rahul | Jain
| Manager
| 22
| 1
| 10000 | 5000 |
| 2
| Rajesh | Kumar | Developer | 25
| 2
| 20000 | 500
|
+--------+--------+--------+-----------+------+------+--------+-------+
mysql> TRUNCATE Emp1;
Query OK, 2 rows affected (0.20 sec)

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:

Aliases for columns:


SELECT first_name AS Name FROM student;
or
SELECT first_name Name FROM student;

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

Aliases for tables:


SELECT s.first_name FROM student;
In the above query, alias 's' is defined for the table student and the column first_name is selected
from the table.
Aliases is more useful when

There are more than one tables involved in a query,

Functions are used in the query,


28

The column names are big or not readable,

More than one columns are combined together

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

SQL> select * from employee order by name;


12. Display all the employee names in the ascending order of their date of joining from employee
table.
SQL> select name from employee order by doj;
13. List all the employee who are staying in Mysore from employee table
SQL> select name from employee where place = Mysore;
14. List the employee name which is located in Shimoga and Mangalore from employee table.
SQL> select name from employee where place = 'Shimoga' or Place = 'Mangalore';
15. Count the number of employees whose name start with S
SQL> select count(name) from employee where name like S%;
16. Find the total salary from employee table
SQL> select sum(salary) from employee;
17. Find the total salary taken from Commerce department
SQL> select sum(salary) from employee where dept = Commerce;
18. List Department wise total salary
SQL> select dept, sum(salary) from employee group by dept;
19. List the maximum salary from employee table
SQL> select max(salary) from employee;
20. List the department total salary more than 100000
SQL> select dept, sum(salary) from employee group by dept having sum(salary) >= 100000;
21. Replace salary Rs.50000 where salary less than 35000 from employee table
SQL> update employee set salary = 50000 where salary <=35000;
22. Change the salary Rs 20000 where designation is Lecturer from employee table.
SQL> update employee set salary = 20000 where design = 'Lecturer';
23. Change the salary of employees in addition to extra 10% from employee table.
SQL> update employee set salary = salary + salary * 10/100;
24. Delete all records whose salaries less are equal to 20000.
SQL> delete from employee where salary <= 20000;
25. Delete all records from employee table
SQL> delete from employee;
26. Write a query to undo the above delete query.
SQL> rollback;

27. Delete records where the Empno is equal to 100.


SQL> delete from employee where empno = 100 ;
28. Delete records from employee where the place venue is Shimoga.
31

SQL> delete from employee where place = 'Shimoga';


29. Delete all from employee table where salary range between 10000 to 20000
SQL> delete from employee where salary between 10000 and 20000;
30. Delete records from employee table where salary is equal to Rs.20000 and Desig ='Lecturer'
SQL> delete from employee where salary = 20000 and desig ='Lecturer';
31. Delete records from employee table where dept ='commerce' or kannada.
SQL> delete from employee where dept = 'Commerce' or Dept = 'Kannada';
32. Write a query the following statement can be delivered 'Adithya is working as Professor
since 15-12-2002' where empno is 117.
SQL> select name || ' is working as ' || desig || 'since' || doj from employee where empno =
117;
33. Write a query the column name 'name' should be displayed as employee name from the
employee table.
SQL> select name as Employee Name from employee;
34. Add a column phone_no of data type 'number' and size ='10' to the employee table.
SQL> alter table employee add(phone_no number(10));
35. Increase the size of "place" 20 to 25 in employee table.
SQL> alter table employee modify (place varchar2(25));
36. Modify the "empno" key as a primary key from employee table.
SQL> alter table employee add primary key(empno);
37. Drop the primary key of employee table.
SQL> alter table employee drop primary key;
38. Display empno, name and annual salary of each employee from employee table with a
column name "Annual Salary" on the basis of salary.
SQL> select empno as "Employee Number", name as "Employee Name", salary*12 as
"Annual salary" from employee;

32

Write a pl - sql to find the greater no among three numbers.


SQL> edit
Declare
a number;
b number;
c number;
Begin
a:=&a;
b:=&b;
c:=&c;
if a>b and a>c then
dbms_output.put_line(a||'is greater');
elsif b>a and b>c then
dbms_output.put_line(b||'is greater');
elsif c>a and c>b then
dbms_output.put_line(c||'is greater');
end if;
end;
SQL> /

Program to calculate Factorial of number.


SQL> edit
declare
v_num number :=#
fact number :=1;
begin
for i in 1..v_num
loop
fact:=fact*i;
end loop;
dbms_output.put_line('fact of '||v_num||' is '||fact);
end;
SQL> /

Program to calculate Even or odd Number


SQL> edit
33

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;

1. PL/SQL Program to find average of three numbers


Declare
a
Number;
b
Number;
c
Number;
avgr
Number;
Begin
a:= &a;
b:= &b;
c:= &c;
avgr:= (a+b+c)/3;
dbms_output.put_line ('Average of number is: ' || avgr);
End;
2. PL/SQL Program to find area of circle
Declare
34

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

5. PL/SQL Program to find area of triangle


Declare
b number;
h number;
area number;
begin
b:=&b;
h :=&h;
area:=1/2*b*h;
dbms_output.put_line('Area of triangle is : ' || area);
end;
6. PL/SQL Program given number is even or odd
Declare
num number;
Begin
num:=&num;
if num mod 2 =0 then
dbms_output.put_line('Accepted Number '||num||' is even');
else
dbms_output.put_line('Accepted Number '||num||' is odd');
end if;
End;
7. PL/SQL Program Leap year
Declare
y number;
Begin
y:=&y;
if y mod 4 =0 then
dbms_output.put_line('Year '|| y ||' leap year');
else
dbms_output.put_line('Year '|| y ||' not leap year');
end if;
End;
8. PL/SQL Program biggest 3 number
Declare
A number;
B number;
C number;
Big number;
Begin
a :=&a;
b :=&b;
c :=&c;
36

if a > b and a > c then


big :=a;
else if b > a and b > c then
big:=b;
else
big:=c;
end if;
end if;
dbms_output.put_line('Biggest number is '||big);
End;
9. PL/SQL Program Commission of salesmen
Declare
n char(10):=Mr. DGS;
sales number;
com number;
tot number;
Begin
sales:=&sales;
if sales >=50000 then
com:=sales*5/100;
elsif sales >=25000 then
com:=sales*3/100;
elsif sales >=10000 then
com:=sales*1/100;
else
com:=0;
end if;
dbms_output.put_line('Salesmen Name

'|| n );

dbms_output.put_line('Sales is '|| sales );


dbms_output.put_line('Commission is '|| com );
End;
10. PL/SQL program to print 1 to 10 number using FOR loop
declare
num number(3);
begin
dbms_output.put_line(Numbers are);
for num in 1..10 loop
dbms_output.put_line(num);
end loop;
end;
37

11. Program to print 1 to 10 in reverse order using FOR loop.


declare
num number(3);
begin
for num in REVERSE 1..10 loop
dbms_output.put_line(num);
end loop;
end;
12. PL/SQL program to generate Fibonacci series.
declare
f1 number(3);
f2 number(3);
f3 number(3);
num number(3);
begin
f1:=0;
f2:=1;
f3:=0;
num:=1;
while num<=10
loop
dbms_output.put_line(f3);
f1 :=f2;
f2:=f3;
f3:=f1+f2;
num:=num+1;
end loop;
end;
13. Write a PL/SQL to find the greater no among three
numbers.
Declare
a number;
b number;
c number;
Begin
a:=&a;
b:=&b;
c:=&c;
if a>b and a>c then
dbms_output.put_line(a||'is greater');
elsif b>a and b>c then
dbms_output.put_line(b||'is greater');
elsif c>a and c>b then
38

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 Language (TCL)

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.

TCL Statements available in Oracle are


COMMIT

:Make changes done in transaction permanent.

ROLLBACK :Rollbacks the state of database to the last commit point.


SAVEPOINT :Use to specify a point in transaction to which later you can rollback.

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;

/* undo the changes */

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

Вам также может понравиться