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

Introduction to SQL

In this section we will explain some of the basic terminologies which will be required to
learn SQL. We will give an overview of what SQL is and what does it do etc.

What is Database?

A database is an organized collection of data, that is useful to us. The data inside in a
database can be modified, deleted or new data can be added. They are stored in the form
of records as shown in the table below:

Emp_id Emp_name Age Salary


1101 Ana 28 15000

The above table shows a single record. The columns-Emp_id, Emp_name, Age, Salary are
the fields or attributes, while the row containing the corresponding the values-1101, Ana,
28, 15000 is a single record.

There can be a number of records in a table and number of tables in a database. The
tables in a database are related to each other through one/more attributes/fields.

A Database is diagrammatically shown below. It consists of two tables-Employee and


Emp_INFO. While Employee stores information regarding an employee's ID, dept and
salary, the table Emp_INFO stores ID, name and date of join of the employee. The
common link between the table is established by the field Emp-ID.

SQL Database Tables

As explained above, database is nothing but a collection of inter-related tables. A table


consists of rows and columns. Rows are the records stored whereas columns are attributes
or fields. Each table is identified with a name e.g, Employee (Emp_id, Emp_name, Age,
Salary), suggesting Table named Employee has four fields-Emp_id, Emp_name, Age,
Salary.

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14000

What is Dbms?

DBMS (DataBase Management System) consists of inter-related data and methods to


manipulate those data. It is designed to help users in managing data in a database
efficiently.

A database management system (DBMS), sometimes also called as a database manager,


is a program that lets one or more computer users create and access data in a database.
The DBMS manages user requests, as well as requests from other programs, so that users
and other programs are not bothered to understand where the data is physically located
on storage media and, in a multi-user system, who else is also be accessing the data. In
handling user requests, the DBMS takes care that integrity of the data (that is, making
sure it continues to be accessible and is consistently organized as intended) and security
(making sure only those with access privileges can access the data) remain intact. The
most typical DBMS is a Relational DataBase Management System (RDBMS).

A DBMS is usually an inherent part of a database product. Some of the popular DBMSs
(actually they are all Relational DBMS) are-Oracle's line of database management
products, Sybase's products, Microsoft's SQL Server. On PCs, Microsoft Access is a popular
example of a single-or small-group user DBMS.

Basics

What is SQL

SQL, an acronym for Structured Query Language, is an ANSI (American National Standard
Institute) standard computer language. SQL statements are used for accessing and
manipulating data from these database systems. It works with RDBMS like Oracle,
Sybase, Microsoft SQL Server, Access, Ingres etc.

SQL:

· runs queries against a database.


· retrieves data from database.
· inserts new records into a database.
· updates records in a database.
· deletes records from a database.
· creates/deletes tables in a database.
· alters the table structure in a database.
· is easy to learn and understand.

What is a Query?

A Query is a statement containing SQL commands and reserved words, which when
executed returns a set of desired records known as result set. Actually queries are used as
an interface to manipulate a database and its contents.

For Example:

SELECT column_name FROM table_name

In the above statement, SELECT is a command to extract or select a record(s) from a


column in a database table.

Data Type

A data type is a set of data with values having predefined characteristics. Each languge
has its own data types. Usually, a limited number of such data types come built into a
language. The language usually specifies the range of values for a given data type, how
the values are processed by the computer, and how they are stored. Some data types in
SQL are: char, number, date etc.

The various Data Types along with their description are shown below:
Data Type Description
char(size) Holds fixed-length character string. Size is specified in parenthesis. Max
255 bytes.
varchar(size) Holds variable-length character string. Max size is specified in
parenthesis.
number(size) Holds Number value with a max number digits specified in parenthesis.
Date Holds a Date value.
number(size,d Holds a Number value with a maximum number of digits of "size" total,
) with a maximum number of "d" digits to the right of the decimal.

Operators

Oracle provides a set of built-in operators-Arithmetic Operators (+, -, *, ), Comparison


Operators ( =, >, <), Logical operators (NOT, AND, OR). These operators take as input
one or more arguments (operands) and return a result.

The various Operators along with their description are shown below in tabular form:

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
LIKE String comparison test
AND Logical And returns TRUE when both the specified conditions are true
OR Logical Or returns TRUE when atleast one of the specified conditions is true
NOT Logical Not returns TRUE when none one of the specified conditions is true

Data Definition Language (DDL)

SQL can be termed as a DDL i.e. Data Definition Language. The DDL part in SQL enables it
to create/delete/alter a database table. Through this DDL feature indexes, links between
tables as well as constraints can be defined.
The following statements/commands consist of DDL portion of SQL:

Create Table : creates a new database table.


Alter Table : alters a database table.
Drop Table : deletes a database table.
Create Index : creates an index.
Drop Index : deletes an index.

Data Manipulation Language (DML)


SQL can be termed as DML i.e. Data Manipulation Language. Database is manipulated so
as to insert, update and delete records.

The following statements/commands consist of DML portion of SQL:

Select : Retrieves desired records from a database table.


Update : Updates/modifies records in a database table.
Delete : Deletes records from a database table.
Insert into : Inserts new records into a database table.

Data Control Language (DCL)

SQL can be termed as DCL i.e. Data Control Language. The DCL part of SQL are those
statements that control the behaviour of the database objects.

The various commands covering the DCL part of SQL are:

Savepoint : This statement is used to identify a point in a transaction to which you


