Unit-2- Database Query Using SQL
Unit-2- Database Query Using SQL
Database:
A database is defined as a collection of interrelated data stored together.
DBMS:
Full form of DBMS is Database Management System. This is software which is used to create,
manage, and update databases. Examples of DBMS: Oracle, Microsoft SQL Server, MYSQL, IBM
DB2, SQLite etc. RDBMS is a DBMS that follows the concepts of Relational Data Model. The
main concepts of this model are discussed below.
101 RAM 12
203 RAHIM 11
307 SHYAM 9
2. Domain: A domain is a set of values from which the actual values appearing in a given
column are taken. In student table domain of Rollno is Set of positive integers.
3. Tuple: The rows of tables are called tuples.
203 RAHIM 11
307 SHYAM 9
Attributes: The columns of tables are called attributes. In student table Roll no, Name, and
Class are attributes.
101 RAM 12
203 RAHIM 11
307 SHYAM 9
Degree: The number of attributes in a relation determines the degree of a relation. In student
table attributes are Roll no, Name and Class. So, degree of student table is 3.
Cardinality: The number of Tuples or rows in a relation is called the cardinality of the relation.
Cardinality of student table is 3.
QUESTIONS:
1. A relational database consists of a collection of:
(a)Tuples (b) Attributes (c) Relations (d) Keys
Ans (c)
6. A company ram InfoTech has prepared its database. Tables of employee and department
are shown as below. After studying tables answer the following questions.
Employee table:
Ans (c)
(ii) What is the cardinality of Department table?
(a) 3 (b) 1 (c) 4 (d) 5
Ans (a)
(iii) Write the name of attributes of Department table.
Ans (d)
7. A set (pool) of values where from a field can take (draw) values is called________.
Ans . Domain
8. Collection of logically related data tables is called__________.
Ans. Database
9. A row in a relation is called a _______.
Ans. Tuple
10. A column in a relation is called an _________.
Ans. Attribute
11. Mr. singh is responsible for setting up an inventory system in a supermarket. He creates a
database table, INVENTORY, to store the information on products for sale.
Table: INVENTORY
Ans. NAME
12. A company Best Solution Infotech has maintained its data in DBMS. In its database two
tables are given as follows. ANSWERS THE QUESTIONS GIVEN BELOW.
EMPLOYEE:
TABLE: JOB
Ans: EMPLOYEEID
(ii) Tell the name of foreign key in above tables.
null
• Missing/unknown/inapplicable data represented as a null value.
• null is not a data value. It is just an indicator that the value is unknown.
SQL OPERATORS
• Arithmetic operators like +, -, *, /
• Logical operators: and, or, not
• Relational operators: =, <=, >=, < >, < , >
Description Command
EXAMPLE:
alter table student add contact_phone char(10);
alter table student modify contact_phone char(12);
alter table student drop (contact_phone);
alter table student add primary key(stu_id);
alter table student drop primary key;
SQL - update
Syntax: update tablename set column_name =value [ where <condition>];
• Updating All Rows:
update customer_fixed_deposit set rate_of_interest_in_percent = null;
select COMMAND
• Retrieving all columns from a table:
Syntax: select column1, column2,… from tablename;
Example:
select *from banking_details;
RELATIONAL OPERATORS
• List all customers with an account balance > $10000:
select account_no, total_available_balance_in_dollars from customer_transaction where
total_available_balance_in_dollars > 10000.00;
Relational operators:
= , < , > , <= , >= , != or < >
LOGICAL OPERATORS
• List all customer_id, customer_last_name where account_type is ‘savings’ and bank_branch is
‘capital bank’:
select customer_id, customer_last_name from banking_details where account_type = ‘savings’
and bank_branch = ‘capital bank’;
• List all customer_id, customer_last_name where neither account_type is ‘savings’ and nor
bank_branch is ‘capital bank’:
select customer_id, customer_last_name from banking_details where not account_type =
‘savings’ and not bank_branch = ‘capital bank’;
• List all account numbers with balance in the range $10000.00 to $20000.00:
select account_no from customer_transaction where total_available_balance_in_dollars >=
10000.00 and total_available_balance_in_dollars <= 20000.00;
or
select account_no from customer_transaction where total_available_balance_in_dollars
between 10000.00 and 20000.00;
• List all accounts where the bank_branch column has ‘a’ as the second character:
select customer_id, customer_last_name, account_no from banking_details where
bank_branch like ‘_a%’;
AGGREGATE FUNCTIONS
An aggregate function performs a calculation on multiple values and returns a single value.
Following is the list of aggregate functions supported by mysql.
Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given column.
NULL & Aggregate Functions:
Consider a table Employee having following records as Null values are excluded when (avg)
aggregate function is used:
Emp Code Name Sal
E01 Mohan NULL
E02 Anup 4500
E03 Vijaya NULL
E04 Vaishali 3500
E05 Anirudh 4000
Queries example output
mysql> Select Sum(Sal) from EMP; 12000
mysql> Select Min(Sal) from EMP; 3500
mysql> Select Max(Sal) from EMP; 4500
mysql> Select Count(Sal) from EMP; 3
mysql> Select Avg(Sal) from EMP; 4000
mysql> Select Count(*) from EMP; 5
The GROUP BY clause groups a set of rows/records into a set of summary rows/records by
values of columns or expressions. It returns one row for each group. We use the GROUP BY
clause with aggregate functions such as SUM, AVG, MAX, MIN, and COUNT.eg
mysql>select count(*) from employee group by job;
GROUP BY with aggregate functions
The aggregate functions allow us to perform the calculation of a set of rows and return a single
value. The GROUP BY clause is used with an aggregate function to perform calculation and
return a single value for each subgroup. e.g.
select class, count(*) from student group by class;
select class,avg(marks) from student group by class;
select class,avg(marks) from student where class<10 group by class order by marks desc;
HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows
or aggregates. The HAVING clause is often used with the GROUP BY clause to filter groups
based on a specified condition.
To filter the groups returned by GROUP BY clause, we use a HAVING clause.
select class, avg(marks) from student group by class having avg(marks)<90;
select class, avg(marks) from student group by class having count(*)<3;
JOIN
Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It is used for combining column from two or more tables by using values common to both
tables.
INNER Join or EQUI Join
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the SQL query. e.g.
select course.student_name from couse , student where
course.student_name=student.student_name;
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.e.g.
Select * from a natural join b;
SQL: (Questions)
Q: With SQL, how do you select all the records from a table named "Persons" where the value
of the column "FirstName" is "Peter"?
a) SELECT * FROM Persons WHERE FirstName='Peter'; [correct answer]
b) SELECT * FROM Persons WHERE FirstName<>'Peter';
c) SELECT [all] FROM Persons WHERE FirstName LIKE 'Peter';
d) SELECT [all] FROM Persons WHERE FirstName='Peter'
Q: With SQL, how do you select all the records from a table named "Persons" where the value
of the column "FirstName" starts with an "a"?
a) SELECT * FROM Persons WHERE FirstName LIKE 'a%'; [correct answer]
b) SELECT * FROM Persons WHERE FirstName='a';
c) SELECT * FROM Persons WHERE FirstName='%a%';
d) SELECT * FROM Persons WHERE FirstName LIKE '%a'
Q: With SQL, how do you select all the records from a table named "Persons" where the
"FirstName" is "Peter" and the "LastName" is "Jackson"?
a) SELECT * FROM Persons WHERE FirstName='Peter' AND LastName='Jackson'; [correct
answer]
b) SELECT FirstName='Peter', LastName='Jackson' FROM Persons;
c) SELECT * FROM Persons WHERE FirstName<>'Peter' AND LastName<>'Jackson'
Q: The __________clause of SELECT query allows us to select only those rows in the results that
satisfy a specified condition.
(a) where (b) from (c) having (d) like
Q: Which of the following function is used to FIND the largest value from the given data in
MYSQL?
(a) max() (b) maximum() (c) largest() (d) big()
Q: Which of the following function is not an aggregate function?
(a) round() (b) sum() (c) count() (d) avg()
Q: Aggregate functions can be used in the select list or the _____ clause of a select statement.
They cannot be used in a ______ clause.
(a) Where, having (b) having, where (c) group by, having (d) group by, where
Q: The HAVING clause does which of the following?
(a) Acts EXACTLY like WHERE clause (b) Acts like a WHERE clause but is used for columns rather
than groups. (c) Acts like a WHERE clause but is used form groups rather than rows. (d) Acts
like a WHERE clause but is used for rows rather than columns.
Q: Which clause is used with “aggregate functions”?
(a) GROUP BY (b) SELECT (c) WHERE (d) Both (a) and (b)
Q: SQL applies conditions on the groups through _____ clause after groups have been formed,
(a) group by (b) with (c) where (d) having
Q: All aggregate functions except _______ ignore null values in their input collection.
(a) count (attribute) (b) count (*) (c) avg (d) sum
Q: Which of the following group functions ignore NULL values?
(a) max (b) count (c) sum (d) all of the above
Q: Sports Authority of India (SAI) has recruited some players with the details given below in
table ‘sports’. Now, SAI wants to perform some queries on sports table that is already been
created in database. Therefore, Write mentioned five SQL queries to facilitate SAI:-
Table: sports
Query (1): Show details of those players whose name start with ‘K’.
Query (2): Delete the records of those players whose gender in unknown (null).
Query (3): Show name of those players whose age is between 20 and 30.
Query (4): Show details of those players who play either Karate or Squash.
Query (5): Increase (update) the 15% pay of all the players.
Ans:
(1) select * from sports where pname like ‘K%’;
(2) delete from sports where gender is null;
(3) select pname from sports where age between 20 and 30;
(4) select * from sports where sname in (‘Karate’,‘Squash’);
(5) update sports set pay=pay+(pay*15)/100;
Q: Ravi wants to create a table ‘teacher’ on the basis of the specifications given below, help him
to do the same:
Columns(fields): following are the columns in the teacher table:
a) teacher id (constraint: primary key)
b) teacher first name (constraint: not null)
c) teacher middle name
d) teacher last name
e) salary
f) address (constraint: not null)
g) mail-id (constraint: unique)
Ans:
create table teacher
(
t_id char(5) primary key,
t_first_name varchar(20) not null,
t_mid_name varchar(4),
t_last_name varchar(20),
salary int(5),
address varchar(10) not null,
t_email varchar(30) unique
);
Q: Differentiate between WHERE and HAVING clause.
Ans: WHERE clause is used to select particular rows that satisfy a condition whereas HAVING
clause is used in connection with the aggregate function, GROUP BY clause. For ex. – select *
from student where marks > 75; This statement shall display the records for all the students
who have scored more than 75 marks. On the contrary, the statement – select * from student
group by stream having marks > 75; shall display the records of all the students grouped
together on the basis of stream but only for those students who have scored marks more than
75.
Q: Perform the below queries in MySql database using SQL:
Ans:
(i) 63
(ii) 800
(iii) 475
Q: Perform the below case in MySql database using SQL:
Math functions (POWER (), ROUND (), MOD ()):
Perform operation over numeric value:
Text functions (UCASE ()/ UPPER (), LCASE ()/ LOWER (), MID ()/ SUBSTRING () /SUBSTR (),
LENGTH (), LEFT (), RIGHT (), INSTR (), LTRIM (), RTRIM (), TRIM()):
Perform operation over string values:
Date Functions (NOW (), DATE (), MONTH (), MONTHNAME (), YEAR (), DAY (), DAYNAME ()):
Perform operation over date values: