0% found this document useful (0 votes)
5 views26 pages

Unit-2- Database Query Using SQL

This document provides an overview of databases, specifically focusing on relational databases and SQL (Structured Query Language). It covers key concepts such as relations, domains, tuples, attributes, and cardinality, along with various SQL statements and their functions, including Data Definition Language (DDL), Data Manipulation Language (DML), and more. Additionally, it includes examples of SQL commands and aggregate functions to manipulate and retrieve data from databases.

Uploaded by

lokajaybhadra04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views26 pages

Unit-2- Database Query Using SQL

This document provides an overview of databases, specifically focusing on relational databases and SQL (Structured Query Language). It covers key concepts such as relations, domains, tuples, attributes, and cardinality, along with various SQL statements and their functions, including Data Definition Language (DDL), Data Manipulation Language (DML), and more. Additionally, it includes examples of SQL commands and aggregate functions to manipulate and retrieve data from databases.

Uploaded by

lokajaybhadra04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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.

Relational Database Model:


1. Relation: A table in this model is called a relation. It is collection of records. For example
student table.

Rollno Name Class

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.

Rollno Name Class

tuples 101 RAM 12

203 RAHIM 11

307 SHYAM 9

Attributes: The columns of tables are called attributes. In student table Roll no, Name, and
Class are attributes.

Rollno Name Class

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)

2. The term ____________ is used to refer to a field in a table.


(a.) Attribute (b) Tuple (c) Row (d) Instance
Ans (a)

3. The cardinality of the given table is:

(a) 4 (b) 3 (c) 5 (d) 2


Ans (b)
4. What is primary key?
Ans It is set of one or more attributes having values that are unique within the relation and
are thus able to uniquely identify that tuple.

5. Why do we use databases?


Ans. Some uses are:
Databases can store very large numbers of records efficiently.
It is very quick and easy to find information.
It is easy to add new data and to edit or delete old data.
Data can be searched easily

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:

EID NAME salary


123 sumit 15000
104 vaibhav 12000
207 shyam 11000
112 sansakar 12000
Department table:

dep_id department location EID


S101 sales delhi 123
S122 production mumbai 112
S300 marketing kanpur 207

(i) What is the degree of employee table?


(a) 2 (b) 4 (c) 3 (d) none of the above

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. dep_id, department, location, EID


(iv) Which of the following will become foreign key?
(a) Dep_id (b) location (c) salary (d) EID

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

CAT CODE NAME PRICE QTY


BEVERAGE B163 BEST JUICE 10 10
SNACK S968 YUMMY 10 40
NOODLE N042 WOW 20 20
BEVERAGE B482 FRESH TEA 25 80
NOODLE N091 QQ NOODLE 8 10
Answer the following questions:
(i) Which of following may be Candidate keys in Inventory table?

Ans. CODE, NAME


(ii) Let’s CODE is primary key then which will be the alternate key?

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:

EMPLOYEEID NAME SALES JOBID


E1 SUMIT 1100000 101
E2 VIJAY 1300000 102
E3 AJAY 1100000 103
E4 VIJAY 1250000 103
E5 SHAILJA 1450000 102

TABLE: JOB

JOBID JOBTITLE SALARY


101 PRESIDENT 200000
102 VICE PRESIDENT 125000
103 CEO 300000
104 ACCOUNTING MANAGER 70000
105 ACCOUNTANT 65000

(i) Tell the name of primary key in employee table.

Ans: EMPLOYEEID
(ii) Tell the name of foreign key in above tables.

Ans: JOBID in EMPLOYEE table.


SQL
• SQL (Structured Query Language) is the standard language for dealing with Relational
Databases.
• SQL is generally used to insert, select, update, and delete database records.

TYPES of SQL Statements


• DDL (Data Definition Language)
– Create
– Alter
– Drop
– Truncate
• DML (Data Manipulation Language)
– Insert
– Update
– Delete
– Select
• DCL (Data Control Language)
– Grant
– Revoke
• TCL (Transaction Control Language)
– Commit
– Rollback

SQL Data types


• int
• char
• varchar2
• date
Integer values---- int
Floating point numbers---- float
Fixed length character strings---- char
Variable length character strings---- varchar2
DATE values---- date

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: =, <=, >=, < >, < , >

MYSQL STATEMENTS/COMMANDS RELATED TO DATABASE


The CREATE DATABASE statement is used to create a new SQL database.
Syntax:
create database database_name;
Example:
create database mydb;

The drop database statement is used to drop an existing SQL database.


Syntax:
drop database database_name;
Example:
drop database mydb;
Other MySQL Commands:

Description Command

List all databases on the MySQL show databases;

Switch to a database use [database_name];

To see all the tables in the db show tables;

To see details of any table desc [table_name];

SQL-Data Definition Language (DDL)


Types of Constraints
• Primary Key Constraint
• Not Null Constraint
• Unique Constraint

SQL - CREATE TABLE


Syntax:
create table tablename
(
column_name data_ type constraints, …
);
Used to create a table by defining its structure, the data type and name of the various columns,
the relationships with columns of other tables etc.

EXAMPLE (with use of constraints):