can later roll back. This saves transactional changes upto a point
called savepoint.
Rollback : This statement rolls back a transaction to the named savepoint.
Modifications that the transaction made to rows after the savepoint
was set, are undone in the rollback.
Commit : This statement saves changes made due to a transaction.

Semicolon after SQL Statements

Semicolon(;) is the standard way to separate SQL statements from one another in
database systems that allow more than one SQL statement to be executed in the same
call to the server.

Note: We would abstain from using semicolon after each SQL statement in this tutorial.
However it is necessary to execute a query.

SQL Commands
SQL commands are used by Access, Oracle, MS SQL server etc. In short, if you use
databases, be it in VB, FoxPro, Access or anything else, at some stage you will need to
use SQL. SQL gives you complete control over databases, creating, deleting, modifying,
adding, reading, sorting, querying etc.

In this section, we will cover the SQL Commands which have been classified as:

DML Commands To insert/update/delete records from a database table.

DDL Commands To create/alter/delete a table.

DCL Commands To control the behavior of the database objects.

Nested Queries To make compound queries in which a subquery resides in


a parent query.

Grant & Revoke To give or take back privileges on database objects.


Data Manipulation Language
In this section we will be using commands that would enable us to Insert, Update or
Delete records in a database table.

The commands have been described with appropriate examples one at a time, covering all
the clauses.

SQL Select

The Select statement is used to retrieve desired records from a database table.

Syntax:

SELECT column_name(s) FROM table_name

TO SELECT ONE/SOME COLUMNS.

Example:

SELECT Emp_name FROM Employee

The above query on running will return a set of desired records (result set) from table
Employee as shown below:

EMPLOYEE Table

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14000

Result Set

Emp_name
Ana
Joe
Jack

Now lets take up an example where we want to view values from two column as discussed
in the query below:

SELECT Emp_name, Age FROM Employee

the above query will yield the following result set from the table "Employee".

Emp_name Age
Ana 28
Joe 23
Jack 25

Thus we can include more one columns using comma to view values from more than one
table.

To SELECT ALL COLUMNS.

Example:

SELECT * FROM Employee

The above query on running will return the following set of records.

Result Set

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14500

The Distinct Keyword

Distinct keyword is used to retrieve values that are distinct or non-repetitive. The SQL
Select retrieves values from database table which may be repetitive. Adding the word
Distinct to Select, we can get rid of this problem.

Syntax:

SELECT DISTINCT column_name(s) FROM table_name

Example:

SELECT S_name FROM Student.

The above query on the following database table Student:

S_name S_age Subjects


Renee 10 Physics
James 12 Maths
Renee 10 Computers

Will yield the result-set

S_name
Renee
James
Renee

Note that "Renee" is listed twice in the list.

To get rid of the above problem we use Distinct keyword.

Example:

SELECT DISTINCT S_name FROM Student

The above query will give the following result set:

S_name
Renee
James

Note "Renee" is listed only once this time.

The Where Clause

We might want to retrieve records which satisfy a particular condition. For example, we
want to retrieve Employee names from database table Employee with salaries above
14000. To do this, we make use of the clause Where. Thus Where clause is used to specify
a selection criterion.

Syntax:

SELECT column_name(s) FROM table_name

WHERE condition

The operators that can be used to specify the condition are listed below:

Comparison Operators

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
LIKE String comparison test

Example:
To get the names of all the employees with salaries above 14000 from table Employee

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14500

we key in the following query:

SELECT Emp_name FROM Employee

WHERE Salary > 14000

The query will retrieve the following result:

Emp_name
Ana
Jack

Lets take another example involving text values.

SELECT * FROM Employee

WHERE Emp_name='Ana'

the above query will produce the result set as shown below:

Emp_id Emp_name Age Salary


1101 Ana 28 15000

The Like condition can be used to search for a particular pattern in a column in a database
table.

Syntax:

SELECT column_name FROM table_name

WHERE column_name LIKE pattern

Example:

The following SQL statement will display Employee names beginning with alphabet 'A'

SELECT Emp_name FROM Employee

WHERE Emp_name LIKE 'A%'


The following SQL statement will display Employee names ending with alphabet 'a'

SELECT Emp_name FROM Employee

WHERE Emp_name LIKE '%a'

Now Suppose, we want to retrieve all information about employees from "Employee" table
where the second character of names is 'n'. For that, we key in the following query:

SELECT Emp_name FROM Employee

WHERE Emp_name LIKE '%_n'

SQL And & Or

AND & OR are logical operators and are used to join two or more single conditions. As we
have seen, WHERE clause is used to select data conditionally. But it has the limitation of
specifying single condition only. Hence AND & OR are used to specify compound conditions
(compound conditions are made by joining two or more single conditions using AND or
OR).

AND operator displays a record if All single conditions are True. OR operator displays a
record if Any of the single conditions are True
Syntax:

SELECT column_name FROM table_name

WHERE condition1 AND/OR condition2

Example:

SELECT * FROM Employee

WHERE Emp_name LIKE 'A%' AND Salary > 14000

Result Set

Emp_id Emp_name Age Salary


1101 Ana 28 15000

Notice in the output above that only one record is displayed in the result-set because that
is the only record which satisfies both the specified condition.

Example:

SELECT * FROM Employee

WHERE Emp_name LIKE 'A%' OR Salary > 14000

Result set
Emp_id Emp_name Age Salary
1101 Ana 28 15000
1103 Jack 25 14500

