Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 61

DATABASE

CONCEPTS
Basic Database concepts

Data :- 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.
• DATABASE : A database is a collection of interrelated data.

• Database System is basically a computer based record keeping


system .It is a computer program designed to manage a
database . It enables you to store , modify and extract
information from a database.
• Eg: SQL ,Oracle.
Advantages of database
1. Databases reduce the data redundancy:
The database system do not maintain separate copies of the same data, rather all the data are kept at one place and all
application that require data refer to be the centrally maintained database. If any change is to be made it will be made at just
one place and the changed information will be available to other applications. Duplication of the data is known as data
redundancy.
2. Database can control data inconsistency:
When data redundancy is not controlled, there may be occasions on which the two entries of the same data do not agree i.e.
when one of them stores the updated version and the other does not. In that case a database is said to be inconsistent. By
controlling the data redundancy, inconsistency is also controlled.
3. Database facilitates sharing of data:
In a database system all the users handling different related applications refer and share the same data stored in a central
location.
4. Database enforce standard
Database management system can ensure that all the data follow the applicable standard laid by the organization. For
example an organization can enforce the rule that all its employees must be a graduate.
5. Integrity can be maintained:
When a database contains data to be used by many users it is important to keep integrity to check to insure that data values
satisfy to certain specified rules for example and invalid dates should not to allowed to entered as 31/02/96
6. Database can ensure security.
A database ensures security and privacy by ensuring that only the authorized person can access the database .
Database Abstraction
A database management system (DBMS) is a collection of interrelated files and a set of programs
that allow users to access and modify these files. A major purpose of database system is to provide
the users only that much information that is required. The system does not disclose all the details of
data rather it hides certain details on how data is stored and maintained. This feature of database
management is system is known as Data Abstraction. Based on this feature there are users of a
DBMS.
1. Database/End users
Any person who can access some information from the database is called
Database or end user.
2. Database Administrator
DBA manages the database and seeks to meet the needs of the database
users.
3. Application programs
Processes executed by the computer.
Different data models
Relational data model
Data is stored in the form of tables, these table are called relations ,in which rows are
tuples and columns are fields.
Hierarchical data model
This model uses a tree like structure to represent relationship among records.
Network data model
A network database is a collection of nodes and links, such that any node
can be linked to any other node multiple times.
Terminologies:
Relation : A table having rows and columns.
Domain : A pool of values from which actual value present in a given column are
taken.
Attributes : Columns of a table. Vertical part of the relation.
Tuples : Rows of a table. Horizontal part of the relation.
Degree : No of attributes(columns ) in a table.
Cardinality : No of tuples(rows) in a table.
Key : An attribute or a group of attributes which are used to distinguish records in a
relation.
View: A view is a virtual table that does not really exist in its own right but is instead
derived from one or more underlying base table(s).
Relation : Student
Rollno Name Class Section Gender Address
14 Rohan 12 D M Dubai
45 Arpita 11 A F Sharjah
23 Kush 12 G M Dubai

What is the degree of this table? Degree – 6

What is the cardinality of this table? Cardinality - 3


Keys:These in general, refer to the column(s) which specify how rows of a relation are distinct from each other. The different types of keys which are used in relational algebra are explained below:

Primary key: It is a key field which uniquely identifies a particular record /tuple. . For eg. in table
student, the column rollno contains unique values 1 and 2 to identify the two rows. The primary key is
non redundant i.e. it does not have duplicate values in the same table.
Candidate key: All attributes combination inside a relation that can serve as a primary key. They are
candidates for the primary key. Attributes that uniquely identifies an instance of an entity set.
Alternate key:Attributes which are not selected as primary keys.All the candidate keys other than the
primary keys of a relation are alternate keys for a relation.
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.
Roll no Name Address Mobileno Rfidno
12 Rahul V Dubai 050-1234567 s456
5 Rohan Dubai 050-9562411 s923
18 Rahul S Sharjah 055-4598125 s121

Roll no , Mobileno , Rfid no – Candidate Keys


Roll no - Primary Key
Mobileno , Rfid no – Alternate key RfidNo- Foreign key
STRUCTURED QUERY
LANGUAGE
(SQL)
Structured Query Language

SQL is a non procedural language that is used to create, manipulate and


process the databases(relations).

Characteristics of SQL

 It is very easy to learn and use.

 Large volume of databases can be handled quite easily.

 It is non procedural language. It means that we do not need to specify the


