0% found this document useful (0 votes)
5 views

sql -xii IP

The document provides an overview of databases and SQL, detailing the structure and functions of Database Management Systems (DBMS) and Relational Database Management Systems (RDBMS). It explains SQL commands including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), as well as data types, constraints, and various SQL operations such as joins and queries. Additionally, it highlights the differences between CHAR and VARCHAR data types and outlines the process of data retrieval and manipulation using SQL syntax.

Uploaded by

Ayush Jawla
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 views

sql -xii IP

The document provides an overview of databases and SQL, detailing the structure and functions of Database Management Systems (DBMS) and Relational Database Management Systems (RDBMS). It explains SQL commands including Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL), as well as data types, constraints, and various SQL operations such as joins and queries. Additionally, it highlights the differences between CHAR and VARCHAR data types and outlines the process of data retrieval and manipulation using SQL syntax.

Uploaded by

Ayush Jawla
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/ 28

DATABASE USING SQL

Revision of SQL

Database  Is a collection of records , the related data are organized


in such a manner that they can easily be accessed using
DBMS.
DBMS  Database Management System
Advantages of DBMS
 Minimize the duplication of data – data redundancy
 Stores large amount of data
 Reliable result
 Allows user to make different queries as per requirement
 Updating easier
RDBMS – Relational Database Management System
Commonly used terms in RDBMS -
 Relation – Table
 Attributes – column of a table
 Tuple – rows of a table
 Cardinality – no of rows in a relation
 Degree – no of attributes in a relation
Primary Key – an attribute which uniquely identifies each and every record of a
table in relational database.
Candidate Key – The attributes which can become primary key but not declared
is called Candidate Key
Alternate Key – Remaining candidate keys are also known as Alternate key
Foreign key – a non key attribute which is derived from primary key of some
other table, then in current table it ‘s called Foreign key.
Structured Query Language (SQL)
(i) DDL - Data Definition Language
- CREATE  To create database or table
- ALTER  To update the structure of a table
- DROP  To delete the database or table
(ii) DML - Data Manipulation Language
- Commands that deals with manipulation of data in the
table
- INSERT
- UPDATE
- DELETE
- SELECT
(iii) DCL - Data Control Language
- It deals with the rights , permission and other controls
of the database system.

1|Page
- Grant  it gives user’s access privilege to a database
- Revoke  It withdraws user’s access privileges given by
using the GRANT command
DATA TYPE OF ATTRIBUTE:

 Data type indicates the type of data value that an attribute can have and the
operations that can be performed on the data of that attribute

CHAR  Fixed length


 Declaring CHAR (10) implies to reserve spaces for 10
characters. If data does not have 10 characters MySQL fills
the remaining characters with spaces padded on the right.

VARCHAR  Variable length


 declaring VARCHAR (30) means a maximum of 30 characters
can be stored but the actual allocated bytes will depend on
the length of entered string
INT Integer value. Each INT value occupies 4 bytes of storage

FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4
bytes.
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is
the 4 digit year, MM is the 2 digit month and DD is the 2 digit date

Difference between Char and Varchar

CHAR data type VARCHAR Data type


1. It simply represents a character 1. It represents a variable character
data type. data type
2. It stores values in fixed lengths 2. It stores values in variable
and are occupied with space lengths and are not occupied
characters to match the specified with any characters.
length.
3. It uses static memory allocation 3. It uses dynamic memory
allocation
4. It can hold a maximum of 255 4. It can hold a maximum of 65535
character character.

CONSTRAINTS:

 Constraints are certain types of restrictions on the data values that an


attribute can have. They are used to ensure the accuracy and reliability of
data.

2|Page
 SQL queries:

DDL Commands
1. CREATE Syntax : Example :
DATABASE CREATE DATABASE CREATE DATABASE EMP_DATA;
<DBNAME>;
2. For using Syntax : Example :
/opening USE <DBNAME>; USE EMP_DATA;
Database
3. To show all Syntax : Example :
available SHOW DATABASES; SHOW DATABASES;
databases
4. To create Syntax : Example :
table CREATE TABLE <table_name> CREATE TABLE EMP
(<col_name> <datatype> (EMPNO INT ,
<size> constraint, ENAME VARCHAR(20),
<col_name> <datatype> SALARY INT);
<size> constraint,----------
); CREATE TABLE EMP
(EMPNO INT PRIMARY KEY,
ENAME VARCHAR(20),
SALARY INT);

3|Page
5. Describe table Syntax : Example :
DESCRIBE <TABLE_NAME>;
– can view the
structure of
the table

6. Alter table – Syntax : Example :


to change the ALTER TABLE <TABLE_NAME> (a) Add an attribute to an existing
structure of ADD/MODIFY/DROP table
the table like <COLUMN_NAME>…;
Adding new ALTER TABLE STUDENT
column, ADD MARKS INT;
deleting a
column etc. (b) Modify datatype of an attribute

ALTER TABLE STUDENT


MODIFY MARKS FLOAT;

(c) Remove an attribute

ALTER TABLE STUDENT


DROP MARKS;
7. Drop table - Syntax : Example :
DROP DROP TABLE <table_name>; Command to delete a database
statement to EMP_DATA.
remove a Syntax to drop a database: DROP DATABASE EMP_DATA;
database or a DROP DATABASE db_name;
table Command to delete a table
permanently STUDENT.
from the DROP TABLE STUDENT;
system.
DML Commands
8. Insertion of Syntax : Example :
Record INSERT INTO <TABLE_NAME> INSERT INTO STUDENT
(<col_name>,<col_name>,…) VALUES (11, ‘MEENU’, ‘2005-10-
VALUES (<val1>,<val2>,…); 25’ , ‘ABC’);

OR

INSERT INTO STUDENT


(ROLLNO,SNAME,SDOB,GUID)
VALUES (11, ‘MEENU’, ‘2005-10-
25’ , ‘ABC’);

OR

4|Page
INSERT INTO STUDENT
(ROLLNO,SNAME,SDOB)
VALUES (20, ‘SHEENA’, ‘2009-10-
13’);

9. Select 1) To display all record To display all details of students.


statement
Syntax: Example :
SELECT * FROM tablename; SELECT * FROM STUDENT;

2) To display selected columns To display only ROLLNO and


and all rows SNAME from STUDENT table.
Syntax:
SELECT SELECT ROLLNO, SNAME FROM
<colname>,<colname>.. STUDENT;
FROM <tablename>;

3) To display selected rows and To display all details whose rollno


all columns is less than 15.
Syntax :
SELECT * FROM <tablename> SELECT * FROM STUDENT
WHERE <condition>; WHERE ROLLNO<15;

4) To display selected rows and


selected columns To display name of student whose
Syntax : roll no is 20.
SELECT
<colname>,<colname> SELECT SNAME FROM STUDENT
FROM <tablename> WHERE ROLLNO=20;
WHERE <condition>;
10. Column Syntax: Example: Display names of all
Aliases – SELECT <COLNAME> AS “<new employees along with their annual
renaming a name>” FROM salary (Salary*12). While
<tablename>;
column displaying query result, rename
EName as Name.

mysql> SELECT EName AS Name,


Salary*12 FROM EMPLOYEE;

Output:-

5|Page
11. DISTINCT Syntax : To display unique department
clause - The SELECT DISTINCT <COLNAME> number for all the employees.
SELECT FROM <tablename>;
statement mysql> SELECT DISTINCT DeptId
when FROM EMPLOYEE;
combined
with Output:-
DISTINCT
clause,
returns
records
without
repetition
(distinct
records)
12. WHERE Syntax : To display distinct salaries of
clause - The the employees working in the
WHERE SELECT * FROM <tablename> department number D01.
clause is WHERE <condition>;
used to mysql> SELECT DISTINCT Salary
retrieve data FROM EMPLOYEE WHERE
that meet Deptid='D01';
some
specified Output:-
conditions

6|Page
13. Membership Syntax:
Operator – SELECT * FROM <tablename>
IN WHERE <colname> IN
(<val1>,<val2>…);
The IN
operator
compares a
value with a
set of values
and returns
true if the
value belongs
to that set.
14. ORDER BY Syntax : Example :
clause –
used to SELECT <colname>… SELECT * FROM EMP
FROM <tablename>
display data ORDER BY <colname>; ORDER BY SALARY;
in an ordered
(arranged) Output:-
form with
respect to a
specified
column.

By default
displays
records in
ascending
order

To display
The following query displays
the records in
details of all the employees in
descending
descending order of their salaries.
order, the
DESC
mysql> SELECT * FROM
keyword
EMPLOYEE ORDER BY Salary
written
DESC;

Output:-

7|Page
15. Handling Syntax :  Displays details of all those
NULL employees who have not been
Values SELECT * FROM <tablename> given a bonus. This implies that
WHERE <colname> IS NULL/
IS NOT NULL; the bonus column will be blank.

mysql> SELECT * FROM


EMPLOYEE WHERE Bonus IS NULL;

Output:-

 Displays names of all the


employees who have been given a
bonus. This implies that the bonus
column will not be blank.

mysql> SELECT EName FROM


EMPLOYEE WHERE Bonus IS NOT
NULL;

Output:-

16. Substring • % (percent)— used to  Displays details of all those


pattern represent zero, one, or employees whose name starts with
matching multiple characters 'K'.
• _ (underscore)— used to
represent a single char
mysql> SELECT * FROM
8|Page
EMPLOYEE WHERE Ename LIKE
'K%';

 Displays details of all those


employees whose name ends with
'a'.

mysql> SELECT * -> FROM


EMPLOYEE -> WHERE Ename LIKE
'%a';

 Displays details of all those


employees whose name consists of
exactly 5 letters and starts with
any letter but has ‘ANYA’ after
that.

mysql> SELECT * FROM


EMPLOYEE WHERE Ename LIKE
'_ANYA';

 Displays names of all the


employees containing 'se' as a
substring in name.

mysql> SELECT Ename FROM


EMPLOYEE WHERE Ename LIKE
'%se%';

 Displays names of all


employees containing 'a' as the
second character.

mysql> SELECT EName FROM


EMPLOYEE WHERE Ename LIKE
'_a%';
17. Data Syntax:  To update the name of
Updation – UPDATE table_name SET student to ‘SANJAY’ whose Roll no
to make attribute1 = value1, is 3 in table STUDENT.
attribute2 = value2, ..
changes in WHERE condition;
the value(s) mysql> UPDATE STUDENT
of one or SET SNAME = ‘SANJAY’
more WHERE RollNumber = 3;
columns of

9|Page
existing
records in a
table.
18. Data Deletion Syntax:  To delete the details of
- TheDELETE FROM table_name student whose Roll number is 2.
DELETE WHERE condition;
statement is mysql> DELETE FROM STUDENT
used to WHERE RollNumber = 2;
delete one or
more
record(s)
from a table

SQL Joins:
 Process of accessing data from multiple tables is called Join in SQL
 JOIN operation combines tuples from two tables on specified conditions. This is
unlike cartesian product, which make all possible combinations of tuples
 Example : List the Ucode, Uname, Ucolor, size and Price of related tuples of
table UNIFORM and COST.
(a) SELECT * FROM UNIFORM U, COST C where U.Ucode = C.Ucode;

(b) Explicit use of JOIN clause:

SELECT * FROM UNIFORM U JOIN COST C ON U.Ucode=C.Ucode;


c) Explicit use of NATURAL JOIN clause
SELECT * FROM UNIFORM NATURAL JOIN COST;
Following are some of the points to be considered while applying JOIN operations on
two or more relations:
• If two tables are to be joined on equality condition on the common attribute, then
one may use JOIN with ON clause or NATURAL JOIN in FROM clause. If three tables
are to be joined on equality condition, then two JOIN or NATURAL JOIN are required.
• In general, N-1 joins are needed to combine N tables on equality condition.
• With JOIN clause, we may use any relational operators to combine tuples of two
tables.

10 | P a g e
Equi Join

 The SQL Equi join is a simple join clause where the relation is established using
equal to sign as the relational operator to mention the condition.
 The join in which columns are compared for equality is called equi-join. A non
equi join specifies condition with non-equality operator. In equi-join we put (*)
in the select list will print common column twice in the output.
Example :

Equi Join – Inner join is used to return the records which are having matching values
in both the tables
An Equi Join is a type of join that combines tables based on matching values in the
specified columns.
❖ The column names do not need to be the same.
❖ The resultant table can contain repeated columns.
❖ It is possible to perform an equi join on more than two
Equi Join- ❖ It performs a JOIN against equality or matching column(s) values of the
associated tables.
SELECT * /Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;

Or

SELECT * /Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;

Example: SELECT * FROM emp JOIN dept ON emp.deptno=dept.deptno;Or


SELECT * FROM emp, dept WHERE emp.deptno=dept.deptno;

11 | P a g e
Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname
belongs
toDEPT table. So, to retrieve data in this we will use join
SELECT emp.ename, emp.sal, dept.dname
FROM emp, dept WHERE emp.deptno=dept.deptno;

Output:
++++
| ename | sal | dname |
++++
| SMITH | 800.00 | RESEARCH |
| ALLEN | 1600.00 | SALES |
| WARD | 1250.00 | SALES |
| JONES | 2975.00 | RESEARCH |
| MARTIN | 1250.00 | SALES |
| BLAKE | 2850.00 | SALES |
| CLARK | 2450.00 | ACCOUNTING |
| SCOTT | 3000.00 | RESEARCH |
| KING | 5000.00 | ACCOUNTING |
| TURNER | 1500.00 | SALES |
| ADAMS | 1100.00 | RESEARCH |
| JAMES | 950.00 | SALES |
| FORD | 3000.00 | RESEARCH |
| MILLER | 1300.00 | ACCOUNTING |

Note:

❖ In case of join full qualified (table_name.column_name) name is used to avoid


ambiguity as both table contains common columns as PRIMARY KEY and
FOREIGN KEY.
❖ Table Alias – Like column alias table alias can be used in case of join as given
below.
SELECT e.ename, e.sal FROM emp e, dept d WHERE emp.deptno=dept.deptno;
❖ Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.

FUNCTION in MySQL

 Function:

12 | P a g e
A function is a predefined command set that performs some operation and returns
the single value. A function can have single, multiple or no arguments at all.

 Types of SQL Functions:

1) Single Row Functions:


 Single row function in SQL can be character, numeric, date, and conversion
functions.
 These functions are used to modify data items. These functions need one or
more input and operate on each row, thereby returning one output value for
each row

2) Multiple row Functions (Aggregate Functions):


 The Multiple Row Functions in SQL are used to return either group of
values (or) a single value.
 These functions are basically operated on a set of rows and return one result or
one result per group.
 The Multiple row function in Oracle is also called group functions or it is also
called aggregate functions.

Single Row Functions:


There are three types of Single Row Functions in SQL
1) Character / String Functions
2) Numeric Functions
3) Date and Time Functions
1) Character / String Functions:
i. CONCAT()
ii. LOWER() / LCASE()
iii. UPPER()/UCASE()
iv. LTRIM()
v. TRIM()

13 | P a g e
vi. RTRIM()
vii. SUBSTR()/MID()
viii. INSTR(),
ix. LENGTH()
x. RIGHT()
xi. LEFT()

2) Numeric / Math Functions:


i. POWER(),
ii. ROUND(),
iii. MOD()