Notice in the output above that 2 records are displayed in the result-set because both the
records satisfy atleast one out of the two specified condition.

Lets take up another example. Suppose, we want to retrieve all information about
employees from "Employee" table where either the second character of names is 'o' or
name is 3 characters long and first two characters is 'An'. For that, we key in the following
query:

SELECT Emp_name FROM Employee

WHERE Emp_name LIKE '%_o' OR Emp_name LIKE '%An_'

SQL Not

Sql statements using NOT will process all rows in a table and display the result only when
none of the conditions specified usong the NOT operator are used.

Syntax:

SELECT column_name FROM table_name

WHERE NOT condition

Example:

SELECT * FROM Employee

WHERE NOT (Emp_name LIKE 'A%')

The above query shows the following output:

Emp_id Emp_name Age Salary


1102 Joe 23 13500
1103 Jack 25 14500

Notice in the above output the details of 'Ana' are missing.

SQL In & Between


The IN keyword is used to test whether a value(s) is present in the list of values specified
after the keyword IN.

Syntax:

SELECT column_name FROM table_name

WHERE column_name IN ( value1, value2,...')

Example:

SELECT Emp_id, Emp_name FROM Employee

WHERE Emp_name IN ( 'Ana', 'Joe')

The above query will select Emp_id and Emp_name from the Employee table where
Emp_name is equal to either: Ana or Joe. Thus the result displayed by this query is shown
below:

Emp_id Emp_name
1101 Ana
1102 Joe

While IN is used to select a value present in the list, NOT IN is used to exclude the rows
from the list mentioned.
For example, the following query:

SELECT Emp_id, Emp_name FROM Employee

WHERE Emp_name NOT IN ( 'Ana', 'Joe')

will give the following result set:

Emp_id Emp_name
1103 Jack

The BETWEEN keyword is used to test whether or not a value is present between the two
values mentioned in the query followed by the keyword BETWEEN.

Syntax:

SELECT column_name(s) FROM table_name

WHERE column_name BETWEEN value1 AND value2

Example:

SELECT Emp_id, Emp_name, Age FROM Employee

WHERE Age BETWEEN 23 AND 26


This query will select the "Emp_id", "Emp_name", "Age" from "Employee" table where the
age lies between 23 and 26 ( including 23 and 26) as shown below:

Emp_id Emp_name Age


1102 Joe 23
1103 Jack 25

While BETWEEN is used to retrieve values present in the specified range, NOT BETWEEN is
used to exclude values between the specified range.

For example, suppose we want to select the "Emp_id", "Emp_name" and "Age" from
"Employee" table where age does not lie between 23 and 26 (including 23 and 26). We
type in the following query for that:

SELECT Emp_id, Emp_name, Age FROM Employee

WHERE age NOT BETWEEN 23 AND 26

The above query gives the following result set

Emp_id Emp_name Age


1101 Ana 28

Order By Clause

ORDER BY is used to get the result in the sorted manner. Unless Explicitly stated, the
order by clause sorts the result in ascending order.

Syntax:

SELECT column_name(s) FROM table_name

ORDER BY column_name

Example:

To display the names in alphabetical order

SELECT Emp_id, Emp_name FROM Employee

ORDER BY Emp_name

Result Set

Emp_id Emp_name
1101 Ana
1103 Jack
1102 Joe

Example:

To display the names in reverse alphabetical order

SELECT Emp_id, Emp_name FROM Employee

ORDER BY Emp_name DESC

Result Set

Emp_id Emp_name
1102 Joe
1103 Jack
1101 Ana

Example:

Consider the table Student as shown below:

S_name S_age Subjects


Renee 10 Physics
James 12 Maths
Renee 10 Computers

Now suppose we want to display names in reverse alphabetical order and subjects in
alphabetical order. To do so, we key in

SELECT S_name, Subjects FROM Student

ORDER BY S_name DESC ,Subjects ASC

the above query will yield the following result set:

S_name Sujects
Renee Computers
Renee Physics
James Maths

SQL Insert
INSERT INTO statement allows a new row to be inserted or added into a database table.
The values that are mentioned and to be inserted will be fed into the rows and they will
match up with the names of the columns that are specified correspondingly.

Syntax:

INSERT INTO table_name

VALUES (value1, value2,...)

The column names can be explicitly specified for which data is to be inserted as shown
below:

INSERT INTO table_name (column_name1, column_name2,...)

VALUES (value1, value2,...)

Example:

INSERT INTO Employee VALUES ( 1104, 'Wasim', 29, 15000)

will result in

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14500
1104 Wasim 29 15000

Lets take another case in which the columns for which data is to be inserted are specified.

Example:

INSERT INTO Employee (Emp_id, Emp_name, Salary)

VALUES ( 1105, 'Rita', 13500)

will result in

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500

1103 Jack 25 14500


1104 Wasim 29 15000
1105 Rita 13500
In addition to inserting one row/record into a table at a time, we can also insert data into
a table that exists in another table. This can be done as:

Syntax:

INSERT INTO table1

SELECT column_name(s)

FROM table2

For example, suppose we want to insert data into table "Supply" from various columns in
table "Client" as:

INSERT INTO Supply

SELECT client_id, name, address, city, remarks

FROM Client

On executing the above query, all values from the columns- "client_id", "name",
"address", "city", "remarks", will be inserted into respective columns of table "Supply".

We can add condition i.e. using "WHERE" clause. For example, suppose we want to insert
data into table "Supply" from various columns in table "Client" where client_id contains
the value '1101CS'. We key in the following query for that:

INSERT INTO Supply

SELECT client_id, name, address, city, remarks

FROM Client

WHERE client_id = '1101CS'

SQL Update

Update statement is used to edit or update data in the table.

Syntax:

UPDATE table_name

SET column_name = new_value

WHERE column_name = old_value

Example:

UPDATE Employee

SET Age = 28
WHERE Emp_id = 1105

The above query will result in

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500

1103 Jack 25 14500


1104 Wasim 29 15000
1105 Rita 28 13500

We can also update multiple columns in a row at a time.

Example:

UPDATE Employee

SET Age=26, Emp_name = 'Waqar'

WHERE Emp_id = 1104

The above query will result in

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500

1103 Jack 25 14500


1104 Waqar 26 15000
1105 Rita 28 13500

SQL Delete

The SQL delete is used to delete rows from a database table.

Syntax:

DELETE FROM table_name

WHERE column_name = some_value

Example:

DELETE FROM Employee

WHERE Emp_id = 1104


The above query results in

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500

1103 Jack 25 14500


1105 Rita 28 13500

It is also possible to delete all the records in a database table at one go, without deleting
the table. This implies that although all the records will be deleted, the table structure,
fields and indexes will continue to exist. This can be done by the following SQL statement:

DELETE FROM table_name

or

DELETE * FROM table_name


Data Defination Language
In this section we will be using commands that would enable us to CREATE, ALTER or
DROP a database, table, index etc. This section also describes SELECT INTO which is used
create a back up of a database table.

The commands have been described with appropriate example one at a time covering all
the clauses.

SQL Create

Create a Database

CREATE statement can be used to create a database. A database is nothing but a


collection of tables which are related to each other. The inter-relation amongst the tables
in a database is created by attributes/fields which may be common to more than one
tables.

Syntax:

CREATE DATABASE database_name

Create Table

With CREATE TABLE, a new table can be created. A table can be considered as a basic
structure within which data is stored. It consists of rows and columns. A row represents a
single record while a column represents attributes/fields which can be thought of as one of
the components contributing to make a record. While creating a table, data types have to
be mentioned for each field.

Here are the most common Data Types:


Data Type Description
char(size) Holds fixed-length character string. Size is specified in parenthesis. Max
255 bytes.
varchar(size) Holds variable-length character string. Max size is specified in
parenthesis.
number(size) Holds Number value with a max number digits specified in parenthesis.
Date Holds a Date value.
number(size,d Holds a Number value with a maximum number of digits of "size" total,
) with a maximum number of "d" digits to the right of the decimal.

Syntax:

CREATE TABLE table_name (column_name1 data_type, column_name2 data_type, ...)

Example:

CREATE TABLE Details (First_name varchar(50), Surname varchar(50), Address char(50),


DOB date)

The above statement creates an empty table (containing no records) named Details
having fields-first_name, Surname, Address and DOB.

Null Value Concept

Sometimes cases arise when records in database table do not have values for every field
either because of incomplete information during data entry or the field is not applicable for
each case. In such cases, a NULL value is placed in the column in the absence of a user
defined value and if the column created was NULLABLE i.e, Null values are allowed.

Null values are different from blank or a zero and can be inserted into columns of any data
type.

Not Null Constraint

When a column is defined as NOT NULL, then a value must be entered into that column so
as to store it into the database table.

Syntax:

CREATE TABLE table_name (column_name data_type(size) NOT NULL)

Example:

CREATE TABLE Details (First_name varchar(50) NOT NULL, Surname varchar(50), Address
char(50), DOB date)

The above query results in creation of a database table named Details with the fields-
First_name, Surname, Address, DOB. The Field - First_Name should contain a value for
each record and should not be left blank.
For finding out table(s) created by a user (the tables which user has access to) is:

SELECT * FROM TAB

The above query will display all those tables created by that user and/or has access to:

TNAME TABTYPE
Employee Table
Details Table

For finding out column details of a table we use DESCRIBE (or DESC).

Syntax:

DESCRIBE table_name

For example, to view the column details of the table "Details" that we created above, we
key in:

DESCRIBE Details

the above query will yield:

Name TYPE NULL?


First_name Varchar(50) NOT NULL
Surname Varchar(50)
Address Varchar(50)
DOB DATE

Note: DESCRIBE & SELECT statements are not a part of Data Definition Language.

Create Index

CREATE INDEX is used to create index over one or more columns in a table. Each index
has specific name. They are created to to locate rows (records) quickly and efficiently and
thus speed up the queries.

Syntax:

CREATE INDEX index_name

ON table_name (column_name)

Example:

CREATE INDEX Emp_index


ON Employee (Emp_name)

The above statement creates an index named Emp_index on the field Emp_name of table
Employee.

Index can also be created on multiple columns as shown below:

CREATE INDEX Emp_index

ON Employee (Emp_name, Salary)

To create index on a column in descending order, we make use of reserved word DESC as:

CREATE INDEX Emp_index

ON Employee (Emp_name DESC)

Unique Index

Indexes created above are simple indexes i.e, two rows can have same index values. But
as UNIQUE keyword is used for index creation, duplicate values are not considered.

Syntax:

CREATE UNIQUE INDEX index_name

ON table_name (column_name)

Create View Command

Before describing the create view command, lets understand VIEWS.

After a database table has been created and values have been inserted into it and stored,
it becomes necessary to prevent all columns being accessed by the users. Hence we
create views. A View is an object that is mapped to a SELECT sentence. A view is created
on the top of a base table and contains no data at all until a call for it is made. A view is
treated like a base table (the table on which the view is created) and hence queries can be
fired on it just like on any database table.

Syntax:

CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

Example:

CREATE VIEW emp_view AS

SELECT First_name, Surname


FROM Details

Create Sequence

Before coming to the command CREATE SEQUENCE, lets first try to understand what a
sequence is and why at all. do we need to create it.

Sequences are database objects that automatically generate sequential lists of numbers.
They are useful when creating surrogate key values for primary key fields. For example,
we can generate range of numbers starting from 1101 onwards, when new record is
added to the table, 1101 could be value of the primary field for the first record and so on.

Every sequence must have unique name. The command to create a sequence is CREATE
SEQUENCE.

Consider the following Query:

CREATE SEQUENCE emp_number_seqnce


START WITH 1100
INCREMENT BY 1

The above query creates a sequence called emp_number_seqnce that starts with 1101
and increments by 1 each time the sequence runs new record.

After the sequence has been created, the next thing we want do is to insert it into a table.
Suppose that we want to insert a sequence value for "emp_id" field in the "Emp_detail"
(Emp_id,Emp_name, Age) table. Here is how we will do that:

INSERT INTO Emp_detail

VALUES (emp_number_seqnce.NEXTVAL,'Mohan',26,)

We inserted one record into the "Emp_detail" table using sequence generated values for
the "Emp_id" field. NEXTVAL, that has been used in the query to insert values above, is a
command that generates next available for the sequence. Remember you have to have
record in the department table with "Emp_name" of "Mohan" in order to insert this record
successfully. The above query finally yields the following result set:

Emp_id Emp_name Age


1101 Mohan 26

The current available sequence value can be viewed by:

SELECT emp_number_seqnce.CURRVAL FROM DUAL

We mention "DUAL" above, which is a virtual table with one row and one column. It has
been described in SQL FUNCTIONS SECTION in detail.

Alter Table
ALTER TABLE is used to add/drop/modify column(s) in a table structure of a database.

Syntax:

ALTER TABLE table_name

ADD/DROP/MODIFY column_name data_type

Example:

ALTER TABLE Employee

ADD Date_of_Join date

the above query will add a new field in the table Employee as shown below:

Emp_id Emp_name Age Salary Date_of_Join


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14500
1104 Wasim 29 15000
1105 Rita 28 13500

Similarly, a column can be dropped from a table by the following SQL statement:

ALTER TABLE Employee

DROP Date_of_Join date

This will result in the following change in Employee table:

Emp_id Emp_name Age Salary


1101 Ana 28 15000
1102 Joe 23 13500
1103 Jack 25 14500
1104 Wasim 29 15000
1105 Rita 28 13500

We can also modify existing columns using ALTER with MODIFY clause.

Suppose we want to change the size of the column "Surname" from existing "varchar(50)"
to new size "varchar(40)" in table "Details" that we had created (in Create table section).
We key in the following the following query for that:

ALTER TABLE Details


MODIFY Surname varchar(40)

The above query will alter the size of the column.Notice that only new data type along
with he new size had to be mentioned. There is no need to specify the old data type along
with its corresponding size.

The alteration done can be checked by the DESCRIBE command, as done below:

DESCRIBE Details

The above query will return

Name TYPE NULL?


First_name Varchar(50) NOT NULL
Surname Varchar(40)
Address Varchar(50)
DOB DATE

As seen above the column size of "Surname" has been successfully updated.

SQL Drop

SQL DROP is used to drop or delete a table. Thus all the records containing inside it also
get deleted with the deletion of the table structure.

Syntax:

DROP TABLE table_name

Example:

DROP TABLE Employee

On running the above query, the table named Employee gets deleted and with that,
records are also lost.

Drop Index

DROP INDEX deletes an existing index which was created over a column name in a
database table.

Syntax:

DROP INDEX table_name.index_name

For example, to delete an index named Emp_index which was created over a field/column
in a table named Employee, we key in the following query:

DROP INDEX Employee.Emp_index


Drop View

The above command is used to remove a view from the database.

Syntax:

DROP VIEW view_name

Example:

DROP VIEW emp_view

The above query drops view named 'emp_view'.

Drop Database

To delete an entire database, we make use of DROP DATABASE.

Syntax:

DROP DATABASE database_name

Example:

DROP DATABASE Emp_database

The above query deletes the database named Emp_database and with that, all the tables
inside it containing records are deleted too.

Drop Sequence

When a database sequence is no longer required, it is possible to drop the database


sequence using the following command.

Syntax:

DROP SEQUENCEE sequence_name

To remove the sequence that we created in this tutorial enter the following command.

DROP SEQUENCE emp_number_seqnce

Select Into

The SELECT INTO command is used to make back_up copies of tables i.e, in case a table
is accidentally lost or destroyed, the back_up copy of it can be used.

Syntax:

SELECT column_name(s) INTO backup_table [IN database_name]

FROM table_name
Example:

SELECT * INTO Emp_backup

FROM Employee

The above query creates a backup copy of table Employee called Emp_backup.

In case, the back up is to be created in another database, we make use IN clause.

Example:

SELECT Employee.* INTO Emp_backup IN 'Emp.mdb'

FROM Employee

In the above example, a backup copy of Employee table called Emp_backup gets created
which resides in another database called Emp.mdb.

We can also create a backup copy containing selected columns instead of all columns of a
table.

Example:

SELECT Emp_d, Emp_name, Salary INTO Emp_backup

FROM Employee

WHERE clause can be added to create a backup copy which satisfies a condition. This can
be explained by the following query:

SELECT Emp_d, Emp_name, Salary INTO Emp_backup

FROM Employee

WHERE SALARY > 14000

Constraints

Constraints are rules that are applied on data while values are keyed in columns so that
invalid data entry into the database tables can be prevented. The various Constraints are:

Primary Key Constraint


Foreign Key Constraint
Unique Constraint
Check Constraint

A Constraint can be created as:

CONSTRAINT constraint_name constraint_definition

For Example, The following query creates a table Details in which a primary key constraint
called p_key has been defined:

CREATE TABLE Details (E_id varchar(10) CONSTRAINT p_key PRIMARY KEY, First_name
varchar(50), Surname varchar(50), Address char(50), DOB date)

Primary Key Constraint

What is a Primary Key?

A Primary Key, consisting of one or more columns in a database table, uniquely identifies
each row/record in the table. Thus the values fed into a column(s) which is a primary key,
must be unique (non-repeatitive) and should not contain Null Values.

If a single column is the primary key in a table it is called a Simple Key. When a Primary
Key is made of more than one columns (i.e, multicolumn), it is called as Composite Key.

Syntax:

CREATE TABLE table_name (column_name data_type (size) PRIMARY KEY)

Example:

CREATE TABLE Details (E_id varchar(10) PRIMARY KEY, First_name varchar(50), Surname
varchar(50), Address char(50), DOB date)

The above query creates a table Details where E_id is the primary key.

The above query could also be written as:

CREATE TABLE Details (E_id varchar(10), First_name varchar(50), Surname varchar(50),


Address char(50), DOB date PRIMARY KEY (E_id))

Lets take up an example where a primary key is made of two columns i.e we make a
composite key.

CREATE TABLE Sales_Details

(detail_order_no varchar(4), product_no varchar (4), qty_ordered number (6),

pruduct_rate number(6,2), PRIMARY KEY (detail_order_no, product_no)

The above query creates a table "Sales_Details", whose Primary key is a composite key i.e
consists of more than one columns and they are-"detail_order_no" and "product_no".

Foreign Key Constraint

A foreign key is a column (or group of columns) whose values are derived from a primary
key/unique key of some other table.

The database table that defines the Primary key is called as the Primary table while the
table that defines the Foreign key is called as the Foreign table.
The Primary Table is referenced in the table where foreign key is defined (Foreign Table)
using the keyword REFERENCES.

The existence of foreign implies a relation between two tables i.e, the Primary table and
the Foreign /table. Thus a Foreign Key in foreign table must have a corresponding Primary
Key in Primary Table.

An error message is displayed when an attempt is made to delete a record from Primary
Table when the corresponding records exist in Foreign table. There is an option of ON
DELETE CASCADE, which when specified in the foreign key definition and an attempt is
made to delete a record in the primary table, all corresponding records in the foreign table
along with record in the primary table gets deleted.

Syntax:

foreign_tablename (column_name data_type (size) REFERENCES primary_tablename) [ON


DELETE CASCADE]

Example:

CREATE TABLE Daily (E_id varchar(10) REFERENCES Details, E_dept varchar(20),


E_Designation varchar(20), Grade char(1))

The above table defines Foreign Key-E_id, which is a Primary Key in Table Details.

Unique Constraint

The UNIQUE constraint is used to avoid keying in repeated values into a column which has
been declared UNIQUE. This ensures that the value stored into the column is unique (non-
repeated). A table ca have more than one columns with Unique constraint.

Syntax:

CREATE TABLE table_name (column_name data_type(size) UNIQUE)

Example:

CREATE TABLE Details (E_id varchar(10) UNIQUE, First_name varchar(50), Surname


varchar(50), Address char(50), DOB date)

The above query results in creation of a database table named Details with the fields-E_id,
First_name, Surname, Address, DOB. The Field-E_id is unique, i.e no two values in this
field/column are same.

Check Constraint

CHECK constraints are generally specified as logical expression and hence evaluates either
True/False. Various Validations can be applied on values in a column of a database table
using CHECK constraint.

Syntax:
CREATE TABLE table_name (column_name(s) data_type(size) CHECK (logical expression))

Example:

CREATE TABLE Details (E_id varchar(10), First_name varchar(50) CHECK


(First_name=upper (First_name)), Surname varchar(50) CHECK
(Surname=upper(Surname)), Address char(50), DOB date)

The Above Query creates a table Details such that Values inserted into the fields
First_name & Surname are in upper case only. The above query can be re-written as:

CREATE TABLE Details (E_id varchar(10), First_name varchar(50), Surname varchar(50),


Address char(50), DOB date, CHECK (First_name=upper(First_name)), CHECK
(Surname=upper(Surname)))

Data Control Language


In this section we will be using commands that control the behavior of database objects.
Although DCL form a part of PL/SQL part, they have been described in brief here.

The commands have been described one at a time, covering all the clauses

Before we go on to discuss Data Control Language (DCL) commands, lets understand the
concept of transaction.

What is a Transaction?

A transaction consists of one or more statements that are executed together as a unit, so
either all of the statements are executed, or none of the statements is executed.

For example, when a shopkeeper updates the amount of a particular product sold each
week, he will also want to update the total amount sold to date. However, he will not want
to update one without also updating the other; otherwise, the data will be inconsistent.
The way to ensure that either both actions occur or neither action occurs is to use a
transaction.

Now we come to various DCL commands which make use of transactions.

Savepoint

When a transaction is rolled back to a savepoint all changes made after that savepoint are
undone. Savepoint names must be distinct within a given transaction. If you create a
second savepoint with the same identifier as an earlier savepoint, then the earlier
savepoint is erased. After a savepoint has been created, you can either continue
processing, commit your work, roll back the entire transaction, or roll back to the
savepoint.

SAVEPOINT Savepoint_name

The above statement sets a named transaction savepoint whose name is savepoint_name.

Rollback

The Rollback Statement terminates the current transaction and rescinds all changes made
under the transaction. It rolls back the changes to the database.

Thus, Rollback statement is used to undo work done in the current transaction.

ROLLBACK [TO SAVEPOINT savepoint_name]

The above statement rolls back a transaction to the SAVEPOINT named savepoint_name.
Modifications that this transaction made to rows after the savepoint was set, are undone
in the rollback

Using Rollback, without the To Savepoint clause, ends the transaction and with that, all
the savepoints are erased. This undoes all changes in the current transaction.

Commit

Commit statement leaves all the changes made by the current transaction in effect i.e, it
saves all the changes brought about by the current transaction. Thus all changes resulting
from statements in the transaction will be made permanent with Commit.

The Commit Statement terminates the current transaction and makes all changes under
the transaction persistent. It commits the changes to the database.

However, Commit may fail if the transaction had been marked to be canceled before
Commit operates.

Using Savepoint, Rollback & Commit

Having defined Commit, Rollback & Savepoint above, we now take up an example using
these three commands, given below:

Consider a case where Ana and Jack's salary are to updated in table Employee
(emp_name, emp_grade, dept, salary), check that total salary in the department does not
exceed Rs.1,00,000 then re-enter Jack's salary

UPDATE Employees
SET salary = 7000
WHERE emp_name = 'Ana'

SAVEPOINT ana_sal

UPDATE Employees
SET salary = 10000
WHERE emp_name = 'Jack'

SAVEPOINT jack_sal

SELECT SUM(salary) FROM Employees;

ROLLBACK TO SAVEPOINT ana_sal

UPDATE employees
SET salary = 9000
WHERE emp_name = 'Jack'
Commit

As seen from the above code that as the sum of salary exceeds 100000, the transaction is
rolled back to the save point named ana_sal meaning changes upto that point have been
updated but updations after that have been rolled back i.e made undone.

Nested Queries
In this section we discuss nested queries and why they are used.

Nested Queries
A nested query is a query that 'NESTS' inside a query, implying a query residing inside
another query. The nested queries are also termed as Subqueries. The statement/query
containing/enclosing a subquery is called as he parent query. The parent query makes use
of the rows/records returned by the sub query.

Subqueries are used:

· to create tables/views
· to insert records in a table
· to update records in a table
· to supply values in SELECT/UPDATE/DELETE statements where conditions are specified
using clauses-WHERE, HAVING, IN etc.

To explain the subqueries further using examples we would be referring two tables-
Student and Students_Sports as shown below:

Student

S_id S_name S_house


0011 Renee CVR
0012 James JN
0013 Sameer CVR
0014 Piyush CVR
0015 Ana CVR
0016 Jane JN
0017 Mita JN

Student_Sports

S_id Sport
0012 Basketball
0013 Basketball
0014 Basketball
0016 Volleyball

From the two tables above, suppose we want to retrieve the names of all students who do
not play sports.

We key in the following query for that:

SELECT S_id, S_name FROM Student

WHERE S_id NOT IN

(SELECT S_id FROM Student_Sports)


SQL Joins, Union and Intersect
In this section we will be learning to work with more than one table, at a time, using Joins
Unions and Intersect. So lets take them up one by one.

SQL Join

Join is one of the most beneficial features of SQL and Relational Database Management
Systems. Till now we have been using a single table to select records. With Join, we can
refer to more than one table at time. Thus Join by allowing to link data from two or more
tables, truly makes the relational database management system-Relational.

We will classify the JOINS as:

Inner Join
Outer Join
Self Join

To Explain Join further, let us first of all consider two tables in a database:

Table Transaction

Trans_id T_Date Cust_id


0420 03-02-2004 AB04
0320 03-02-2004 CD03
0424 04-02-2004 AB04
0224 04-02-2004 EF04

Table Customer

Cust_id Cust_name
AB04 Ana
CD03 Perry
EF04 Jane
GH05 Joe

For Explaining the various type of joins, we will be using these two tables.

Inner Join

Inner Join returns all those records from both the tables where a match is found. This
implies whenever a set of records from two tables satisfy the specified condition, they are
selected.

Syntax:

SELECT column1, column2, column3


FROM table1

INNER JOIN table2

ON table1.column = table2.column

Example:

The query:

SELECT Transaction.T_Date, Customer.Cust_name

FROM Transaction

INNER JOIN Customer

ON Transaction.Cust_id = Customer.Cust_id

will result in

T_Date Cust_name
03-02-2004 Ana
03-02-2004 Perry
04-02-2004 Ana
04-02-2004 Jane

Outer Join

Outer join may be further classified as:

Left Join
Right Join

Left Join

Left Join returns all the records from the first table even if no corresponding matches are
found in the second table.

Syntax:

SELECT column1, column2, column3

FROM table1

LEFT JOIN table2

ON table1.column = table2.column

Example:
The query:

SELECT Customer.Cust_name,Transaction.T_Date

FROM Customer

LEFT JOIN Transaction

ON Customer.Cust_id = Transaction.Cust_id

will result in:

Cust_name T_Date
Ana 03-02-2004
Ana 04-02-2004
Perry 03-02-2004
Jane 04-02-2004
Joe

As seen above, the T_date Field is empty for Cust_name Joe as no match was found for
Joe (of table Customer) in table Transaction.

Right Join

Left Join returns all the records from the second table even if no corresponding matches
are found in the first table.

Syntax:

SELECT column1, column2, column3

FROM table1

RIGHT JOIN table2

ON table1.column = table2.column

Example:

The query

SELECT Transaction.T_Date,Customer.Cust_name,

FROM Transaction

RIGHT JOIN Customer

ON Transaction.Cust_id = Customer.Cust_id
T_Date Cust_name
03-02-2004 Ana
03-02-2004 Perry
04-02-2004 Ana
04-02-2004 Jane
Joe

As shown above, Although no match was found for the last record of table Customer on
the First table Transaction. The field for which no match has been found is kept empty.

Self Join

There are times, when it becomes necessary to join a table to itself. This is known as Self
Join.

In Self Join, two copies of the same table are opened in the memory. Hence in the FROM
clause the table name is mentioned twice under aliases. This is done to avoid the situation
when the second table overwrites the copy of the first table since both have the same
name.

To Explain the Self Join further with an example conisder a table Emp_Manager below:

Emp_id Emp_name Manager_id


0420 Ana 0320
0320 Perry 0224
0424 Jane -
0224 Joe -

Suppose we want select the records displaying the names of the employees and their
respective managers from the above table. We key in the following query for that:

SELECT emp.Emp_name Employee, mgr.Emp_name Manager FROM Emp_Manager emp,


Emp_Manager mgr

WHERE emp.Manager_id = mgr.Emp_id

The output of the above query is shown below:

Employee Manager
Ana Perry
Perry Jane

The above output results as each Manager_id record (0320, 0224) of emp table is joined
with Emp_id records (0420, 0320, 0424, 0224) of mgr table.

SQL Union
SQL Union is used to join the results of two queries together. It is similar to Join with one
big exception and that is, the selected columns, while using Union, must be of same data
type. Queries using Union always return distinct i.e, non-repetitive values.

Syntax:

SQL Statement1

Union

SQL Statement2

Suppose we have the following two tables in a database:

Client_Local

C_id Client_name
L11 ABC
L12 DEF
L13 HIJ
L15 RST
L16 OPQ

Client_Foreign

C_id Client_name
F11 XYZ
F12 UVW
F13 RST
F14 OPQ

Now we use the Union to select all the client names that are distinct. We key in the
following query:

SELECT Client_name FROM Client_Local

Union

SELECT Client_name FROM Client_Foreign

which returns the result set

Client_name
ABC
DEF
HIJ
RST
OPQ
XYZ
UVW

Although client_name 'RST' and 'OPQ' appeared in both the tables i.e, twice, still in the
result set duplicate values have been removed. Thus the two client names appear only
once in the result set.

Union All

Union All is similar to Union except that the former does not remove duplicate values from
the result set. This implies that the values in the result set using Union All might not be
distinct and may have repetitive values.

Syntax:

SQL Statement1

Union All

SQL Statement2

Example:

SELECT Client_name FROM Client_Local

Union All

SELECT Client_name FROM Client_Foreign

returns the result set:

Client_name
ABC
DEF
HIJ
RST
OPQ
XYZ
UVW
RST
OPQ
As seen above, client_name 'RST' and 'OPQ' are listed twice in the result set.

Intersect

Using Intersect, multiple queries can be put together and their output can be combined.
Intersect outputs only those rows/records that are produced by both the queries. This
implies queries using Intersect will include only those rows that are fetched by both the
queries.

Syntax:

SQL Statement1

Intersect

SQL Statement2

Lets take up an example to understand it better. We will consider the two tables for that
namely, table "Student and table" "Student_Sport" as shown below:

Student

S_id Name Hostel


0111 Ana CVR
0112 Perry CVR
0113 Jane NGH
0115 Joe NGH

Student_Sport

S_id Sport
0111 Volleyball
0112 Basketball
0225 Basketball
0119 Volleyball
0445 Volleyball

Now, suppose we want to retrieve the names all students who play 'Volleyball' and stay in
'CVR' hostel.

SELECT S_id, Name FROM Student

WHERE Hostel = 'CVR'

Intersect

SELECT Student.S_id, Name FROM Student, Student_Sport


WHERE Sport = 'Volleyball' AND Student.S_id = Student_Sport.S_id

Lets analyze how the Intersect keyword gives the final result set from output of two
queries. The first query in the Intersect example above i.e:

SELECT S_id, Name FROM Student

WHERE Hostel = 'CVR'

will fetch the following result set

S_id Name
0111 Ana
0112 Perry

The second query i.e:

SELECT Student.S_id, Name FROM Student, Student_Sport

WHERE Sport = 'Volleyball' AND Student.S_id = Student_Sport.S_id

will yield the result set:

S_id Name
0111 Ana

The Intersect clause picks up those records that are common in both queries. Thus from
the above two result sets, applying the Intersect clause, we get the final set as shown
below:

S_id Name
0111 Ana

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