procedures to accomplish a task but just to give a command to perform the
activity.

 SQL can be linked to most of other high level languages that makes it first
choice for the database programmers.
Sql (Structured query language)
SQL statements are divided into 3 sub languages
• DDL (Data Definition Language) - DDL contains commands that are
used to create the tables, databases, indexes, views, sequences and
synonyms etc.
CREATE , ALTER , DROP

• DML (Data Manipulation Language) – DML contains command that can


be used to manipulate the data base objects and to query the databases
for information retrieval.
SELECT ,INSERT, UPDATE , DELETE
Data types of SQL

Just like any other programming language, the facility of


defining data of various types is available in SQL also.
Following are the most common data types of SQL.

1. CHAR(n)
2. VARCHAR(n)
3. DATE
4. int
5. float
Data types
Data types are declared to identify the type of data stored for a
particular column or variable.
Data type Description
VARCHAR2(W) / VARCHAR(W) Variable length character up to width W.
CHAR(W) Fixed length character value of width W.
FLOAT To represent floating point decimals .
DATE Date value (Format is ‘yyyy-mm-dd’)
INT Whole numbers
DIFFERENCE BETWEEN CHAR AND VARCHAR
2. CHAR
Used to store fixed length 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 is fixed
length data type once the size n is declared the value of the attribute column will hold n characters.
e.g. name char(25) declares a data item name of type character of 25 size long even if the value for
tuple is entered as 10 characters it will hold the other 10 characters in memory.

3. VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is,
varchar(size)
where size represents the maximum number of characters in a column but will allocate only the
characters assigned to the attribute.
e.g address varchar(50);
address is of type varchar of upto 50 characters long if the address attribute for a tuple only has 15
characters it will only occupy the 15 characters.
SQL Commands

Constraints:

Constraints are the conditions that can be enforced on the


attributes of a relation. The constraints come in play when
ever we try to insert, delete or update a record in a relation.

1.NOT NULL
2.UNIQUE
3.PRIMARY KEY
SQL Commands
Constraints:
1. NOT NULL: Ensures that we cannot leave a column as null. That is a value has
to be supplied for that column.
e.g name varchar(25) not null;

2. UNIQUE: Constraint means that the values under that column are always
unique.
e.g Roll_no number(3) unique;

3. PRIMARY KEY: Constraint means that a column can not have duplicate values
and not even a null value.
e.g. Roll_no number(3) primary key;
The main difference between unique and primary key constraint is that a column
specified as unique may have null value but primary key constraint does not allow
null values in the column.
SQL Commands
CREATE TABLE Command:
Create table command is used to create a table in SQL. It is a DDL type of
command. The general syntax of creating a table is
create table <tablename> (
<column 1> <data type> [not null] [unique] [<column constraint>],
.........
<column n> <data type> [not null] [unique] [<column constraint>],
[<table constraint(s)>]
);
Eg :
CREATE TABLE STUD(RNO INT , NAME VARCHAR(20) , SECTION
CHAR(1) , DOB DATE , MARKS FLOAT);

NOTE : SQL COMMANDS ARE NOT CASE SENSITIVE.


SQL Commands
CREATE TABLE Command:
For each column, a name and a data type must be specified and the column name
must be unique within the table definition. Column definitions are separated by
comma. Uppercase and lowercase letters makes no difference in column names,
the only place where upper and lower case letters matter are strings comparisons. A
not null Constraint means that the column cannot have null value, that is a value
needs to be supplied for that column. The keyword unique specifies that no two
tuples can have the same attribute value for this column.
Syntax:
CREATE TABLE TABLE_NAME ( COLUMN_NAME1 DATATYPE ,
COLUMN_NAME2 DATATYPE , COLUMN_NAME3 DATATYPE ,
COLUMN_NAME4 DATATYPE , ……);
Mysql command prompt
Some Command you must Know:
• will show all the databases existing in mysql
• show databases;
• will create a database student info
• create database student_info;
• will use the databse student_info to create tables
• use student_info;
• will show all the tables in the existing database
• show tables;
• will show the attributes/fields of a table and its datatypes
• describe tablename;
SQL Commands-Create Table

CREATE TABLE student (


Roll_no int primary key,
Name varchar(25) not null,
Class varchar(10),
Marks float,
City varchar(25) );
SQL Commands