3) Date Functions:
i. SYSDATE()
ii. NOW()
iii. DATE()
iv. MONTH()
v. YEAR()
vi. DAYNAME()
vii. MONTHNAME()
viii. DAY()

Math Functions:
1.Pow(x,y )/power(x,y): Returns the value of X raised to the power of Y.
Example:
(i)Select POW(2,4); Result:16
(ii)SELECT POW(2,-2; Result:0.25
(iii)SELECT POW(-2,3); Result: -8
(iv)SELECT id, salary, POWER(salary,2) FROM employee;
Result:

14 | P a g e
+----+----------+-----------------+
| id | salary | power(salary,2) |
+----+----------+-----------------+
| 1 | 25000.00 | 625000000 |
| 2 | 30000.00 | 900000000 |
| 3 | 32000.50 | 1024032000.25 |
| 4 | 37500.50 | 1406287500.25 |
| 5 | 42389.50 | 1796869710.25 |
+----+----------+-----------------+
2.ROUND(X): Rounds the argument to zero decimal place, whereas ROUND(X,
d) rounds X to d decimal places.
Example:
(i) ROUND(-1.23); Result: -1
(ii) ROUND(-1.68); Result: -2
(iii) ROUND(1.58); Result: 2
(iv) ROUND(3.798, 1); Result: 3.8
(v) ROUND(1.298, 0); Result: 1
(vi) ROUND(76823.298, -1); Result: 76820
(vii) ROUND( 25.298,-1); Result: 30
(viii) ROUND(3.798, 1); Result: 3.8
(ix) ROUND(4536.78965,-3) Result: 5000
(X) ROUND(4536.564553,-2): Result: 4500
(XI) ROUND(4586.564553,-2): Result: 4600
(XII)ROUND(76823.298, -2); Result:76800
XII)ROUND(76823.298, 2); Result: 76823.30
(XIII) ROUND(3.798, 2); Result: 3.80

3. MOD(x,y): Divides x by y and gives the remainder.


(i)SELECT MOD(12,5); Result: 2

CHARACTER / STRING FUNCTIONS

