You are on page 1of 23

SQL:

SQL or Structured Query Language(also known as sequel) is an non procedural


language used to create and manipulate databases.
Donald D. Chamberlin and Raymond F.Boyce developed the first version of
SQL.
SQL is an ANSI (American National Standards Institute) standard for accessing
database systems. SQL statements are used to retrieve and update data in a
database.
(Briefly, SQL is a standard language for accessing and manipulating databases.)
using SQL we can access and manipulate data in: MySQL, SQL Server, Access,
Oracle, Sybase, DB2, and other database systems.
ORACLE:
There are several DBMSs available in the market today, out of which oracle is
the most popular one.
It was the first commercial relational database management system (RDBMS)
and the first version of oracle came into the market in 1979(version 2.0).
Oracle was the first company to release a product that used the English-based
Structured Query Language or SQL. This version supported only basic SQL
functionalities.
When a user wants to get some information from a database file, he can issue a
query.
A query is a userrequest to retrieve data or information with a certain
condition.
With SQL, we can query a database and have a result set returned.

Oracles Interface:
There are several tools available to access a database created in oracle. The
most popular and simplest tool is SQL*Plus.
SQL*Plus is an Oracle tool (specific program) which accepts SQL commands
and PL/SQL blocks and executes them.
SQL*Plus enables manipulations of SQL commands and PL/SQL blocks.
It also performs additional tasks such as calculations, store and print query
results in the form of reports, list column definitions of any table, access and
copy data between SQL databases and send messages to and accept responses
from the user.
When SQL*Plus is started, it asks the users to log on by providing the username
and password. Oracle provides some default usernames inclusing SYS,
SYSTEM etc. and during installation, it asks for a password for these default
usernames.
SQL Commands:
SQL commands are instructions used to communicate with the database to
perform specific task that work with data. SQL commands are grouped into four
major categories depending on their functionality:
1. Data Definition Language
Create, Alter, Drop and Truncate
2. Data Manipulation Language
Insert, Update, Delete and Select
3. Transaction Control Language
Commit, Rollback and Save point
4. Data Control Language
Grant and Revoke

Data Definition Language:


The Data Definition Language(DDL) provides commands that can be used to
create, alter(modify) and delete database objects. The database objects include
relation schemas, relations, views, catalogs, indexes etc.
The Data Definition Language(DDL) commands used for table definition can be
classified into following:
Create table command
Alter table command
Truncate table command
Drop table command
CREATE TABLE COMMAND:
The CREATE TABLE command is used to specify a new relation by
giving it a name and specifying its attributes and initial constraints(key
constraints, referential integrity constraints).
The syntax for CREATE TABLE command is shown below.
CREATE TABLE <table_name>
(
<attribute1> <data-type1> [contraint1],
<attribute2> <data-type2> [contraint2],
<attribute3> <data-type3> [contraint3],
.
..
<attributen> <data-typen> [constraint n],
[table contraint1]
..
..
[table constraint n]
);

For example, the command to create room relation whose schema is


room(roomID, bldg, roomNo, maxCapacity, style) can be specified as

Ex:2

Once the relation(table) is created, its structure can be viewed by using the
DESCRIBE(or DESC) command. For ex, the command to view the structure of
the room relation can be specified as
DESCRIBE room
(or)
DESC room
As a result of this command, the structure of the relation room will be
displayed.

Attribute Data Types:


DATATYPE
NUMBER(p,s)

DESCRIPTION
It is used to specify numeric data. Formatted numbers can be
declared by using NUMBER(p,s) (or) DECIMAL(p,s) where
p is the precision, the total number of decimal digits and j,
the scale, is the number of digits after the decimal point.
(this data type include integer numbers of various
sizes(INTEGER or INT and SMALLINT) and floatingpoint(FLOAT) numbers of various precision.)

CHAR(n) (or)
it is used to represent data as fixed-length string of
CHARACTER(n) characters of size n.

VARCHAR2(n)

it is used to represent data as variable length string of


characters of Maximum size n.

LONG

it stores variable-length character data up to 2GB. Its length


would be restricted based on memory space available in the
computer.

DATE

it is used to represent data as date. oracle predefined format


for Date data type is dd-mm-yyyy.

TIME

it is used to represent data as time.

TIMESTAMP

It is used to represent data consisting of both date and time.

In addition to these data types, there are many more data types supported by
SQL like RAW, LONG RAW, CLOB, BLOB and BFILE etc.