Operators in SQL:

The following are the commonly used operators in SQL


Arithmetic Operators +, -, *, /
Relational Operators =, <, >, <=, >=, <>
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.
Create table command using constraints
CREATE TABLE EMPLOYEE
Relation name – Employee (
Attributes :
ENO int PRIMARY KEY ,
Eno – primary key
Ename – NOT NULL
ENAME VARCHAR(20) NOT NULL ,
Gender GENDER CHAR(1) ,
Sal SAL float ,
Bonus BONUS int,
Address MOBILENO int UNIQUE,
Mobileno – UNIQUE DESIGNATION VARCHAR(20) ,
Designation DEPTNO CHAR(4) ,
Deptno WORKDUR int
Hobbies );
Workdur
SQL Commands
Data Modifications in SQL
After a table has been created using the create table command, tuples can be
inserted into the table, or tuples can be deleted or modified.
INSERT Statement

The simplest way to insert a tuple into a table is to use the insert statement

insert into <table> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);

e.g. INSERT INTO student VALUES(101,'Rohan','XI',400,‘Chennai');

While inserting the record it should be checked that the values passed are of same
data types as the one which is specified for that particular column.

29
Inserting data in a table
METHOD I – Inserting all values
INSERT INTO EMPLOYEE VALUES (1, ‘ROHAN’ , ‘M’, 6500, 150, ’SHARJAH’,
0501234567, ’MANAGER’, ’D001’ ,’CRICKET’, 9);

METHOD II – Inserting selected values and in different sequence


INSERT INTO EMPLOYEE (ENO,ENAME,GENDER,SAL,BONUS) VALUES
(2,’RATUL’,’M’,5500,125);

30
DESCRIBING THE STRUCTURE OF THE TABLE
DESC EMPLOYEE ; OR DESCRIBE EMPLOYEE ;

• DROPPING A TABLE
DROP TABLE EMPLOYEE;

SAVING THE DML COMMANDS


COMMIT;

COMMAND FOR SHOWING ALL TABLES IN YOUR DBMS


SHOW TABLES;

COMMAND FOR SHOWING ALL DATABASES IN YOUR DBMS 31

SHOW DATABASES;
SQL Commands

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.

Projection: This is the capability of SQL to return only specific attributes in the
relation. 32
STUDENT TABLE
In the above table command
Roll_ Name Cla Mark City Select * from student where name=‘rohan’;
no ss s Will give row
101 rohan x1 400 Chennai
101 Rohan XI 400 Chennai
102 Aneeta XII 390 Bengaluru So this is example of selection and If we give command
as
103 Pawan IX 298 Mysore Select name,class from student
Kumar will return the vertical subset .It will return columns
104 Rohan IX 376 Mangalore having name and class in it.

105 Sanjay VII 240 Mumbai


Name Class
113 Anju VIII 432 Delhi
Rohan XI
Aneeta XII
Pawan Kumar IX

Rohan IX
Sanjay VII

Anju VIII 33
TABLE : STUDENT SQL Commands
Roll_no Name Clas Marks City SELECT Command
s  SELECT * FROM student;
101 Rohan XI 400 Chennai command will display all the tuples in the relation student
102 Aneeta XII 390 Bengaluru  SELECT * FROM student WHERE Roll_no <=102;
103 Pawan Kumar IX 298 Mysore The above command display only those records whose Roll_no
104 Rohan IX 376 Mangalore less than or equal to 102.
Select command can also display specific attributes from a
105 Sanjay VII 240 Mumbai
relation. Roll_no Name Clas Marks City
s
113 Anju VIII 432 Delhi
101 Rohan XI 400 Chennai

Name Class 102 Aneeta XII 390 Bengaluru

Rohan XI
 SELECT name, class FROM student;
Aneeta XII
Pawan IX The above command displays only name and
Kumar
class attributes from student table.
Rohan IX
Sanjay VII

Anju VIII
34
VARIOUS SELECT STATEMENTS
SELECTING ALL THE DATA IN THE TABLE ENO EName SAL BONU Designatio
S n
SELECT * FROM EMPLOYEE; 101 Rohan 2000 100 PEON
102 Aneeta 3000 200 WORKER
SELECTING SELECTED VALUES FROM THE TABLE 103 Pawan 7000 300 MANAGER
Kumar
SELECT ENO ,ENAME,SAL,BONUS FROM EMPLOYEE; 104 Rohan 8000 400 MANAGER
SELECT DISTINCT DESIGNATION FROM EMPLOYEE; 105 Sanjay 5600 500 IT

SELECT DESIGNATION FROM EMPLOYEE; 113 Anju 4000 300 WORKER

OR SELECT ALL DESIGNATION FROM EMPLOYEE;


SELECTION USING RELATIONAL OPERATORS
SELECT * FROM EMPLOYEE WHERE SAL>5600;
SELECT * FROM EMPLOYEE WHERE SAL BETWEEN 5500 AND 6000;
SELECT * FROM EMPLOYEE WHERE BONUS NOT BETWEEN 150 AND 200;
SELECT * FROM EMPLOYEE WHERE SAL<>5000 AND DESIGNATION =‘MANAGER’;
SELECT * FROM EMPLOYEE WHERE SAL>5000 AND DESIGNATION =‘MANAGER’ 35AND
ADDRESS =‘DUBAI’;
SQL Commands

Roll_n Name Clas Marks City


o s
SELECT Command Chennai
101 Rohan XI 400
102 Aneeta XII 390 Bengaluru
 SELECT count(*) AS “Total Number of 103 Pawan Kumar IX 298 Mysore
 Records” FROM student; 104 Rohan IX 376 Mangalore
105 Sanjay VII 240 Mumbai

Display the total number of records with title as 113 Anju VIII 432 Delhi
“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;

36
SQL Commands
Eliminating Duplicate/Redundant data

Roll_n Name Clas Marks City


DISTINCT keyword is used to restrict the o s
duplicate rows from the results of 101 Rohan XI 400 Chennai

a SELECT statement. 102 Aneeta XII 390 Bengaluru


103 Pawan Kumar IX 298 Mysore
104 Rohan IX 376 Mangalore
e.g. SELECT DISTINCT name FROM student;
105 Sanjay VII 240 Mumbai

The above command returns,(notice rohan is not 113 Anju VIII 432 Delhi

Repeated again)

Name
Rohan
Aneeta
Pawan Kumar
Sanjay
37
Anju
SQL Commands
Roll_n Name Clas Marks City
o s
101 Rohan XI 400 Chennai
Conditions based on a range
102 Aneeta XII 390 Bengaluru
SQL provides a BETWEEN operator that defines a range of values that
the column value must fall for the condition to become true. 103 Pawan IX 298 Mysore
Kumar
e.g. SELECT Roll_no, name FROM student WHERE Roll_no
104 Rohan IX 376 Mangalore
BETWEEN 100 AND 103;
The above command displays Roll_no and name of those students whose 105 Sanjay VII 240 Mumbai

Roll_no lies in the range 100 to 103 (both 100 and 103 are included in the
113 Anju VIII 432 Delhi
range).

Conditions based on a list


To specify a list of values, IN operator is used. This operator select
values that match any value in the given list.
e.g. SELECT * FROM student WHERE city IN
(‘Bengaluru’,’Delhi’,’Chennai’);
The above command displays all those records whose city is either
Bengaluru or Delhi or Chennai
38
SQL Commands
Roll_n Name Clas Marks City
o s
Conditions based on Pattern
101 Rohan XI 400 Chennai
SQL provides two wild card characters that are used while
comparing the strings with LIKE operator. 102 Aneeta XII 390 Bengaluru
103 Pawan IX 298 Mysore
Kumar
a. percent ( % ) Matches any string
104 Rohan IX 376 Mangalore
b. Underscore ( _ ) Matches any one character
105 Sanjay VII 240 Mumbai
e.g SELECT Roll_no, name, city FROM student WHERE
Roll_no LIKE “%3”; 113 Anju VIII 432 Delhi
displays those records where last digit of Roll_no is 3 and may
have any number of characters in front.

e.g SELECT Roll_no, name, city FROM student WHERE


Roll_no LIKE “1_3”;

displays those records whose Roll_no starts with 1 and second letter
may be any letter but ends with digit 3.
39
SELECTION USING WILD CARD PATTERNS % AND _(UNDERSCORE)
SELECT * FROM EMPLOYEE WHERE HOBBIES LIKE ‘C%’;
SELECT * FROM EMPLOYEE WHERE ENAME NOT LIKE ‘A%’; OR
SELECT * FROM EMPLOYEE WHERE NOT ENAME LIKE ‘A%’;
SELECT * FROM EMPLOYEE WHERE DESIGNATION LIKE ‘M______’;
ENO EName SAL BONUS Designati Hobbie Gender Addre
SELECT * FROM EMPLOYEE WHERE SAL LIKE ‘7%’; on s s
101 Rohan 2000 100 PEON Cake M SHARJ
SELECTION OF CALCULATED RESULT H
102 Aneeta 3000 200 WORKER Sing F DUBA
SELECT * FROM EMPLOYEE WHERE SAL*12>10000; 103 Pawan 7000 300 MANAGE Dance M SHARJ
Kumar R H
SELECT SAL ,SAL*6 FROM EMPLOYEE ; 104 Rohan 8000 400 MANAGE Sing M DUBA
R
SELECTION FROM A LIST
SELECT * FROM EMPLOYEE WHERE GENDER IN (‘M’,’F’) ; OR
SELECT * FROM EMPLOYEE WHERE GENDER=‘M’ OR GENDER=‘F’;
SELECT * FROM EMPLOYEE WHERE ADDRESS IN (‘SHARJAH’,’DUBAI’);
SELECT NAME ,SAL FROM EMPLOYEE WHERE SAL IN(5000,6000,7000);
40
SELECT * FROM EMPLOYEE WHERE DESIGNATION NOT IN (‘MANANGER’ ,’SALES’,’MP’);
SQL Commands
Roll_n Name Clas Marks City
o s
ORDER BY Clause Chennai
101 Rohan XI 400
ORDER BY clause is used to display the result of a query in a
102 Aneeta XII 390 Bengaluru
specific order(sorted order).
The sorting can be done in ascending or in descending order. 103 Pawan IX 298 Mysore
Kumar
It should be kept in mind that the actual data in the database is
104 Rohan IX 376 Mangalore
not sorted but only the results of the query are displayed in sorted
105 Sanjay VII 240 Mumbai
order.
113 Anju VIII 432 Delhi
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student
sorted by name in increasing/ascending order.

e.g. SELECT * FROM student ORDER BY city DESC;


It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in
ascending order.

41
ARRANGING DATA IN ASCENDING/DESCENDING ORDER - ORDER BY CLAUSE
ENO EName SAL BONUS Designati Hobbie Gender Addres
on s s
101 Rohan 2000 100 PEON Cake M SHARJA
H
102 Aneeta 3000 200 WORKER Sing F DUBAI
103 Pawan 7000 300 MANAGE Dance M SHARJA
Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R

• SELECT * FROM EMPLOYEE ORDER BY ENAME;(will display all the details of table in increasing order of ename)
• SELECT * FROM EMPLOYEE ORDER BY SAL DESC; (will display all the details of table in decreasing order of sal)
• SELECT * FROM EMPLOYEE ORDER BY NAME , SAL DESC;(look below for result. Records are arranged
ENO EName SAL BONUS Designati Hobbie Gender Addres
• In increasing order of names.but when two people have on s s
102 Aneeta 3000 200 WORKE Sing F DUBAI
• same name,their records are arranged in desceding R
103 Pawan 7000 300 MANAGE Dance M SHARJA
• Order of sal Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R
101 Rohan 2000 100 PEON Cake M 42SHARJA
H
ARRANGING DATA IN ASCENDING/DESCENDING ORDER - ORDER BY CLAUSE
ENO EName SAL BONUS Designati Hobbie Gender Addres
on s s
101 Rohan 2000 100 PEON Cake M SHARJA
H
102 Aneeta 3000 200 WORKER Sing F DUBAI
103 Pawan 7000 300 MANAGE Dance M SHARJA
Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R

SELECT * FROM EMPLOYEE WHERE NAME LIKE ‘A%’ ORDER BY DEPTNO;


All the people whose name is starting with A in the increasing order of deptno will be
displayed
SELECT * FROM EMPLOYEE WHERE GENDER=‘M’ AND SAL>6000 ORDER BY
DESIGNATION;
All the male people with salary above 6000 in the increasing order of sal will be
displayed
SELECT NAME ,SAL FROM EMPLOYEE WHERE SAL>5000 ORDERBY SAL DESC;

43
SQL Commands
GROUP BY Clause

The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the
results by one or more columns.
The syntax for the GROUP BY clause is: Roll_n Name Clas Marks City
o s
SELECT column1, column2, ... column_n, aggregate_function 101 Rohan XI 400 Bengaluru
(expression)
FROM tables 102 Aneeta XII 390 Bengaluru
WHERE conditions 103 Pawan IX 298 Mysore
GROUP BY column1, column2, ... column_n; Kumar
104 Rohan IX 376 Mangalore
e.g SELECT name, COUNT(*) as "Number of employees“ 105 Sanjay VII 240 Mangalore
FROM student WHERE marks>350
GROUP BY city; 113 Anju VIII 432 Delhi
Name Number of employees
Rohan 2
Pawan Kumar 1
Rohan 2
Anju 1 44
AGGREGATE FUNCTIONS
They are functions which work on many tuples and yield one result.Various aggregate functions
are
ENO EName SAL BONUS Design Hobb Gend Addr
• SUM - SELECT SUM(SAL) FROM EMPLOYEE;(20000) ation ies er ess
• AVG – SELECT AVG(SAL) FROM EMPLOYEE;5000 Cake M SHARJ
101 Rohan 2000 100 PEON
AH
• MAX – SELECT MAX(BONUS) FROM EMPLOYEE;400
102 Aneeta 3000 200 WORK Sing F DUBAI
• MIN – SELECT MIN(SAL) FROM EMPLOYEE;2000 ER
• COUNT – This functions counts all non NULL values. 103 Pawan 7000 300 MANA Dance M SHARJ
Kumar GER AH
SELECT COUNT(SAL) FROM EMPLOYEE;4 104 Rohan 8000 400 MANA Sing M DUBAI
• GER
COUNT(*) – This function counts all, even the
• NULL values .
SELECT COUNT(*) FROM EMPLOYEE;4

e.g. SELECT sum(marks) FROM student;


displays the sum of all the marks in the table student.
e.g. SELECT min(Roll_no), max(marks) FROM student;
displays smallest Roll_no and highest marks in the table student. 45
SQL Commands
HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT
statement to filter the records that a GROUP BY returns.
Roll_n Name Clas Marks City
The syntax for the HAVING clause is: o s
SELECT column1, column2, ... column_n, aggregate_function 101 Rohan XI 400 Mumbai
(expression)
102 Aneeta XII 390 Bengalore
FROM tables
103 Pawan IX 298 Mysore
WHERE predicates Kumar
GROUP BY column1, column2, ... column_n 104 Rohan IX 376 Banglore
HAVING condition1 ... condition_n;
105 Sanjay VII 240 Mumbai

e.g. SELECT city,SUM(marks) as "Total marks"


113 Anju VIII 432 Delhi
FROM student
GROUP BY CITY
HAVING SUM(marks) > 500;

City Total Marks


Mumbai 640
Banglore 766
46
Grouping of data - Group by clause
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES; ENO EName SAL BONUS Design Hobb Gend Addr
ation ies er ess
Sum(sal) Hobbies
101 Rohan 2000 100 PEON Cake M SHARJ
2000 Cake AH

11000 Sing 102 Aneeta 3000 200 WORK Sing F DUBAI


ER
7000 Dance
103 Pawan 7000 300 MANA Dance M SHARJ
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES HAVING Kumar GER AH
HOBBIES=‘Sing’;
104 Rohan 8000 400 MANA Sing M DUBAI
• Sum(sal) Hobbies GER

• 11000 Sing
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES HAVING
SUM(SAL)>10000;
• Sum(sal) Hobbies
• 11000 Sing
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES HAVING HOBBIES LIKE
‘C%’;
• Sum(sal) Hobbies
• 2000 Cake
NOTE:
• ONLY AGGREGATE FNS AND GROUP BY ATTRIBUTES CAN BE USED IN GROUP BY COMMANDS. 47
• CONDITIONS ARE GIVEN TO GROUP BY STATEMENTS USING HAVING CLAUSE.
Grouping of data - Group by clause
ENO EName SAL BONUS Design Hobb Gend Addr
ation ies er ess
• SELECT SUM(SAL),ADDRESS FROM EMPLOYEE GROUP BY 101 Rohan 2000 100 PEON Cake M SHARJ
ADDRESS ORDER BY SAL; AH

• Sum(sal) address 102 Aneeta 3000 200 WORK Sing F DUBAI


ER
• 11000 Dubai 103 Pawan 7000 300 MANA Dance M SHARJ
Kumar GER AH
• 9000 Sharjah
104 Rohan 8000 400 MANA Sing M DUBAI
GER

• SELECT SUM(SAL),ADDRESS FROM EMPLOYEE GROUP BY


ADDRESS HAVING ADDRESS =‘SHARJAH’ ORDER BY SAL;

Sum(sal) address
9000 Sharjah

NOTE:
• ONLY AGGREGATE FNS AND GROUP BY ATTRIBUTES CAN BE USED IN GROUP BY COMMANDS.
• CONDITIONS ARE GIVEN TO GROUP BY STATEMENTS USING HAVING CLAUSE. 48
SELECTION USING NULL ENO EName SAL BONUS Design Hobb Gend Addr
ation ies er ess
SELECT * FROM EMPLOYEE WHERE SAL IS NULL;
SELECT * FROM EMPLOYEE WHERE SAL IS NOT 101 Rohan 2000 100 PEON Cake M SHAR
JAH
NULL; OR 102 Aneeta 3000 200 WORK Sing F DUBA
ER I
SELECT * FROM EMPLOYEE WHERE NOT SAL 103 Pawan 7000 300 MANA Dance M SHAR
JAH
Kumar GER
IS NULL; 104 Rohan 8000 400 MANA Sing M DUBA
I
GER

SHOWING MESSAGE IN A QUERY


SELECT NAME,’GETS A SAL OF’ ,SAL FROM EMPLOYEE;
SELECT NAME ,’IS FROM DEPARTMENT’,DEPTNO FROM EMPLOYEE;
SELECT NAME ,’IS FROM DEPARTMENT’ “ “,DEPTNO FROM EMPLOYEE; - HEADING WILL NOT HAVE
MESSAGE
SELECT NAME,SAL,SAL*12 ”YEARLY SALARY” FROM EMPLOYEE; - NEW NAME GIVEN FOR THAT
COLUMN.
49
Unsolved questions • Display list of all the commerce stream students from
Table 1: STUDENT the table.

No Name Stipend Stream Avgmark Grade Class • List the names of students who are in grade 12 sorted
s by stipend in ascending order.

• List the details of all students sorted by Avgmarks in


1 Karan 400 Medical 78 B 12
descending order within class in ascending order.
2 Divakar 450 Commerc 45 D 11
e • Display a report listing name, stream and stipend
received in a year assuming that stipend is paid every
3 Anil 399 Humanitie 67 C 11 month.
s
• To count the number of students with grade C.
4 Vikas 500 Commerc 74 B 12
e • To display details of students whose name starts with
‘V’.
5 Manu 650 Medical 89 A 11
• To display details of students who have opted for
medical stream.

50
Unsolved questions
Table 2: INSURANCE • Give the name and type of all companies whose
Company Type Years Name Coverage coverage is more than 100000 but less than 700000.

• List the name, company and years of all those whose


CUF Car 15 Care safe 80000
type is life and years are more than 20.

LIT Life 40 Insured Life policy 200000 • List the different types of policies.

• Calculate the average coverage of type House .


HC House 25 House Secure policy 550000
• List the name in descending order of coverage.
URFree Life 35 Life Insurance 750000
• Display the sum of coverage on the basis of type ‘Life’.
Care Child 25 Future Child 500000
• Display the details of all companies whose insurance
years range from 20 to 30 years.

51
Unsolved questions
TABLE 3: ACTIVITY
Acode Activityname Noofparticipa Prizemoney Scheduledate
nts
• To display name of all activities with their
Acodes in descending order.

• To display sum of Prizemoney for


1001 Relay 4*100 16 16000 23/01/2004
Noofparticipants grouping 12.
1005 Highjump 10 10000 12/12/2003
• To display Activityname and Noofparticipants
whose schedule date is in the year 2004.
1002 Shortput 12 6000 14/02/2004

• To display details of activities whose


1003 Longjump 12 9000 01/01/2004
prizemoney is between 10000 and 20000.
1008 Discussthrow 10 8000 19/03/2004
• To display the names of the different activities
provided.

52
SQL Commands

DELETE Command
To delete the record from a table SQL provides a delete statement.ENO
General
EName
syntax is:-
SAL BONUS Design Hobb Gend
DELETE FROM <table_name> [WHERE <condition>]; ation ies er
e.g. DELETE FROM student WHERE city = ‘Chennai’; 101 Rohan 2000 100 PEON Cake M
This command deletes all those records whose city is Chennai.
102 Aneeta 3000 200 WORK Sing F
ER
103 Pawan 7000 300 MANA Dance M
Kumar GER

104 Rohan 8000 400 MANA Sing M


• DELETE FROM EMPLOYEE - All rows are deleted GER

• DELETE FROM EMPLOYEE WHERE RNO=12;


• DELETE FROM EMPLOYEE WHERE ADDRESS IN (‘SHARJAH’,’DUBAI’);
• DELETE FROM EMPLOYEE WHERE NAME LIKE ’A%’;
• DELETE FROM EMPLOYEE WHERE SAL<5000 AND DEPTNO =‘D001’;
53
UPDATE Command
SQL Commands
• To update the data stored in the data base, Roll_n Name Clas Marks City
• UPDATE command is used. o s
101 Rohan XI 400 Mumbai
e. g. UPDATE student SET marks = marks + 100;
102 Aneeta XII 390 Bengalore
• Increase marks of all the students by 100. 103 Pawan IX 298 Mysore
e. g. UPDATE student SET City = ‘Hydrabad’ Kumar
Banglore
WHERE city = ‘Bangaluru’; 104 Rohan IX 376
105 Sanjay VII 240 Mumbai
changes the city of those students to Hydrabad whose
city is Bangaluru. 113 Anju VIII 432 Delhi

• We can also update multiple columns with update command, like


e. g. UPDATE student set marks = marks + 20, city = ‘Mangalore’
WHERE city NOT IN (‘Delhi’,’Mysore’);

54
UPDATE COMMAND
• UPDATE EMPLOYEE SET BONUS=150;
• UPDATE EMPLOYEE SET TAX=100 WHERE TAX IS NULL;
• UPDATE EMPLOYEE SET BONUS=100 ,TAX=10 WHERE EMPNO=12;
• UPDATE EMPLOYEE SET WORKDUR=NULL WHERE ENO=5;
• UPDATE EMPLOYEE SET WORKDUR=10 WHERE ADDRESS =‘SHARJAH’ AND
DEPTNO =‘D001’;

55
SQL Commands
ALTER TABLE Command
In SQL if we ever need to change the structure of the database then ALTER TABLE
command is used. By using this command we can add a column in the existing
table, delete a column from a table or modify columns in a table.
Adding a column
The syntax to add a column is:-
ALTER TABLE table_name
ADD column_name datatype;
Removing a column
ALTER TABLE table_name
DROP COLUMN column_name;
e.g ALTER TABLE Student
DROP COLUMN Address;
The column Address will be removed from the table student
56
ALTER TABLE COMMAND
• ADDING ATTRIBUTES

ALTER TABLE EMPLOYEE ADD TAX INT;

• MODIFYING ATTRIBUTES - Changing existing data type and constraint.


ALTER TABLE EMPLOYEE MODIFY SAL INT PRIMARY KEY;

• DROPPING ATTRIBUTES

ALTER TABLE EMPLOYEE DROP COLUMN TAX;

57
SQL Commands

ALTER TABLE Command


The command to add a column Address to the table student.

e.g. ALTER TABLE student ADD Address varchar(30);

If we give command

SELECT * FROM student;

The following data gets displayed on screen:

58
SQL Commands
TABLE : STUDENT

Roll_no Name Class Marks City Address

101 Rohan XI 400 Chennai


102 Aneeta XII 390 Bengaluru
103 Pawan Kumar IX 298 Mysore
104 Rohan IX 376 Mangalore
105 Sanjay VII 240 Mumbai
113 Anju VIII 432 Delhi

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.
59
SQL Commands

DROP TABLE Command


Sometimes you may need to drop a table which is not in use. DROP TABLE
command is used to Delete / drop a table permanently. It should be kept in mind that
we can not drop a table if it contains records. That is first all the rows of the table
have to be deleted and only then the table can be
dropped.

The general syntax of this command is:-

DROP TABLE <table_name>;

e.g DROP TABLE student;

This command will remove the table student


60
SUBQUERY
•SELECT * FROM EMPLOYEE WHERE SAL =
(SELECT MAX(SAL) FROM EMPLOYEE);

•SELECT * FROM EMPLOYEE WHERE BONUS =


(SELECT MIN(BONUS) FROM EMPLOYEE);

61

You might also like