create table student
(
stu_id int(5) primary key,
stu_first_name varchar2(20) not null,
stu_mid_name varchar2(4),
stu_last_name varchar2(20),
marks int(5),
address varchar2(10) not null,
stu_email varchar2(30) unique
);
SQL - alter table
Syntax:
alter table tablename (add/modify/drop column_name);

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 - drop table


– Deletes table structure
– Cannot be recovered
– Use with caution
Syntax: drop table table_name;
Example: drop table student;

SQL- Data Manipulation Language (DML)


Reference Table
For further examples, banking_details table will also be used. So, create this table in database
before your run example queries related to this table:
create table banking_details
(
customer_id int(5) primary key,
customer_last_name varchar2(20),
customer_mid_name varchar2(4),
customer_first_name varchar2(20),
account_no int(5) unique,
account_type varchar2(10),
bank_branch varchar2(10),
customer_email varchar2(30) unique
);

SQL - insert into


• Single-row insert with values for all Columns:
insert into banking_details values (106, 'kumar', 'a.', 'ravi', 3350, 'savings', 'indus bank',
'[email protected]');
Syntax: insert into tablename (columnlist) values (value list);

• Inserting one row, few columns at a time:


insert into banking_details (customer_id, customer_last_name, customer_mid_name,
customer_first_name, account_no, account_type, bank_branch) values (107, 'raj', 'b.', 'ankit',
3351, 'savings', 'indus bank');

• Inserting null Value into a Column:


insert into banking_details (customer_id, customer_last_name, customer_mid_name,
customer_first_name, account_no, account_type, bank_branch,customer_email) values (108,
'khanna', 'b.', 'pradeep', 3352, 'savings', 'indus bank‘,null);

SQL - delete from


Syntax: delete from tablename [where <condition>];
• Deleting All Rows:
delete from banking_details;

• Deleting Specific Rows:


delete from banking_details where customer_id = 102;

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;

• Updating Particular rows:


update customer_fixed_deposit set rate_of_interest_in_percent = 7.3 where
amount_in_dollars > 3000;

• Updating Multiple Columns


update customer_fixed_deposit set customer_email = ‘[email protected]’ ,
rate_of_interest_in_percent = 7.3 where customer_id = 104;

select COMMAND
• Retrieving all columns from a table:
Syntax: select column1, column2,… from tablename;
Example:
select *from banking_details;

• Retrieving Few Columns:


select customer_id, account_no from banking_details;

SQL - all, distinct


• Get all Customers Name:
select all customer_last_name from banking_details;
or
select customer_last_name from banking_details;

• Get all distinct Customer Name


select distinct customer_last_name from banking_details;

RETRIEVING A SUBSET OF ROWS


For retrieval of rows based on some condition, the syntax is:
select col1,col2,.........from table_name where <search condition>;
select stu_id from student where marks>75;

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;

• List the Customer_id, Account_No of ‘graham’:


select customer_id, account_no from banking_details where customer_first_name = ‘graham’;

Relational operators:
= , < , > , <= , >= , != or < >

• List all Account_No where Total_Available_Balance_in_Dollars is atleast $10000.00:


select account_no from customer_transaction where total_available_balance_in_dollars >=
10000.00;

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 customer_id, customer_last_name where either account_type is ‘savings’ or


bank_branch is ‘capital bank’:
select customer_id, customer_last_name from banking_details where account_type = ‘savings’
or bank_branch = ‘capital bank’;

RETRIEVAL USING ‘between’

• 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;

RETRIEVAL USING ‘in’


• List all customers who have account in capital bank or indus bank:
select customer_id from banking_details where bank_branch = ‘capital bank’ or bank_branch =
‘indus bank’;
or
select customer_id from banking_details where bank_branch in (‘capital bank’, ‘indus bank’);

RETRIEVAL USING ‘like’


• List all accounts where the bank_branch begins with a ‘c’ and has ‘a’ as the second character:
select customer_id, customer_last_name, account_no from banking_details where
bank_branch like ‘ca%’;

• 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%’;

RETRIEVAL USING IS ‘null’


• List employees who have not been assigned a manager yet:
select employee_id from employee_manager where manager_id is null;

• List employees who have been assigned to some manager:


select employee_id from employee_manager where manager_id is not null;

SORTING YOUR RESULTS (order by)


• List the customers account numbers and their account balances, in the increasing order of the
balance:
select account_no, total_available_balance_in_dollars from customer_transaction order by
total_available_balance_in_dollars;
• List the customers account numbers and their account balances, in the decreasing order of
the balance:
select account_no, total_available_balance_in_dollars from customer_transaction order by
total_available_balance_in_dollars desc;

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: What does SQL stand for?


a) Structured Question Language
b) Structured Query Language [correct answer]
c) Strong Question Language

Q: Which SQL statement is used to extract data from a database?


a) EXTRACT
b) GET
c) OPEN
d) SELECT [correct answer]

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

id pname age sname pay gender


1 Kabir 35 Lawn Tennis 15000 null
2 Rekha 29 Karate 12000 F
3 Kanishk 34 Squash 20000 M
4 Sarita 29 Squash 21000 null
5 Ravi 24 Karate 25000 M

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:

You might also like