SPECIFYING CONSTRAINTS:
Constraints are used to impose rules on the data that is being stored into the
tables.
Constraints are required to maintain the integrity of the data, which ensures that
the data in database is consistent, correct and valid. These constraints are
specified within the definition of a relation.
There are table level constraints as well as column level constraints.
Different types of constraints are specified as given below.
a) PRIMARY KEY constraint:
A primary key is one or more columns(s) in a table to uniquely identify
each row in the table. A table can have only one primary key.
This constraint ensures that attribute declared as primary key cannot have
null value and no two tuples can have the same value for primary key
attribute.In other words, the values in the primary key attributes are not null and
are unique.
Syntax:
The syntax of a PRIMARY KEY constraint when applied as a column-level
constraint is
<attribute> <data_type> PRIMARY KEY
The syntax of a PRIMARY KEY constraint when applied as a table-level
constraint is
PRIMARY KEY(<attribute>)
Ex: ISBN VARCHAR2(15) PRIMARY KEY
(or)
PRIMARY KEY (ISBN)
If a primary key has more than one attribute, the PRIMARY KEY constraint is specified as
table level constraint.

The syntax of a PRIMARY KEY constraint when applied on more than one
attribute is
PRIMARY KEY(<attribute1> , <attribute2> , .., <attribute n>)
Ex:

PRIMARY KEY(ISBN,R_ID)

b) UNIQUE CONSTRAINT:
the UNIQUE constraint ensures that the set of attributes have unique
values i.e., no two tuples can have same value in the specified attributes.
UNIQUE constraint can be applied as a column-level as well as table-level
constraint.
The syntax of UNIQUE constraint when applied as a column-level constraint
is
<attribute> <data_type> UNIQUE
The syntax of a UNIQUE constraint when applied as a table-level constraint is
UNIQUE (<attribute>)
Ex: pname VARCHAR2(15) UNIQUE
(or)
UNIQUE (pname)
If a unique constraint is applied on more than one attribute, the UNIQUE constraint is
specified as table level constraint.

The syntax of a UNIQUE constraint when applied on more than one attribute is
UNIQUE (<attribute1> , <attribute2> , .., <attribute n>)
Ex:

UNIQUE (pname, address)

c)CHECK Constraint:
This constraint ascertains that the value inserted in an attribute must satisfy a given
expression i.e., it is used to specify the valid values for a certain attribute.

The syntax of CHECK constraint when applied as a column-level constraint is


<attribute> <data_type> CHECK (<expression>)
The syntax of a CHECK constraint when applied as a table-level constraint is

Ex: price number(6,2) CHECK(price>200)


(or)
Constraint chk_price CHECK(price>200)

d) NOT NULL CONSTRAINT:


The NOT NULL constraint is used to specify that an attribute will not accept null values.

The syntax of NOT NULL constraint when applied as a column-level constraint


is
<attribute> <data_type> NOT NULL
Ex: page_count number(4) NOT NULL
Note: The NOT NULL constraint can be specified only as a column-level
constraint and not as table-level constraint.

e) FOREIGN KEY CONSTRAINT:


This constraint ensures that the foreign key value in the referencing relation
must exist in the primary key attribute of the referenced relation i.e., foreign key
references the primary key attribute of referenced relation.
A FOREIGN KEY constraint can be specified as a column-level
constraint and also as a table-level constraint.
The syntax of FOREIGN KEY constraint when applied as a column-level
constraint is
<attribute> <data_type> REFERENCES (referenced_relation) (<key_attribute>)

The syntax of a FOREIGN KEY constraint when applied as a table-level


constraint is
FOREIGN KEY <attribute> REFERENCES (referenced_relation) (<key_attribute>)

Where key_attribute is the primary key of the referenced relation.


Ex: P_id varchar2(4) REFERENCES PUBLISHER(P_id)
(or)
FOREIGN KEY(P_id) REFERENCES PUBLISHER(P_id)

Online book database:


The CREATE TABLE command for the relations of online book database along with the
required constraints are given below.

CREATE TABLE PUBLISHER


(
P_id
varchar2(4),
Pname
varchar2(50) NOT NULL,
Address
varchar2(50),
State
varchar2(15),
Phone
varchar2(20),
Email_id
varchar2(30),
PRIMARY KEY(P_id)
);
CREATE TABLE BOOK
(
ISBN
varchar2(15),
Book_title
varchar2(50) NOT NULL,
Category
varchar2(20),
Price
number(6,2),
Copy_right date number(4),
year
number(4),
page_count
number(4),
p_id
varchar2(4) NOT NULL,
CONSTRAINT chk_price CHECK (price BETWEEN 20 and 200),
PRIMARY KEY(ISBN),
FOREIGN KEY(P_id) REFERENCES PUBLISHER(P_id)
);
CREATE TABLE AUTHOR
(
A_id
varchar2(4),
Aname
varchar2(30) NOT NULL,
State
varchar2(15),
City
varchar2(15),
Phone
varchar2(20),
Email_id
varchar2(30),
PRIMARY KEY(A_id)
);