15 | P a g e
1. LENGTH(): Returns the length of a string in bytes/no. of characters in string.
Example:
(i) SELECT LENGTH(‘#INFOR MATICS#’); Result:14
(ii)SELECT LENGTH(First_Name) FROM Employee;
Result:

+--------------------+
| LENGTH(First_Name) |
+--------------------+
|4|
|7|
|8|
|5|
|6|
+--------------------+
5 rows in set (0.00 sec)

1. INSTR(): Returns the index of the first occurrence of substring.


Example:
(i) SELECT INSTR(‘Informatics’,’ mat’);
Result: 6 (since ‘m’ of ‘mat’ is at 6th place)
(ii) SELECT INSTR ('Computers', 'pet');
Result: 0
(iii) mysql> SELECT INSTR (First_Name,'Kiran') FROM Employee;
Result:
+---------------------------+
| INSTR(First_Name,'Kiran') |
+---------------------------+
|0|
|0|
| 4 | Select instr(“good morning to all”,”or”)

16 | P a g e
|0|
|0|
+---------------------------+

(iv) Select instr(“good morning to all”,”or”) Result: 7

5. LOWER()/ LCASE(): Convert the string in lowercase.


Example:
SELECT LOWER(‘INFORMATICS’); Result: informatics

6. UPPER()/ UCASE(): Convert the string in uppercase.

Example:
SELECT UCASE(‘informatics’); Result: INFORMATICS

7.LEFT(): Returns the given number of characters by extracting them from the left
side of the given string
Example:
SELECT LEFT(‘INFORMATICS PRACTICES’, 3); Result: INF

8. RIGHT(): Returns the given number of characters by extracting them from the
right side of the given string
Example:
SELECT RIGHT(‘INFORMATICS PRACTICES’,3); Result: CES

9. MID()/ SUBSTR(): Returns a substring starting from the specified position in a


given string.
Example:
(i) SUBSTR(‘INFORMATICS PRACTICES’,3,4); Result: FORM
(ii) SELECT SUBSTRING('Informatics',3); Result:'formatics'
(iii) SELECT SUBSTRING('Computers', -3); Result: 'ers'

17 | P a g e
(iv) SELECT SUBSTRING('Computers', -5, 3); Result: 'ute'
(v) SELECT MID('Informatics',3,4); Result: 'form'
(vi) SELECT MID(first_name,3,2) FROM Employee;
Result:
+---------------------+
| MID(first_name,3,2) |
+---------------------+
| it |
| ek |
| vk |
| mt |
| aw |
+---------------------+
10. LTRIM(): Removes leading spaces.
Example:
SELECT LTRIM(' INFORMATICS '); Result: 'INFORMATICS’

11. RTRIM(): Removes trailing spaces.


Example:
SELECT RTRIM(‘ INFOR MATICS '); Result: ‘ INFOR MATICS’

12. TRIM(): Removes leading and trailing spaces.


Example:
SELECT TRIM(' $$INFOR MATICS$$ '); Result: ‘$$INFOR MATICS$$’

Date/Time Functions
1. NOW(): Returns the current date and time
Example:
select NOW(); Result: '2020-04-06 13:58:11'

2. DATE(): Extracts the date part of a date or datetime expression

18 | P a g e
Example:
SELECT DATE('2020-04-06 01:02:03'); Result: '2020-04-06'

3. MONTH(): Returns the month from the date passed as argument.


Example:
SELECT MONTH('2020-03-21'); Result:3

4. YEAR(): Returns the year.


Example:
SELECT YEAR('2020-03-21'); Result: 2020

5. DAYNAME(): Returns the name of the weekday.


Example:
SELECT DAYNAME('2010-07-21'); Result: WEDNESDAY
6. DAY(): Returns the day of the month
Example:
SELECT DAY(‘2022-07-14’); Result: 14
7. MONTHNAME(): Returns the name of the month
Example:
SELECT MONTHNAME(‘2022-07-14’); Result: July
Multiple Row Functions
(Aggregate Function)

 Aggregate functions summarize the results of a query and return a single value
calculated from values in a column instead of providing the listing of all of the
rows.
Syntax:
SELECT <FUNCION> (column_name) FROM <table_name>;
The following are aggregate functions:

19 | P a g e
1) SUM(): returns the total sum of a numeric column. It gives the arithmetic sum of
all the values present in a particular column. It can take only one argument. NULL
values are not included in the calculations.
Example: SELECT SUM(MARKS) FROM STUDENT;
It displays sum of all the marks in the table student

2) AVG(): returns the average value of any column or expression based on a


column. NULL value not included
Example: SELECT AVG(MARKS) FROM STUDENT;
It displays average of all the marks in the table student

3) MAX(): It returns the maximum value among the given set of values of any
column or expression based on column.
Example: SELECT MAX(MARKS) FROM STUDENT;
It displays maximum marks from the column marks of student table.

4) MIN(): It returns the minimum value among the given set of values of any
column or expression based on column.
Example: SELECT MIN (MARKS) FROM STUDENT;
It displays minimum marks from the column marks of student table.

5) COUNT(): It count the number of non-null values in a column. It can take one
argument, which can be a column name or *. When the argument is a column name
then COUNT() returns the non-null values in that column.
If the argument is an * then COUNT() counts the total number of records / rows
along with the NULL values satisfying the condition, if any, in the table. So, it returns
the total number of records or rows from the table.

Syntax: SELECT COUNT(COLUMN_NAME) FROM <TABLE_NAME>;


Example: SELECT COUNT(*) FROM STUDENT ;

20 | P a g e
It will give output as 10 rows.
But while writing SELECT COUNT(MARKS) FROM STUDENT;
Will give output as 7 because there will be 3 null values which is ignored by COUNT()

