Database and SQL Concepts
Database and SQL Concepts
COM
Raw facts and figures which are useful to an organization. We cannot take decisions on
the basis of data.
Information:- Well processed data is called information. We can take decisions on the basis of
information
Field:
Set of characters that represents specific data element.
Record:
Collection of fields is called a record. A record can have fields of different data
types.
File:
Collection of similar types of records is called a file.
Table:
Collection of rows and columns that contains useful data/information is called a
table. A table generally refers to the passive entity which is kept in secondary
storage device.
Relation:
Relation (collection of rows and columns) generally refers to an active entity on
which we can perform various operations.
Database:
Collection of logically related data along with its description is termed as database.
Tuple:
A row in a relation is called a tuple.
Attribute:
A column in a relation is called an attribute. It is also termed as field or data item.
Degree:
Number of attributes in a relation is called degree of a relation.
Cardinality: Number of tuples in a relation is called cardinality of a relation.
Primary Key: Primary key is a key that can uniquely identifies the records/tuples in a relation.
This key can never be duplicated and NULL.
Foreign Key: Foreign Key is a key that is defined as a primary key in some other relation. This
key is used to enforce referential integrity in RDBMS.
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are alternate
keys for a relation.
DBA: Data Base Administrator is a person (manager) that is responsible for defining the data base
schema, setting security features in database, ensuring proper functioning of the data bases etc.
Relational Algebra: Relation algebra is a set operation such as select, project, union, &
Cartesian product etc.
Select operation : Yields set of set of rows depending upon certain condition. Mathematically it
is denoted as
e.g
(student)
-means show those rows of student table whose roll no.s
are >10.
Project Operation : yields set of columns as result which are specified. Mathematically it is
denoted as .
e.g.
(student) - means show only rollno and name column only.
Union Operation : Two relation are said to be union compatible if their degree and column are
same.
e.g Relation A
m
o
c
.
y
a
d
o
t
ies
w
w
w
d
u
t
s
.
Relation A
Relation B
Resultant Relation A B=
x3
y3
z3
87
Downloaded from WWW.STUDIESTODAY.COM
Cartesian product: Cartesian Product of two relation A and B gives resultant relation whose no. of
column are sum of degrees of two relation and no. of rows are product of cardinality of two relations.
e.g Relation A
Relation A
Resultant Relation
AB
Relation B
m
o
c
.
y
a
d
o
t
ies
w
w
w
d
u
t
s
.
88
Downloaded from WWW.STUDIESTODAY.COM
1.
NUMBER
Used to store a numeric value in a field/column. It may be decimal, integer or a real value. General syntax
is
Number(n,d)
Where n specifies the number of digits and d specifies the number of digits to the right of the decimal
point.
e.g
marks number(3)
declares marks to be of type number with maximum value 999.
pct number(5,2)
declares pct to be of type number of 5 digits with two digits to the right of
decimal point.
2.
CHAR
Used to store character type data in a column. General syntax is
Char (size)
where size represents the maximum number of characters in a column. The CHAR type data can hold at
most 255 characters.
e.g
name char(25)
declares a data item name of type character of upto 25 size long.
3.
VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is
varchar(size) / varchar2(size)
where size represents the maximum number of characters in a column. The maximum allowed size in this
data type is 2000 characters.
e.g
address varchar(50); address is of type varchar of upto 50 characters long.
4.
DATE
Date data type is used to store dates in columns. SQL supports the various date formats other that the
standard DD-MON-YY.
e.g
dob
date;
declares dob to be of type date.
5.
LONG
This data type is used to store variable length strings of upto 2 GB size.
e.g
description long;
6.
RAW/LONG RAW
To store binary data (images/pictures/animation/clips etc.) RAW or LONG RAW data type is used. A
column LONG RAW type can hold upto 2 GB of binary data.
e.g
image raw(2000);
m
o
c
.
y
a
d
o
t
ies
w
w
w
d
u
t
s
.
SQL Commands
89
Downloaded from WWW.STUDIESTODAY.COM
3.
4.
5.
6.
i.
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
Not Null constraint : It ensures that the column cannot contain a NULL value.
ii.
Unique constraint : A candidate key is a combination of one or more columns, the value of
which uniquely identifies each row of a table.
iii.
Primary Key : It ensures two things : (i) Unique identification of each row in the table. (ii)
No column that is part of the Primary Key constraint can contain a NULL value.
iv.
Foreign Key : The foreign key designates a column or combination of columns as a foreign
key and establishes its relationship with a primary key in different table.
Create table Fee
(RollNo number(2) Foreign key (Rollno) references Student (Rollno),
Name varchar2(20) Not null, Amount
number(4), Fee_Date date);
v.
m
o
c
.
y
a
d
o
t
ies
d
u
t
s
.
w
w
wSQL
Data Manipulation in
90
Downloaded from WWW.STUDIESTODAY.COM
NOTE:- In SQL we can repeat or re-execute the last command typed at SQL prompt by typing / key
and pressing enter.
Roll_no Name
Class Marks City
101
Rohan
XI
400
Jammu
102
Aneeta Chopra
XII
390
Udhampur
103
Pawan Kumar
IX
298
Amritsar
104
Rohan
IX
376
Jammu
105
Sanjay
VII
240
Gurdaspur
113
Anju Mahajan
VIII
432
Pathankot
Operators in SQL:
The following are the commonly used operators in SQL
1. Arithmetic Operators
+, -, *, /
2. Relational Operators
=, <, >, <=, >=, <>
3. Logical Operators
OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
Relational Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL.
Other operators :
4. Range check between low and high
5. List check in
6. Pattern check like , not like ( % and _ under score is used)
m
o
c
.
y
a
d
o
t
ies
Queries:
To retrieve information from a database we can query the databases. SQL SELECT statement is used to
select rows and columns from a database/relation.
SELECT Command
This command can perform selection as well as projection.
Selection:
This capability of SQL can return you the tuples form a relation with all the attributes.
e.g. SELECT name, class FROM student;
The above command displays only name and class attributes from student table.
Projection:
w
w
w
d
u
t
s
.
This is the capability of SQL to return only specific attributes in the relation. Use of where
clause is required when specific tuples are to be fetched or manipulated.
e.g
SELECT * FROM student; command will display all the tuples in the relation student SELECT
* FROM student WHERE Roll_no <=102;
The above command display only those records whose Roll_no less than or equal to 102.
Select command can also display specific attributes from a relation.
*
SELECT count(*) AS Total Number of Records FROM student;
Display the total number of records with title as Total Number of Records i.e an alias
We can also use arithmetic operators in select statement, like
*
SELECT Roll_no, name, marks+20 FROM student;
*
SELECT name, (marks/500)*100 FROM student WHERE Roll_no > 103;
Eliminating Duplicate/Redundant data
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g.
SELECT DISTINCT name FROM student;
Downloaded from WWW.STUDIESTODAY.COM
91
Downloaded from WWW.STUDIESTODAY.COM
m
o
c
.
y
a
d
o
t
ies
w
w
w
d
u
t
s
.
SQL Functions :
SQL supports functions which can be used to compute and select numeric, character and date
columns of a relations. These functions can be applied on a group of rows. The rows are grouped on a
common value of a column in the table. These functions return only one value for a group and
therefore, they are called aggregate or group functions.
1.
SUM() :
It returns the sum of values of numeric type of a column.
Eg.
Select sum(salary) from employee;
2.
AVG() :
It returns the average of values of numeric type of a column.
Downloaded from WWW.STUDIESTODAY.COM
92
Downloaded from WWW.STUDIESTODAY.COM
Eg.
5.
Group By Clause :
The rows of a table can be grouped together based on a common value by using the Group By clause of
SQL in a select statement.
Syntax :
SELECT <attribute name>, <attribute name> ---- [functions]
FROM <relation name>
GROUP BY <group by column>;
Eg. Select age, count (rollno)
From
students
Group
by
age;
Output :Age Count(rollno)
15
2
14.5
2
14
5
m
o
c
.
y
a
d
o
t
ies
d
u
t
s
.
Group-By-Having Clause :
It is used to apply some condition to the Group By clause.
Eg.
Select class
From students Group by class
Having count(*) > 5;
w
w
w
DELETE Command
To delete the record fro a table SQL provides a delete statement. General syntax is:DELETE FROM <table_name> [WHERE <condition>];
e.g. DELETE FROM student WHERE city = Jammu;
This command deletes all those records whose city is Jammu.
NOTE:
It should be kept in mind that while comparing with the string type values
lowercase and uppercase letters are treated as different. That is Jammu and jammu is different
while comparing.
UPDATE Command
To update the data stored in the data base, UPDATE command is used.
e. g. UPDATE student SET marks = marks + 100;
Increase marks of all the students by 100.
93
Downloaded from WWW.STUDIESTODAY.COM
m
o
c
.
y
a
d
We can also create a view from an existing table based on some specific conditions, like
CREATE VIEW v_student AS SELECT Roll_no, Name, Class FROM student WHERE City <>Jammu;
The main difference between a Table and view is that
o
t
ies
d
u
t
s
.
w
w
w
Rohan
XI
400
Jammu
102
Aneeta Chopra
XII
390
Udhampur
103
Pawan Kumar
IX
298
Amritsar
104
Rohan
IX
376
Jammu
105
Sanjay
VII
240
Gurdaspur
113
Anju MAhajan
VIII
432
Pathankot
Address
94
Downloaded from WWW.STUDIESTODAY.COM
Note that we have just added a column and there will be no data under this attribute. UPDATE
command can be used to supply values / data to this column.
Removing a column
ALTER TABLE table_name
DROP COLUMN column_name;
e.g
m
o
c
1&2 mark questions y.
a
d
o
t
s
e
i
d
u
t
s
.
w
w
w
95
Downloaded from WWW.STUDIESTODAY.COM
v. Candidate Key
Ans : All attributes combinations inside a relation that can serve as primary key are candidate key
as they are candidates for being as a primary key or a part of it.
vi. Relational Algebra
Ans : It is the collections of rules and operations on relations(tables). The various operations are
selection, projection, Cartesian product, union, set difference and intersection, and joining of
relations.
vii. Domain
Ans : it is the pool or collection of data from which the actual values appearing in a given column
are drawn.
(a)
(b)
(c)
(d)
(e)
Sol :
(b)
(c)
m
o
c
.
Database and SQL : 6 marks questions
y
a
d
o
t
s
e
i
d
u
t
s
.
w
w
w
96
Downloaded from WWW.STUDIESTODAY.COM
(d)
(e)
(f)
2. Consider the following tables Sender and Recipient. Write SQL commands for the statements (i) to
(iv) and give the outputs for SQL queries (v) to (viii).
m
o
c
.
y
a
d
o
t
ies
(i)
To display the names of all Senders from Mumbai
Ans. SELECT sendername from Sender where sendercity=Mumbai;
(ii)
To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every
Recipient.
Ans. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName,
R.RecAddress from Sender S, Recepient R
where S.SenderID=R.SenderID;
(iii) To display Recipient details in ascending order of RecName
Ans. SELECT * from Recipent ORDER By RecName;
w
w
w
d
u
t
s
.
(vii)
R Jain
H Singh
S Jha
P K Swamy
SELECT RecName, RecAddress
From Recipient Where RecCity NOT IN (Mumbai, Kolkata);
97
Downloaded from WWW.STUDIESTODAY.COM
3.
Ans.
RecName
S Mahajan
S Tripathi
RecAddress
116, A Vihar
13, BID, Mayur Vihar
(viii)
Ans.
RecID
S Mahajan ND48
Tripathi
RecName ND08
S
Write SQL command for (i) to (vii) on the basis of the table SPORTS
Table: SPORTS
Student
NO
10
11
12
13
14
15
Class
Name
Game1
Grade Game2
Grade2
7
8
7
7
9
10
Sammer
Sujit
Kamal
Venna
Archana
Arpit
Cricket
Tennis
Swimming
Tennis
Basketball
Cricket
B
A
B
C
A
A
m
o
c
.
y
a
d
A
C
B
A
A
C
o
t
ies
Swimming
Skating
Football
Tennis
Cricket
Atheletics
(a) Display the names of the students who have grade C in either Game1 or Game2 or both.
(b) Display the number of students getting grade A in Cricket.
(c) Display the names of the students who have same game for both Game1 and Game2.
(d) Display the games taken up by the students, whose name starts with A.
(e) Add a new column named Marks.
(f) Assign a value 200 for Marks for all those who are getting grade B or grade A in both Game1
and Game2.
Ans : a)
SELECT Name from SPORTS where grade=C or Grade2=C;
b)
SELECT Count(*) from SPORTS where grade=A;
c)
SELECT name from SPORTS where game1 = game2;
d)
SELECT game,game2 from SPORTS where name like A%;
e)
ALTER TABLE SPORTS add (marks int(4));
f)
UPDATE SPORTS set marks=200 where grade=A;
w
w
w
d
u
t
s
.
4. Consider the following tables Stationary and Consumer. Write SQL commands for the statement (i) to
(iv) and output for SQL queries (v) to (viii):
S_ID
DP01
PL02
ER05
PL01
GP02
Table: Stationary
StationaryName Company
Dot Pen
ABC
Pencil
XYZ
Eraser
XYZ
Pencil
CAM
Gel Pen
ABC
Price
10
6
7
5
15
98
Downloaded from WWW.STUDIESTODAY.COM
C_ID
01
06
12
15
16
Table: Consumer
ConsumerName Address
Good Learner
Delhi
Write Well
Mumbai
Topper
Delhi
Write & Draw
Delhi
Motivation
Banglore
S_ID
PL01
GP02
DP01
PL02
PL01
(i)
(ii)
m
o
c
.
y
a
d
Consider the following tables GARMENT and FABRIC. Write SQL commands for the statements (i) to
(iv) and give outputs for SQL queries (v) to (viii).
GCODE
10023
10001
10012
10024
10090
10019
10009
10007
10020
10089
FCODE
F04
F02
F03
F01
o
t
ies
Table : GARMENT
DESCRIPTION
PRICE
PENCIL
SKIRT
1150
FORMAL
SHIRT
1250
INFORMAL SHIRT
1550
BABY
TOP
750
TULIP
SKIRT
850
EVENING
GOWN
850
INFORMAL PANT
1500
FORMAL
PANT
1350
FROCK
850
SLACKS
750
Table : FABRIC
TYPE
POLYSTER
COTTON
SILK
TERELENE
w
w
w
d
u
t
s
.
FCODE
F03
F01
F02
F03
F02
F03
F02
F01
F04
F03
READYDATE
19DEC08
12JAN08
06JUN08
07APR07
31MAR07
06JUN08
20OCT08
09MAR08
09SEP07
20OCT08
(i) To display GCODE and DESCRIPTION of a each dress in descending order of GCODE.
(ii) To display the details of all the GARMENTs, which have READYDATE in between 08
DEC07 and 16JUN08 (inclusive of both the dates).
(iii) To display the average PRICE of all the GARMENTs, which are made up of FABRIC with
FCODE as F03.
99
Downloaded from WWW.STUDIESTODAY.COM
(iv) To display FABRIC wise highest and lowest price of GARMENTs from DRESS table.
(Display FCODE of each GARMENT along with highest and lowest price)
(v) SELECT SUM (PRICE) FROM GARMENT WHERE FCODE= F01;
(vi) SELECT DESCRIPTION, TYPE FROM GARMENT, FABRIC WHERE
GARMENT.FCODE = FABRIC. FCODE AND GARMENT. PRICE>=1260;
(vii) SELECT MAX (FCODE) FROM FABRIC;
(viii) SELECT COUNT (DISTINCT PRICE) FROM FABRIC;
6.
Consider the following WORKERS and DESIG. Write SQL commands for the statements (i)
to (iv) and give outputs for SQL queries (v) to (vi)
WORKERS
W_ID FIRSTNAME LASTNAME ADDRESS
CITY
102
Sam
Tones
33 Elm St.
Paris
105
Sarah
Ackerman
440 U.S. 110
New York
144
Manila
Sengupta
24 Friends Street New Delhi
210
George
Smith
83 First Street
Howard
255
Mary
Jones
842 Vine Ave.
Losantiville
300
Robert
Samuel
9 Fifth Cross
Washington
335
Henry
Williams
12Moore Street
Boston
403
Ronny
Lee
121 Harrison St.
New York
451
Pat
Thompson
11 Red Road
Paris
m
o
c
.
y
a
d
o
t
ies
W_ID
SALARY
DESIG
BENEFITS
102
105
144
210
255
300
335
403
451
75000
85000
70000
75000
50000
45000
40000
32000
28000
15000
25000
15000
12500
12000
10000
10000
7500
7500
w
w
w
d
u
t
s
.
DESIGNATI
ON
Manager
Director
Manager
Manager
Clerk
Clerk
Clerk
Salesman
Salesman
(i) To display the content of workers table in ascending order of first name.
(ii) To display the FIRSTNAME, CITY and TOTAL SALARY of all Clerks from the tables workers
and design, where TOTAL SALARY = SALARY + BENEFITS.
(iii) To display the minimum SALARY among Managers and Clerks from the table DESIG.
(iv) Increase the BENEFITS of all Salesmen by 10% in table DESIG.
(v) SELECT FIRSTNAME, SALARY FROM WORKERS, DESIG WHERE DESIGNATION =
Manager AND WORKERS.W_ID = DESIG.W_ID;
(vi) SELECT DESIGNATION, SUM(SALARY) FROM DESIG
GROUP BY DESIGNATION HAVING COUNT(*)>=2 ;
100
Downloaded from WWW.STUDIESTODAY.COM