CREATE TABLE AUTHOR_BOOK


(
A_id
varchar2(4) NOT NULL,
ISBN
varchar2(4) NOT NULL,
FOREIGN KEY(A_id) REFERENCES Y(A_id),
FOREIGN KEY(ISBN) REFERENCES BOOK(ISBN)
);
CREATE TABLE REVIEW
(
R_id
varchar2(4) NOT NULL,
ISBN
varchar2(4) NOT NULL,
Rating
number(2),
PRIMARY_KEY(R_id,ISBN),
CONSTRAINT chk_rating CHECK (Rating BETWEEN 1 AND 10),
FOREIGN KEY(R_id) REFERENCES AUTHOR(A_id),
FOREIGN KEY(ISBN) REFERENCES BOOK(ISBN)
);
ALTER TABLE COMMAND:
ALTER TABLE COMMAND is used to make changes in the structure of a relation as per
requirements of the user. The requirements may include
i)
ii)
iii)
iv)
v)
vi)

To add an attribute
To modify the definition of an attribute
To drop an attribute
To add a constraint
To drop a constraint
To rename attribute and relation

ADDING an Attribute:
The new attribute can be added to the relation by using the ADD clause of ALTER TABLE
command.
The syntax to add new attribute in an existing relation is
ALTER TABLE <table_name> ADD <attribute> <data_type>;
Ex: the command to add a new attribute pname in the relation BOOK can be specified as
ALTER TABLE BOOK ADD pname varchar2(10);

MODIFYING an Attribute:
Any attribute of a relation can be modified by using the MODIFY clause of ALTER TABLE
command. It can be used to change either its datatype or size or both.
The syntax to MODIFY new attribute in an existing relation is
ALTER TABLE <table_name> MODIFY <attribute> <data_type>;
Ex: The command to MODIFY attribute pname in the relation BOOK can be specified as
ALTER TABLE BOOK MODIFY pname varchar2(50);
DROPPING an Attribute:
The DROP COLUMN clause of ALTER TABLE command can be used to remove
undesirable attributes from a relation.
The syntax to remove an attribute in an existing relation is
ALTER TABLE <table_name> DROP COLUMN <attribute> ;
Ex: The command to remove an attribute pname in the relation BOOK can be specified as
ALTER TABLE BOOK DROP COLUMN pname;
Whenever a particular attribute is dropped, the data stored in that attribute and its associated
constraints are dropped.
NOTE: Alter table <table_name> drop (Column1, Column2,_);

ADDING A CONSTRAINT:
Different types of constraints can be added to the definition of an already existing relation.
The syntax to add a constraint using ADD clause is
ALTER TABLE <table_name> ADD [CONSTRAINT <constraint_name>]
< constraint>;
Where CONSTRAINT is a keyword
Constraint_name is a name given to constraint
Constraint can be any of the constraints

Ex:
ALTER TABLE BOOK ADD CONSTRAINT cons_1 UNIQUE(ISBN);
ALTER TABLE BOOK ADD FOREIGN KEY (P_id) REFERENCES
PUBLISHER;

DROPPING A CONSTRAINT:
Any of the constraint defined can be dropped,provided it is given a name when specified .

Ex:ALTER TABLE BOOK DROP CONSTRAINT cons_1 ;

RENAMING AN ATTRIBUTE:
The name of an attribute of a relation can be modified by using the RENAME
COLUMN.....TO clause.
The SYNTAX to modify the name of an attribute is
ALTER TABLE <table_name> RENAME COLUMN <old_name> TO <new_name>;
Ex:
ALTER TABLE BOOK RENAME COLUMN page_count TO p_count;
RENAMING AN RELATION:
The name of a relation can be modified by using the RENAME.....TO clause.
The SYNTAX to modify the name of a relation is
ALTER TABLE <old_table_name> RENAME TO <new_table_name>;
Ex:
ALTER TABLE BOOK RENAME TO BOOK_DETAIL;
DROP TABLE COMMAND:
THE DROP TABLE COMMAND is used to remove an already existing relation, which is no
more required as a part of the database.
The syntax to remove a relation is
DROP TABLE <table_name>;
Ex: the command to remove the relation BOOK_DETAIL is
DROP TABLE BOOK_DETAIL;
As a result of this command, all the tuples stored in BOOK_DETAIL as well as
relation itself is permanently removed and cannot be recovered.

TRUNCATE TABLE COMMAND:

If there is no further use of records stored in a table and the structure has to be
retained then the records alone can be deleted.
The Syntax is
TRUNCATE TABLE <TABLE NAME>;
Data Manipulation Language:
Data Manipulation Language(DML) commands are used for retrieving and
manipulating data stored in the database. The basic retrieval and manipulating
commands are
INSERT , SELECT, UPDATE and DELETE . For these commands the relation
must already exist.
INSERT COMMAND:
Tuples can be inserted in the relation using the INSERT command. This
command adds a single tuple at a time in a relation.
The syntax to add a new tuple in a relation is given here.
INSERT INTO <table_name> [(<attribute_list>)] VALUES(<value_list>);
The value_list is the list of values to be inserted in the corresponding attributes
listed in attribute_list. The values should be specified in the same order in which
the attribute are listed in attribute_list. In addition, the data type of the
corresponding values and attributes must be the same.
Ex: consider the following relation
CREATE TABLE BOOK
(
ISBN
varchar2(15),
Book_title
varchar2(50) NOT NULL,
Category
varchar2(20),
Price
number(6,2),
Copy_right _date number(4),
year
number(4),
page_count
number(4),
p_id
varchar2(4) NOT NULL,
CONSTRAINT chk_price CHECK (price BETWEEN 20 and 200),
PRIMARY KEY(ISBN),
FOREIGN KEY(P_id) REFERENCES PUBLISHER(P_id)
);

The command to add a tuple in the relation BOOK can be specified as


INSERT INTO BOOK (ISBN, Book_title, Category, Price,
Copy_right_date, year, page_count, p_id)
VALUES (001-987-760-9,dbms,textbook,40,2004,2005,800,p001);
Alternatively, tuple can be inserted in to a relation by omitting the attribute list
from the command. So a tuple can also be inserted as
INSERT INTO BOOK
VALUES (001-987-760-9,dbms,textbook, 40, 2004, 2005, 800,p001);
Adding values in a table using Variable method:
Till now we have seen static method to insert data. One can add data in a table
using variable method with & (ampersand) sign. It will prompt user to enter
data of mention field.
Generally It is used to add more than one row in a table without typing whole
command repetitively using / sign.
Ex: the command to insert tuples into passenger table is given below.
Consider the following relation

After creating the passenger relation(table) using create table command, the
values can be inserted into that relation using insert command as follows.

SQL> insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name',


&Age, '&Sex','&PPNO');
Enter value for pnr_no: 1
Enter value for ticket_no: 1
Enter value for name: SACHIN
Enter value for age: 12
Enter value for sex: m
Enter value for ppno: sd1234
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name',
&Age, '&Sex','&PPNO')
new 1: insert into Passenger values(1,1,'SACHIN',12,'m','sd1234')
1 row created.
SQL> /
Enter value for pnr_no: 2
Enter value for ticket_no: 2
Enter value for name: rahul
Enter value for age: 34
Enter value for sex: m
Enter value for ppno: sd3456
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name',
&Age, '&Sex','&PPNO')
new 1: insert into Passenger values(2,2,'rahul',34,'m','sd3456')
1 row created.
SQL> /
Enter value for pnr_no: 3
Enter value for ticket_no: 3
Enter value for name: swetha
Enter value for age: 24

Enter value for sex: f


Enter value for ppno: sdqw34
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name',
&Age, '&Sex','&PPNO')
new 1: insert into Passenger values(3,3,'swetha',24,'f','sdqw34')
1 row created.

SELECT COMMAND:
The SELECT command is the only data retrieval command in SQL.
The syntax of SQL command is given below.
SELECT <attribute1>,<attribute2>,,<attributen>
FROM <table_name>;
Query1:
Retrieve the attributes ISBN, Book_title, category from the relation BOOK
Ans:
SELECT ISBN,Book_title, category
FROM BOOK;
Note:
When all the attributes of a relation has to be retrieved, then instead of
specifying list of all attributes in the select command , the symbol asterisk(*)
will be used.
Query2:
Retrieve the all attributes from the relation BOOK
Ans:
SELECT *
FROM BOOK;
Query3:
Retrieve the category of all books from the relation BOOK
Ans:
SELECT category
FROM BOOK;
Note:
The result of above command consists of tuples having duplicate values for the
attribute category. To eliminate duplicate tuples from the resultant relation, the
keyword DISTINCT is used.

Query4:
Retrieve the unique values for the attribute category from the relation BOOK
Ans:
SELECT distinct category
FROM BOOK;
WHERE CLAUSE:
To retrieve the tuples from the relation based on certain condition, we can use
WHERE clause in the select command. The condition will be specified in the
WHERE clause.
The syntax of select command with where clause is
SELECT <attribute1>,<attribute2>,,<attributen>
FROM <table_name>
WHERE<condition>;
the relational operators (= , < >,<, <=,>,>=) can be used to specify the
conditions in the WHERE clause for selecting the tuples from a relation.
We can use logical operators AND, OR and NOT.
Query 5:
Retrieve city,phone and url of the author whose name is Lewis Ian
Ans:
SELECT city, phone, url
FROM author
WHERE aname= Lewis Ian;

Query 6:
Retrieve name,address and phone of all the publishers located in new York
state
Ans:
SELECT pname,address, phone
FROM publisher
WHERE state=new york;
Query 7:
Retrieve title and price of all the textbooks with pagecount greater than 600
Ans:
SELECT book_title, price
FROM book
WHERE category=textbookAND page_count>600;
Query 8:
Retrieve ISBN, title and price of the books belonging to either novel or
language book category.
Ans:
SELECT isbn, book_title, price
FROM book
WHERE category=novel OR category= language book;

BETWEEN OPERATOR:
The BETWEEN comparison operator can be used to simplify the condition in
WHERE clause that specifies numeric values based on ranges.
Query 9:
Retrieve details of all books with price between 20 and 30.
Ans:
SELECT *
FROM book
WHERE price BETWEEN 20 and 30;
Note:
The NOT BETWEEN operator can also be used to retrieve tuples that do not
belong to the specified range.
IN OPERATOR:
The IN operator is used to specify a list of values. The IN operator selects
values that match any value in a given list of values.
Query 10:
Retrieve book details belonging to the categories textbook or novel
Ans:
SELECT *
FROM book
WHERE category IN (textbook,novel);

LIKE OPERATOR:
SQL provides LIKE operator, which allows to specify comparison conditions
on only parts of the strings. Different patterns are specified by using two special
characters namely percent(%) and underscore( _ ).
The % character is used to match substring with any number of characters
where as _ used to match substring with only one character. For ex,
A% matches any string beginning with character A.

%A matches any string ending with character A.


A%A matches any string beginning and ending with character A.
%AO% matches any string with character AO appearing anywhere in a string
as substring
A_ _ matches any string beginning with character A and followed by exactly
two characters.
_ _ A matches any string ending with character A and preceded by exactly
two characters.
D_ _ A matches any string beginning with character D and ending with
character A and with exactly two characters in between.
Query 11:
Retrieve details of all the authors, whose name begins with the characters Jo
Ans:
SELECT *
FROM author
WHERE Aname LIKE Jo%;
Query 12:
Retrieve details of all the authors, whose name begins with the characters Jo
and ends with characters in
Ans:
SELECT *
FROM author
WHERE Aname LIKE Jo%in;

Query 13:
Retrieve details of all the authors, whose name begins with the characters James
and followed by exactly five characters
Ans:
SELECT *
FROM author
WHERE Aname LIKE James_ _ _ _ _;
NOT LIKE OPERATOR:
In order to search the strings not matching the patterns defined, NOT LIKE
operator can be used.

ORDER BY CLAUSE:
Sometimes it may be required to display tuples arranged in a sorted order. SQL
provides the ORDER BY clause to arrange the tuples of relation in some
particular order. The tuples can be arranged on the basis of values of one or
more attributes.
Query 13:
Display the tuples of the relation book on the basis of price attribute
Ans:
SELECT *
FROM book
ORDER BY price;
Note:
By default, the ORDER BY clause arranges the tuples in ascending order on the
basis of values of specified attribute. If we want the tuples to be sorted in
descending order by using the DESC keyword.

Query 14:
Display the tuples of the relation book on the basis of price attribute in the
descending order
Ans:
SELECT *
FROM book
ORDER BY price DESC;
Note:
Tuples can also be sorted on the basis of more than one attribute.
Query 15:
Display the tuples of the relation book on the basis of two attributes price and
category
Ans:
SELECT *
FROM book
ORDER BY category, price;

You might also like