SORTING IN SQL – ORDER BY

 The SQL ORDER BY clause is used to sort data in ascending or descending


order based on one or more columns.
 It sorts record in ascending order by default.
 To sort data in descending order DESC keyword is used.
Syntax:
SELECT <column_name> FROM <table_name>
[where <condition>]
ORDER BY <column_name> [ASC/DESC];
Example: To display the roll number, name and marks of students on the
basis of their marks in ascending order.

SELECT ROLLNO, NAME, MARKS FROM STUDENT


ORDER BY NAME;

Sorting data on Multiple columns:


Syntax:
SELECT <column_name> FROM <table_name>
[where <condition>]
ORDER BY <column_name> [ASC/DESC] , <column_name> [ASC/DESC];

Example: To display the roll number, name and marks of all the students in
descending order of their marks and ascending order of their names.
SELECT ROLLNO, NAME , MARKS FROM STUDENT
ORDER BY MARKS DESC, NAME;

21 | P a g e
GROUP BY in SQL
 At times we need to fetch a group of rows on the basis of common values in a
column. This can be done using a GROUP BY clause.
 It groups the rows tog-ether that contain the same values in a specified
column. We can use the aggregate functions (COUNT, MAX, MIN, AVG and
SUM) to work on the grouped values.
 HAVING Clause in SQL is used to specify conditions on the rows with GROUP
BY clause.

Syntax:
SELECT <column1, column2…..> , aggregate function(colname)
FROM <tablename>
WHERE <condition>
GROUP BY <column1>
HAVING <condition>;

Consider the SALE table is given below.

(i) Write a query to display number of cars purchased by each


customer from the SALE Table.
mysql> SELECT CustID, COUNT(*) "Number of Cars" FROM SALE GROUP BY
CustID;

22 | P a g e
(ii) Write a query to display customer id and number of cars purchased
if the customer purchased more than one car from the sale table.
mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING
Count(*)>1;

(iii) Display number of people in each category of payment mode from


the table SALE.
mysql> SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP
BY Paymentmode ORDER BY Paymentmode;

(iv) Display the payment mode and number of payments made using

23 | P a g e
that mode more than once.
mysql> SELECT PaymentMode, Count(PaymentMode) FROM SALE GROUP
BY Paymentmode HAVING COUNT(*)>1 ORDER BY Paymentmode;

TOPIC – SQL QUERIES USING HAVING AND


GROUP BY CLAUSE

1 Write down name of four functions that can be used with Group by?

Ans Count(), sum(), min(), max()

2. What is Group By clause?


Ans The GROUP BY Clause is utilized in SQL with the SELECT statement to organize
similar data into groups. It combines the multiple records in single or more columns
using some functions. Generally, these functions are aggregate functions such as min
(), max (), avg (), count (), and sum () to combine into single or multiple columns.
3. Why we use Having clause?
Ans The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.
4. What is the purpose of Group By clause?
Ans Group by clause is used in a Select statement in conjunction with aggregate
functions to group the result based on distinct values in column.
5.You have a table “Company” having column cno, cname, department and
salary. Write SQL statement to display average salary of each department.
Ans SELECT department, avg(salary) from company
Group by department;
6. Can a Group by clause be used for more than one column? If yes, given an
example.
Ans Yes.
Select name, grade, class
From student
Group by Class, grade
7. Anis has given the following command to arrange the data in ascending
order of date.

24 | P a g e
Select * from travel where order by tdate;
But he is not getting the desired result.
Help him by choosing the correct command.
a. Select * from travel order by tdate;
b. Select * from travel in ascending order;
c. Select tdate from travel order by tdate;
Ans. Select * from travel order by tdate;
8. Find the output of the following SQL queries:
i. SELECT ROUND(7658.345,2);  O/P – 7658.35
ii. SELECT MOD(ROUND(13.9,0),3);  o/p - 2
9. Give any two differences between POWER() and SUM().
Ans: POWER(x,y) – will return value x power to y
SUM() – Aggregate function, and returns sum of values of one column
10. Find the output of the following SQL queries:
i. SELECT SUBSTR(‘FIT INDIA MOVEMENT’,5);
 O/P – INDIA MOVEMEMNT
ii. SELECT INSTR(‘ARTIFICIAL INTELLIGENCE’, ‘IA’);
 O/P - 8
UNSOLVED QUESTIONS

1) Identify the errors in the following queries.


i. Select * from stock where price = NULL;
ii. Select sum[price] from stock;

2) Mr. Das has created the following table ‘Furniture’


F_id Type Price Qty Date_of_purchase

F12 Double Bed 40000 3 2020-08-19

F22 Sofa 35000 4 2021-11-23

F41 Dining Table 20000 2 2021-12-30


Write the output of the following queries:
i. Select * from Furniture where month(Date_of_purchase) = 8;
ii. Select F_id, Type from Furniture where year(Date_of_purchase) = 2021;
OR

25 | P a g e
Write the queries of the following:
i. Display the details of furniture which are purchased in month of December.
ii. Display the average price of furniture.

3) Write the output of the following:


i. Select substr(“BoardExam@2021”, 4, 7);
ii. Select length(“BoardExam@2021”);
iii. Select left(upper(“BoardExam@2021”),5);
OR
Consider the table ‘School’ whose fields are shown below.
Admno, Class, Mobile, Fees, Name
Write the queries to perform the following task.
i. Display all names in uppercase.
ii. Display the last two characters from column Name.
iii. Display the lowest fees.

4) Identify the following functions:


i. I am a mathematical function and return the remainder.
ii. I am a string function and help to convert lower case string to upper case.
iii. I am a date and time function, returns the month name from the specified
date.
5) Explain the following function with examples.
i. dayname( )
ii. instr( )
iii. now( )

5) Explain the difference between group by and order by clause with example.
6) When we use having clause? Explain with example.
7) Write the SQL queries to do the following:
i. Add a new column “Name” of data type Varchar(30) in table “Hotel”.
ii. Delete a record from table “emp” whose empid is 101.
iii. Delete all the records of table “stock” along with structure.
iv. Display the total of column “Salary” from table “emp”.
v.
8) Based on the table: “Emp” given below:

Empid Salary

1 45000

2 50000

3 55000

4 40000

26 | P a g e
5 NULL
Write the output of the following:
i. Select mod(Salary, 100) from emp;
ii. Select average(Salary) from emp;
iii. Select sum(Salary) from emp where empid > 3;
iv. Select max(Salary) from emp;

9) Predict the output:


i. select substr(‘Informatics Practices’,12,5);
ii. select year(curdate()) + year(yourbirthdate);
10) Write your birthdate in the query then write the output.
i. select round(32.567890);
ii. select lower(‘pre-board I’);

11) Predict the output for following query:


i. select pow(month(now()),2);
ii. select left(dayname(now()),5)
iii. select length('Informatics Practice Class 12’);
OR
Explain the functions with suitable example to do this:
i. To find the position of specific word or character in the given text
ii. Display the total number characters from the text
iii. To display remainder of given two numbers
12) Vats is working with functions of MySQL. Explain him the following with
example:
i. To remove extra leading spaces from the text
ii. To return only day part from today’s date
iii. To return average of particular column from the table
13) Om has written following queries:
i. select count(*) from student;
ii. select count(std_no) from student;

27 | P a g e
He was surprised with the output as query (i) returns 5 rows whereas Query(ii)
returns only 3 rows. Explain why?
14) Which functions in MySQL extract words from specified character to n number of
character from given string. Write the function names and explain them with
example.
15) Anuj is student of class XII, trying to execute the following queries, help him to
predict the output.
i. select round (45.9,-2);
ii. select round ( -101.86,0)

28 | P a g e

You might also like