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

Ch 1 Querying and SQL Functions 2024-25

Uploaded by

reduxotter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Ch 1 Querying and SQL Functions 2024-25

Uploaded by

reduxotter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter 1

Querying and SQL Function

Syllabus 2024-25 :
 Revision of database concepts and SQL commands covered in class XI
 Math functions: POWER (), ROUND (), MOD ().
 Text functions: UCASE ()/ UPPER (), LCASE ()/ LOWER (), MID ()/
SUBSTRING () /SUBSTR (), LENGTH (), LEFT (), RIGHT (), INSTR (), LTRIM
(), RTRIM (), TRIM ().
 Date Functions: NOW (), DATE (), MONTH (), MONTHNAME (), YEAR (), DAY
(), DAYNAME ().
 Aggregate Functions: MAX (), MIN (), AVG (), SUM (), COUNT (); using
COUNT (*).
 Querying and manipulating data using Group by, Having, Order by.
 Working with two tables using equi-join

1. What do you meant by Function in MySQL?


Ans. A Function in MySQL is a special type of pre-defined command set that
performs some operation and returns a single value.
2. a)Write the two Categories of Function in MySQL.
Ans. Function can be categories in two ways-

 Single-row functions (also called Scalar functions)operate on a single


value to return a single value. They can accept one or more arguments but
return only one result per row. When applied on a table, they return a single
result for every row of the queried table. They are further categorized into:
.
 Numeric or Maths functions - Math functions accept numeric value as
input, and return a numeric value as a result.
 String functions - String functions accept character value as input, and
return either character or numeric values as output.
 Date and Time functions - Date and time functions accept date and
time values as input, and return numeric or string, or date and time values
as output.
Class Notes :2024-25

 Multiple-Row Functions (also called Aggregate Functions):Multiple


row functions operate on a set of rows to return a single value.
Examples include SUM(), AVG(), MIN(), MAX() and COUNT().

b) Write the differences between Single row and Multiple row Functions

Ans. Single Row Functions Multiple Row Functions


i) Also known as Scalar Functions i) Also known as Aggregate
Functions.
ii) It operates on a single row at a ii) It operates on groups of rows.
time.
iii) It returns one result per row. iii) It returns one result for a group of
rows.
iv) It can be used in Select, Where, and iv) It can be used in the select clause
Order by clause. only.
v) Math, String and Date functions v) Max(), Min(), Avg(), Sum(), Count()
are examples of single row and Count(*) are examples of
functions. multiple row functions.
3. Write various Numeric/Maths Functions in MySQL.
Ans. i) POWER(m,n) or POW(m,n) – Returns the value of m raised to the power of n.
Eg.32=9

SELECT POW(2,4);
Result: 16

SELECT POW(2,-2);
Result: 0.25

SELECT POW(-2,3);
Result:-8

SELECT id, salary, POWER(salary,2) FROM employee;


Result:

ii) SQRT(n) –Returns square root of the given number.

SELECT SQRT(26);
Result: 5.09901951

SELECT SQRT(25);
Result: 5

Chapter 1:Quering and SQL Functions 2|P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

iii) MOD(m,n) – Returns modulus (i.e. remainder) of the given two number.

SELECT MOD(11,4);
Result: 3

SELECT MOD(25,5);
Result: 0

iv) SIGN(n) –Returns sign of the given number. If n<0, returns -1; If n=0,
returns 0; If n>0, returns 1

SELECT SIGN(-11);
Result: -1

SELECT SIGN(25);
Result: 1

v) ROUND(X,D) or ROUND(X) –This function returns a number rounded off


as per given specification:

a) Rounds the argument X to D decimal places.

SELECT ROUND(6.298,1);
Result: 6.3

SELECT ROUND(-1.58);
Result: -2

b) If number of decimal places is not specified or is zero, the number rounds


to the nearest integer OR (0 decimal places).

SELECT ROUND(-1.23);
Result: -1

SELECT ROUND(-1.58);
Result: -2

SELECT ROUND(1.43);
Result: 1

c) If negative value is specified for precision, it counts off that value left from
the decimal point to nearest ten‟s/hundred‟s etc.

SELECT ROUND(56.235,-1);
Result: 60

SELECT ROUND(55.235,-1);
Result: 60

SELECT ROUND(54.235,-1);
Result: 50
Chapter 1:Quering and SQL Functions 3|P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

SELECT ROUND(54.235,-2);
Result: 100

SELECT ROUND(500.35,-3);
Result: 1000

vi) TRUNCATE(X,D) – This function just truncates the digits without


rounding them off.
Note:TRUNCATE does not round a number. It simply chops off digits from a
number.

a) Returns the number X, truncated to D decimal places.

SELECT TRUNCATE(7.543,1);
Result: 7.5

b) If D is 0, the result has no decimal point or fractional part.

SELECT TRUNCATE(4.567,0);
Result: 4

c) If D is negative, it causes D digits left of the decimal point of the value X to


become zero.
SELECT TRUNCATE(346,-2);
Result: 300

4. Write various String Function in MySQL.


Ans. String functions operate on character type data. String functions are used to
extract, change, format or alter character strings. They return either character or
numeric values.
Note :ASCII values -
65 to 90  A-Z
97 to 122 a-z
48 to 57  0-9

i) ASCII() – Returns the ASCII value of the leftmost character of the string
str. Returns 0 if str is an empty string. Returns NULL if str is NULL.

SELECT ASCII(„2‟);
Result: 50

SELECT ASCII('dx');
Result: 100

SELECT ASCII('A');
Result: 65

SELECT ASCII('');
Result: 0

Chapter 1:Quering and SQL Functions 4|P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

ii) CHAR() – This function returns the character for each integer passed.

SELECT CHAR(70,65,67,69);
Result :
+--------------------+
| char(70,65,67,69) |
+--------------------+
| FACE |
+--------------------+

iii) CONCAT(str1,str2) – Returns the string that results from concatenating


the arguments. May have one or more arguments.

SELECT CONCAT('My', 'S', 'QL');


Result: 'MySQL'

SELECT CONCAT('Class„,NULL,'XI');
Result: NULL

SELECT CONCAT(FirstName,'',LastName)FROM Employee;


Result:

iv) LOWER(str) or LCASE(str) – Returns the argument (str) in lowercase i.e.


it changes all the characters of the passed string to lowercase.

SELECT LOWER('INFORMATICS');
Result: 'informatics'

SELECT LOWER(Last_Name)FROM Employee;


Result:

v) UPPER(str) or UCASE(str) – Returns the argument in uppercase i.e. it


changes all the characters of the passed string to uppercase.

SELECT UPPER('informatics');
Result: 'INFORMATICS'

SELECT UPPER(Last_Name)FROM Employee;


Result:

Chapter 1:Quering and SQL Functions 5|P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

vi) SUBSTRING(str,m,n) or SUBSTR(str,m,n) or MID(str,m,n) – Returns


the specified number of characters from the middle of the string. There are
3 arguments.
str is the source string.
m is the position of first character to be displayed. If m is negative, counts
backwards from the end of str.
n is the number of characters to be displayed. If the n is missing, then
starting from the position specified, the rest of the string is returned. If n is
less then 1, a null is returned.
SELECT SUBSTRING('Informatics',3);
Result: 'formatics'

SELECT SUBSTRING('Informatics',-3);
Result: ‘ics'

SELECT SUBSTRING('Informatics' FROM 4);


Result: 'ormatics'

SELECT SUBSTRING('Informatics',3,4);
Result: 'form'

SELECT SUBSTRING('Computers', -5, 3);


Result: 'ute'

SELECT SUBSTRING('Computers' FROM -4 FOR 2);


Result: 'te'

SELECT MID('Informatics„,3,4);
Result: 'form'

Select MID(first_name,3,2) FROM Employee;


Result :

vii) LEFT(str,len) – Returns the specified number of characters (len) from the
left side of string str.

SELECT LEFT('Informatics', 3);


Chapter 1:Quering and SQL Functions 6|P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Result: 'Inf'

SELECT LEFT(first_name,3)FROM Employee;


Result:

viii) RIGHT(str,len) – Returns the specified number of characters (len) from the
right side of string str.

SELECT RIGHT('Informatics', 3);


Result: ‘ics'

SELECT RIGHT(first_name,3)FROM Employee;


Result:

ix) LENGTH(str) – Returns the length of a column or a string in bytes


including whitespaces.

SELECT LENGTH('Informatics Practices');


Result: 21

SELECT LENGTH(First_Name)FROM Employee;


Result:

x) INSTR(str1,str2) – This function searches for given second string into the
given first string and returns the position number of the first occurrence of
substring str2 in string str1.

SELECT INSTR ('Informatics', 'for');

Chapter 1:Quering and SQL Functions 7|P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Result: 3

SELECT INSTR ('Computers', 'pet');


Result: 0

SELECT INSTR („Corporate Floor', „or');


Result: 2

SELECT INSTR (First_Name,'Kiran')FROM Employee;


Result : 4

xi) LTRIM(str) – Removes leading spaces i.e. removes spaces from the left side
of the string str.

SELECT LTRIM (' Informatics');


Result: 'Informatics'

SELECT LTRIM(First_Name)FROM Employee;


Result:

xii) RTRIM(str) – Removes trailing spaces i.e. removes spaces from the right
side of the string str.

SELECT RTRIM („Informatics ');


Result: 'Informatics'

SELECT RTRIM(First_Name)FROM Employee;


Result:

xiii) TRIM(str) – Removes both leading and trailing spaces from the string str.

SELECT TRIM („ Informatics ');


Result: 'Informatics'

SELECT TRIM(First_Name)FROM Employee;


Result:
Chapter 1:Quering and SQL Functions 8|P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Some advance and complex SQL Queries.For example :


Q. #To extract the user name from the email id.
SELECT LEFT('[email protected]' ,
INSTR('[email protected]' ,"@")-1);

Q. #To extract the domain name from the email id.


SELECT RIGHT('[email protected]' ,
INSTR('[email protected]' ,"@")+1);

Q. #Add a column email_id to customer table with a suitable data type.


alter table customer add email_idvarchar(30) after phone;

Q. # Create a gmail account from customer name by extracting the


customer first name and add the domain name such as @gmail.com
SELECTlower(concat(left(name,instr(name," ")-1),"@gmail.com"))
FROM CUSTOMER;

Q. # Update all emails by Create a gmail account from customer name,


extracting the customer first nameand add the domain name such as
@gmail.com
UPDATE CUSTOMER SET
EMAIL_ID=lower(concat(left(name,instr(name," ")-
1),"@gmail.com"));
Q. #Display emails after removing the domain name extension “.com” from
emails of the customers.
SELECT TRIM(“.com” from Email_id) FROM CUSTOMER;

Q. # Display details of all the customers having gmail emails only.


SELECT * FROM CUSTOMER WHERE Email_id LIKE "%gmail%";

5. Write the various Date/Time function in MySQL.


Ans. Date and Time functions allow us to perform many types of tasks on Date type
data. The default date format in MySQL is YYYY-MM-DD.

i) CURDATE() or CURRENT_DATE() or CURRENT_DATE - Returns


the current date in YYYY-MM-DD format or YYYYMMDD format,
depending on whether the functions used in a string or numeric context.

SELECT CURDATE();
Result: '2013-11-24'

Chapter 1:Quering and SQL Functions 9|P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

ii) NOW() - Returns the current date and time in 'YYYY-MM-DD HH:MM:SS'
or YYYYMMDDHHM MSS.uuuuuu format, depending on whether the
function is used in a string or numeric context.

SELECT NOW();
Result: 2013-11-24 20:53:54

iii) SYSDATE() - Returns the current date and time in 'YYYY-MM-DD


HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on
whether the function is used in a string or numeric context.
SYSDATE() returns the time at which the function executes.

SELECT SYSDATE();
Result: 2013-11-24 20:53:54

iv) DATE(datetime) - Extracts the date part of a date or datetime expression.


SELECT DATE('2010-02-26 01:02:03');
Result: '2010-02-26'

v) MONTH(date) - Returns the numeric month from the date passed, in the
range 0 to 12. It returns 0 for dates such as '0000-00-00' or '2010-00-00‘
that have a zero month part.

SELECT MONTH('2010-02-26');
Result: 2

vi) YEAR(date) - Returns the year for date passed in the range 0 to 9999.
Returns values like 1998, 2010,1996 and so on.

SELECT YEAR('2013-11-24');
Result: 2013

vii) DAYNAME(date) - returns the name of the weekday for the date passed

SELECT DAYNAME('2009-07-21');
Result:'Tuesday'

viii) DAYOFMONTH(date) - Returns the day of the month in the range 0 to31.

SELECT DAYOFMONTH('2010-02-26');
Result: 26

ix) DAYOFWEEK(date) - Returns the day of week in number as 1 forSunday,


2 for Monday and so on.

SELECT DAYOFWEEK('2013-11-24');
Result: 1

x) DAYOFYEAR(date) - Return the day of the year for the given date in
numeric format in the range 1 to 366.
Chapter 1:Quering and SQL Functions 10 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

SELECT DAYOFYEAR('2013-11-24');
Result: 328

xi) MONTHNAME(date) - It returns the month name from the specified date.
SELECT MONTHNAME(„2003-11-28‟);
Result: November

6. How the SYSDATE() is differ from NOW() date function in MySQL.

Ans. SYSDATE() returns the time at which the function executes.


SYSDATE() differs from NOW() which returns a constant time that indicates the
time at which the statement began to execute.

7. Define Multiple Row Function.


Ans. A multiple row function works on multiple values. These functions are called
Aggregate Functions or Group Functions.
8. Write most commonly used Aggregate Function in MySQL.
Ans. i) MAX() – Returns the MAXIMUM of the values under the specified
column/expression.
ii) MIN() - Returns the MINIMUM of the values under the specified
column/expression.
iii) AVG() - Returns the AVERAGE of the values under the specified
column/expression.
Here we have a Limitation: The argument of AVG() function can be of
numeric (int / decimal) type only. Averages of String and Date type
data are not defined.
iv) SUM() - Returns the SUM of the values under the specified
column/expression.
v) COUNT() - Returns the COUNT of the number of values under the specified
column/expression.

9. Consider the following table :

Chapter 1:Quering and SQL Functions 11 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

# MAX() – MAX() function is used to find the Highest Value of any column or any
expression based on a column. MAX() takes one argument which can be any
column name or a valid expression involving a column name.
Q. To find the highest cost of any type of shoe in the factory.
SELECT MAX(cost)FROM shoes;

Q. To find the highest cost of any shoe of type 'School'.


SELECT MAX(cost)FROM shoesWHERE type=„School‟;

# MIN() – MIN() function is used to find the Lowest Value of any column or an
expression based on a column. MIN() takes one argument which can be any
column name or a valid expression involving a column name.

Chapter 1:Quering and SQL Functions 12 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Q. To find the lowest cost of any type of shoe in the factory.


SELECT MIN(cost)FROM shoes;

Q. To find the lowest cost of any shoe of type 'School'.


SELECT MIN(cost)FROM shoes WHERE type=„School‟;

# AVG() – AVG() function is used to find the average value of any column or an
expression based on a column. AVG() takes one argument which can be any
column name or a valid expression involving a column name.
Limitation:The argument of AVG() function can be of numeric (int /
decimal) type only.Averages of String and Date type data are not defined.
Q. To find the average margin from shoes table.
SELECT AVG(margin)FROM shoes;

Q. To find the average quantity in stock for the shoes of type Sports.
SELECT AVG(qty)FROM shoes WHERE type=„sports‟;

Q. To find the average quantity in stock for the shoes of type Sports.
SELECT AVG(qty) FROM shoes WHERE type = 'Sports';

# SUM() – SUM() function is used to find the Total Value of any column or an
expression based on a column. SUM() also takes one argument which can be any
column name or a valid expression involving a column name.
Like AVG(), the argument of SUM() function can be of numeric (int/decimal)
type only. Sums of String and Date type data are not defined.

Chapter 1:Quering and SQL Functions 13 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Q. To find the total quantity present in the stock.


SELECT SUM(qty)FROM shoes;

Q. To find the total value (Quantity X Cost) of Shoes of type 'Office' present in the
inventory.
SELECT SUM(cost*qty)FROM shoes WHERE type = 'Office';

# COUNT() – COUNT() function is used to count the number of values in a column.


COUNT() takes one argument which can be any column name, an expression
based on a column, or an asterisk (*). If the argument is a *, then COUNT()
counts the total number of rows satisfying the condition, if any, in the table.
# Differentiate between COUNT( ) and COUNT(*) functions.
COUNT(Column_Name) : It returns the number of non-null values in the
column used in COUNT()
COUNT(*) :It returns the number of rows in the table

Q. To count the total number of records in the table Shoes.


SELECT COUNT(*)FROM shoes;

Q. To count the different types of shoes that the factory produces.


SELECT COUNT(distinct type) FROM shoes;

Q. To count the number of customers in 'A' category.


SELECT COUNT(*) FROM customers WHERE category ='A';

Q. To count the number of orders of quantity more than 300.


SELECT COUNT(*)FROM orders WHERE order_qty> 300;

Chapter 1:Quering and SQL Functions 14 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

10. How are NULL values treated by aggregate functions? Give example.
Ans. None of the aggregate functions takes NULL into consideration. NULL is simply
ignored by all the aggregate functions.
Example 1 :

SELECT COUNT(*)FROM shoes;

Indicating that there are 13 records in the Shoes table

SELECT COUNT(margin) FROM shoes;

This output indicates that there are 10 values in the


margin column of Shoes table. This means there are 3 NULLs in the margin
column.
This feature of aggregate functions ensures that NULLs don't play any
role in actual calculations.
Example 2 :
SELECT AVG(margin) FROM shoes;

The average margin has been calculated by adding all the 10 non NULL values
from the margin column and dividing the sum by 10 and not by 13.
11. What is the purpose of using GROUP BY clause in SQL?
Ans. GROUP BY clause is used to group the rows together that contain similar values
in a specified column. Some of the group functions are COUNT(), MAX(), MIN(),
AVG() and SUM().
The GROUP BY clause combines all those records that have identical values in a
particular field or a group of fields. This grouping results into one summary
record per group if group functions are used with it.
GROUP BY clause is used in a SELECT statement in conjunction with aggregate
Chapter 1:Quering and SQL Functions 15 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

functions to group the result based on distinct values in a column.


HAVING Clause in SQL is used to specify conditions on the rows with GROUP
BY clause.

Q. The management of the shoe factory may want to know what is the total quantity
of shoes of various types. i.e., what is the total quantity of shoes of type School,
Office, and Sports each.
SELECT type, SUM(qty) FROM shoes GROUP BY type;

Q. The management may also want to know what is the maximum, minimum, and
average margin of each type of shoes.
SELECT type, MIN(margin), MAX(margin), AVG(margin)
FROM shoes GROUP BY type;

Q. Find the total number of customers in each category.


SELECT category, COUNT(*) FROM customers GROUP BY category;

12. What is the purpose of HAVING clause used in conjunction with GROUP BY
clause?
Ans. HAVING clause is used in conjunction with GROUP BY clause in a
SELECTstatement to put condition on groups.It means we want to put some
condition on individual groups (and not on individualrecords).
A condition on groups is applied by HAVING clause.

Chapter 1:Quering and SQL Functions 16 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Q. The management of the shoe factory may want to know which shoes total
quantityis more than 1500.
SELECT type, SUM(qty) FROM shoes
GROUP BY type HAVING SUM(qty) > 1500;

Note :In these statements if we try to put the condition using WHERE instead of
HAVING, we shall get an error.
13. Write the difference between WHERE clause and HAVING clause.
Ans. The WHERE clause is used to restrict records in a query i.e. WHERE condition is
applied on individual row before grouping
Whereas, HAVING clause restricts the records after they have been grouped i.e.
HAVING condition is applied on groups.
14. Can we use both WHERE clause and HAVING in a SELECT statement? Give
reason.
Ans. Yes, we can use both WHERE clause for individual record and HAVING clause
for groups in a SELECT statement.

Example-
Q. The management of the shoe factory may want to know what is the totalquantity of
shoes, of sizes other than 6, of various types. i.e., what is the totalquantity of shoes
(of sizes other than 6) of type School, Office, and Sports each. Moreover, the report
is required only for those groups for which the totalquantity is more than 1500.
SELECT type, SUM(qty) FROM shoes
WHERE size <>6 ->Checks individual row
GROUP BY type HAVING sum (qty) > 1500; ->Checks individual group

Q. The management may also want to know what is the maximum, minimum,
andaverage margin of each type of shoes. But in this reports shoes of sizes 6 and
7only should be included. Report is required only for those groups for which
theminimum margin is more than 2.
SELECT type, MIN(margin), MAX(margin), AVG(margin) FROM shoes
WHERE size in (6,7)
GROUP BY type having MIN(margin) > 2;

Chapter 1:Quering and SQL Functions 17 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

15. Write the purpose of using ORDER BY clause in SQL statement.


Ans. ORDER BY clause is used to display data in an ordered (arranged) form with
respect to a specified column. By default, ORDER BY displays records in
ascending order of the specified column‟s values. To display the records in
descending order, the DESC (means descending) keyword needs to be written
with that column.
Eg.-
i) Display data in Ascending order
SELECT * FROM EMPLOYEE
ORDER BY Salary;
Or,
SELECT * FROM EMPLOYEE
ORDER BY Salary ASC;
ii) Display data in Descending order
SELECT * FROM EMPLOYEE
ORDER BY Salary DESC;

iii) Display data in both in Ascending and Descending order


SELECT * FROM EMPLOYEE
ORDER BY EName ASC, Salary DESC;

16. What is Join in term of RDBMS?


Ans. JOIN operation combines tuples from two tables on specified conditions.
To make a Join, a common attributes is required in the relations. This
common attributes is, generally, Primary Key of one relation and
Foreign Key of the other.
Join in RDBMS refers to combination of multiple tables i.e. the data is to be
retrieved from multiple tables. SQL allows us to writestatements which retrieve
data from multiple tables with a common attributes.
Thus, A Join is a query that combines rows from two or more tables.
17. What are the different ways to apply the Join operation in SQL?

Chapter 1:Quering and SQL Functions 18 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Ans. Three different ways to apply Join operation in query statements are –
i) Using condition in WHERE clause – This join repeat the attributes in
its output.
Eg.-
SELECT * FROM UNIFORM U, COST C
WHERE U.UCode = C.UCode;
ii) Explicit use of JOIN clause – JOIN clause explicitly use along with
condition in FROM clause. Hence, no condition needs to be given in
WHERE clause. This join also repeat attributes in the output.
Eg.-
SELECT * FROM UNIFORM U JOIN COST C
ONU.Ucode=C.Ucode;
iii) Explicit use of NATURAL JOIN clause – This join removes the
redundant attributes in its output.
Eg.-
SELECT * FROM UNIFORM NATURAL JOIN COST;
18. Write some of the points to be consideredwhile applying JOIN operations on two
or more relations.
Ans. 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 relationaloperators to combine tuples of
two tables.
19. What do you understand by Cartesian Product?
Or,
Explain and Illustrate Cartesian product or Cross Join.
Ans. Cartesian product operation combines tuples from two relations.The
degree of the resulting relation is calculated as the sum of the degrees of both
the relations under consideration. The cardinality of the resulting relation is
calculated as the product of the cardinality of relations on which cartesian
product is applied.
Cartesian product (also called Cross Join) of two tables is a table obtained by
pairing up each row of one table with each row of the other table. This way if two
tables contain 3 rows and 2 rows respectively, then their Cartesian product will
contain 6 (=3x2) rows. This can be illustrated as follows:

Chapter 1:Quering and SQL Functions 19 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

In SQL, Cartesian product of two rows is obtained by giving the names ofboth
tables in FROM clause.
Example-

SELECT * FROM order_table, product;

Output-

20. What is Equi-Join with reference to RDBMS?


Ans. Equi-Join: An equi join of two tables is obtained by putting an equality condition
on the Cartesian product of two tables. This equality condition is put on the
common column of the tables. This common column is, generally, primary key of
one table and foreign key of the other.
Example-
SELECT * FROM order_table, product
where p_code=code;

21. How the Equi-Join is formed?


Chapter 1:Quering and SQL Functions 20 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Ans. Equi-join is formed by equating two tables.

Q. The management of the shoe factory wants a report of orders which lists three
columns: Order_No, corresponding customer name, and phone number
SELECT order_no , name, phone
FROM orders, customers
WHERE orders.cust_code = customers.cust_code;
Or,
SELECT order_no , name, phone
FROM orders X, customers Y
WHERE X.cust_code = Y.cust_code;

Output :

Q. The management wants a four-column report containing order_no, order_qty,name


of the corresponding shoe and its cost.
SELECT order_no , Order_Qty, name, cost
FROM orders, shoes WHERE Shoe_Code = code;
Output :

Q. The management wants the names of customers who have placed any order of
quantity more than 300.
SELECT name, address FROM orders, customers
WHERE orders.cust_code = customers.cust_code
and order_qty> 300;

Chapter 1:Quering and SQL Functions 21 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Output :

Q. The management wants a report in which with each Order_No management needs
name of the corresponding customer and also the total cost (Order quantity X Cost
of the shoe) of the order are shown.
SELECT order_no, Order_Qty, customers.name,
cost*order_qty AS 'Order Cost'
FROM orders, shoes, Customers
WHERE Shoe_Code = code
AND Orders.Cust_Code = Customers.Cust_Code ORDER BY order_no;
Or,
SELECT X.order_no, X.Order_Qty, Z.name,
Y.cost * X.order_qty AS 'Order Cost'
FROM orders X, shoes Y, Customers Z
WHERE X.Shoe_Code = Y.code
AND X.Cust_Code = Y.Cust_Code ORDER BY X.order_no;
Output :

22. What is the purpose of usingUNION operator in the relations?


Ans. UNION operation is used to combine the selected tuples/rows of two tables
at a time. If some rows are the same in both the tables, then the result of the
Union operation will show those rows only once.
UNION is an operation of combining the output of two SELECT statements.
Union of two SELECT statements can be performed only if their outputs contain
same number of columns and data types of corresponding columns are also
the same.
Union does not display any duplicate rows unless ALL is specified with it.

Example:Consider the following relations.

Table : Dance
+--------+--------+-------+
Chapter 1:Quering and SQL Functions 22 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

| rollno | Name | Class |


+--------+--------+-------+
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
+--------+--------+-------+
Table : Music
+--------+---------+-------+
| rollno | Name | Class |
+--------+---------+-------+
| 1 | Mehak | 8A |
| 2 | Mahira | 6A |
| 3 | Lavanya | 7A |
| 4 | Sanjay | 7A |
| 5 | Abhay | 8A |
+--------+---------+-------+
SELECT * FROM Dance
UNION
SELECT * FROM Music
+--------+---------+-------+
| rollno | Name | Class |
+--------+---------+-------+
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
+--------+---------+-------+
23. What is the purpose of using INTERSECT operator in the relations?
Ans. Intersect operation is used to get the common tuples from two tables and is
represented by the symbol ∩.MySQL does not support the INTERSECT
operator.
Output:
+--------+---------+-------+
| rollno | Name | Class |
+--------+---------+-------+
| 2 | Mahira | 6A |
| 4 | Sanjay | 7A |
+--------+---------+-------+
24. What is the purpose of using MINUS operator in the relations?
Ans. This operation is used to get tuples/rows which are in the first table but not in the
second table, and the operation is represented by the symbol - (minus).
MySQL does not support the MINUS operator.
Output:
+--------+---------+-------+
| rollno | Name | Class |
+--------+---------+-------+
Chapter 1:Quering and SQL Functions 23 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
+--------+---------+-------+

Chapter 1:Quering and SQL Functions 24 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

NCERT Text Book Question and Answer (NEW)

1. Answer the following questions:


a) Define RDBMS. Name any two RDBMS software.
Ans. A DBMS used to manage or the software required to manipulate Relational
Databases is called an RDBMS (RelationalData Base Management System).
In other words a RelationalDatabase is a collection of one or more tables.
Some popular RDBMS software available are:
Oracle, Microsoft SQL Server, MySQL, Sybase, DB2
b) What is the purpose of the following clauses in a select statement?
i) ORDER BY
ii) HAVING
Ans. i) ORDER BY clause is used to display data in an ordered (arranged) form
with respect to a specified column. By default, ORDER BY displays records
in ascending order of the specified column‟s values. To display the records
in descending order, the DESC (means descending) keyword needs to be
written with that column.
ii) HAVING Clause in SQL is used to specify conditions on the rows with
GROUP BY clause.
c) Site any two differences between Single_row functions and Aggregate
functions.
Ans. Single Row Functions Multiple Row Functions
vi) Also known as Scalar Functions vi) Also known as Aggregate
Functions.
vii) It operates on a single row at vii) It operates on groups of rows.
a time.
viii) It returns one result per row. viii) It returns one result for a
group of rows.
ix) It can be used in Select, Where, ix) It can be used in the select clause
and Order by clause. only.
x) Math, String and Date functions x) Max(), Min(), Avg(), Sum(),
are examples of single row Count() and Count(*) are
functions. examples of multiple row
functions.
d) What do you understand by Cartesian Product?
Ans. Cartesian product operation combines tuples from two relations.The
degree of the resulting relation is calculated as the sum of the degrees of both
the relations under consideration. The cardinality of the resulting relation is
calculated as the product of the cardinality of relations on which cartesian
product is applied.
Cartesian product (also called Cross Join) of two tables is a table obtained
by pairing up each row of one table with each row of the other table. This way if
two tables contain 3 rows and 2 rows respectively, then their Cartesian product
will contain 6 (=3x2) rows.
Chapter 1:Quering and SQL Functions 25 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

e) Write the name of the functions to perform the following operations:


i) To display the day like “Monday”, “Tuesday”, from the date when
India got independence.
ii) To display the specified number of characters from a particular
position of the given string.
iii) To display the name of the month in which you were born.
iv) To display your name in capital letters.
Ans. i) SELECT DAYNAME('1947-08-15');
Result:'Friday'
ii) SUBSTRING(str,m,n) or SUBSTR(str,m,n) or MID(str,m,n)
iii) SELECT MONTHNAME(„2003-11-28‟);
Result: November
2. Write the output produced by the following SQL commands:
a) SELECT POW(2,3);
b) SELECT ROUND(123.2345, 2), ROUND(342.9234,-1);
c) SELECT LENGTH("Informatics Practices");
d) SELECT YEAR(“1979/11/26”), MONTH(“1979/11/26”),
DAY(“1979/11/26”), MONTHNAME(“1979/11/26”);
e) SELECT LEFT("INDIA",3), RIGHT("Computer Science",4);
f) SELECT MID("Informatics",3,4), SUBSTR("Practices",3);
Ans. a) SELECT POW(2,3);
+----------+
| POW(2,3) |
+----------+
| 8 |
+----------+
b) SELECT ROUND(123.2345, 2), ROUND(342.9234,-1);
+--------------------+--------------------+
| ROUND(123.2345, 2) | ROUND(342.9234,-1) |
+--------------------+--------------------+
| 123.23 | 340 |
+--------------------+--------------------+
c) SELECT LENGTH("Informatics Practices");
+---------------------------------+
| LENGTH("Informatics Practices") |
+---------------------------------+
| 21 |
+---------------------------------+
d) SELECT YEAR(“1979/11/26”), MONTH(“1979/11/26”),
DAY(“1979/11/26”), MONTHNAME(“1979/11/26”);
+--------------------+---------------------+-------------------+-------------------------+
| YEAR("1979/11/26") | MONTH("1979/11/26") | DAY("1979/11/26") | MONTHNAME("1979/11/26") |
+--------------------+---------------------+-------------------+-------------------------+
| 1979 | 11 | 26 | November |
+--------------------+---------------------+-------------------+-------------------------+
e) SELECT LEFT("INDIA",3), RIGHT("Computer Science",4);
+-----------------+-----------------------------+
| LEFT("INDIA",3) | RIGHT("Computer Science",4) |
+-----------------+-----------------------------+
| IND | ence |
+-----------------+-----------------------------+
Chapter 1:Quering and SQL Functions 26 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

f) SELECT MID("Informatics",3,4), SUBSTR("Practices",3);


+------------------------+-----------------------+
| MID("Informatics",3,4) | SUBSTR("Practices",3) |
+------------------------+-----------------------+
| form | actices |
+------------------------+-----------------------+
3. Consider the following table named “Product”, showing details of products being
sold in a grocery shop.
PCode PName UPrice Manufacturer
P01 Washing Powder 120 Surf
P02 Tooth Paste 54 Colgate

P03 Soap 25 Lux

P04 Tooth Paste 65 Pepsodant


P05 Soap 38 Dove
P06 Shampoo 245 Dove

a) Write SQL queries for the following:


i) Create the table Product with appropriate data types and constraints.
ii) Identify the primary key in Product.
iii) List the Product Code, Product name and price in descending order of their
product name. If PName is the same then display the data in ascending
order of price.
iv) Add a new column Discount to the table Product.
v) Calculate the value of the discount in the table Product as 10 per cent of the
UPrice for all those products where the UPrice is more than 100, otherwise
the discount will be 0.
vi) Increase the price by 12 per cent for all the products manufactured by Dove.
vii) Display the total number of products manufactured by each
manufacturer.
Ans. i) Create Table Product
(
PCode char(4) Primary Key,
PName varchar(30),
UPrice int,
Manufacturer varchar(20)
);
ii) PCode is the Primary Key in Product table.
iii) SELECT PCode, PName, UPrice from Product ORDER BY PName
DESC;
iv) ALTER TABLE Product ADD Discount decimal(10,2);
v) UPDATE Product SET Discount=UPrice*0.1 WHERE UPrice>100;
vi) UPDATE Product SET UPrice=UPrice+UPrice*0.12 WHERE
manufacturer='Dove';
Chapter 1:Quering and SQL Functions 27 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

vii) SELECT PName, count(PName) from Product GROUP BY PName;

b) Write the output(s) produced by executing the following queries on the basis of
the information given above in the table Product:
i) SELECT PName, Avg(UPrice) FROM Product GROUP BY Pname;
ii) SELECT DISTINCT Manufacturer FROM Product;
iii) SELECT COUNT(DISTINCT PName) FROM Product;
iv) SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY
PName;
Ans. i) SELECT PName, Avg(UPrice) FROM Product GROUP BY Pname
+----------------+-------------+
| PName | Avg(UPrice) |
+----------------+-------------+
| Shampoo | 274.0000 |
| Soap | 34.0000 |
| Tooth Paste | 59.5000 |
| Washing Powder | 120.0000 |
+----------------+-------------+
ii) SELECT DISTINCT Manufacturer FROM Product;
+--------------+
| Manufacturer |
+--------------+
| Surf |
| Colgate |
| Lux |
| Pepsodant |
| Dove |
+--------------+
iii) SELECT COUNT(DISTINCT PName) FROM Product;
+-----------------------+
| COUNT(DISTINCT PName) |
+-----------------------+
| 4 |
+-----------------------+
iv) SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP
BY PName;
+----------------+-------------+-------------+
| PName | MAX(UPrice) | MIN(UPrice) |
+----------------+-------------+-------------+
| Shampoo | 274 | 274 |
| Soap | 43 | 25 |
| Tooth Paste | 65 | 54 |
| Washing Powder | 120 | 120 |
+----------------+-------------+-------------+
5. Consider the following tables Student and Stream in the Streams_of_Students
database. The primary key of the Stream table is StCode (stream code) which is the
foreign key in the Student table. The primary key of the Student table is AdmNo
(admission number).

Chapter 1:Quering and SQL Functions 28 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Table : Student
AdmNo Name StCode
211 Jay NULL
241 Aditya S03
290 Diksha S01
333 Jasqueen S02
356 Vedika S01
380 Ashpreet S03

Table : Stream
StCode Stream
S01 Science
S02 Commerce
S03 Humanities

Write SQL queries for the following:


a) Create the database Streams_Of_Students.
b) Create the table Student by choosing appropriate data types based on the
data given in the table.
c) Identify the Primary keys from tables Student and Stream. Also, identify the
foreign key from the table Stream.
d) Jay has now changed his stream to Humanities. Write an appropriate SQL
query to reflect this change.
e) Display the names of students whose names end with the character „a‟. Also,
arrange the students in alphabetical order.
f) Display the names of students enrolled in Science and Humanities stream,
ordered by student name in alphabetical order, then by admission number in
ascending order (for duplicating names).
g) List the number of students in each stream having more than 1 student.
h) Display the names of students enrolled in different streams, where students
are arranged in descending order of admission number.
i) Show the Cartesian product on the Student and Stream table. Also mention
the degree and cardinality produced after applying the Cartesian product.
j) Add a new column „TeacherIncharge” in the Stream table. Insert appropriate
data in each row.
k) List the names of teachers and students.
l) If Cartesian product is again applied on Student and Stream tables, what
will be the degree and cardinality of this modified table?
Ans. a) create database streams_of_students;
use streams_of_students;
b) Create Table Stream
(
StCode char(4) PRIMARY KEY,
Stream varchar(10)
Chapter 1:Quering and SQL Functions 29 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

);
Create Table Student
(
AdmNo int Primary Key,
Name varchar(30),
StCode char(4),
FOREIGN KEY (StCode) REFERENCES Stream(StCode)
);
c) StCode and AdmNois Primary Key in Stream and Student Table
respectively.StCodeis Foreign Key in Student Table.
d) UPDATE STUDENT SET StCode=(SELECT StCode From Stream where
Stream ='Humanities') Where Name='Jay';
e) SELECT Name FROM Student WHERE name LIKE '%a' ORDER BY
name;
+--------+
| Name |
+--------+
| Aditya |
| Diksha |
| Vedika |
+--------+
f) SELECT x.admno, name, y.stream FROM student x, stream y
WHERE x.stcode=y.stcode AND y.stream IN ('Humanities',
'Science') ORDER BY x.name, x.admno;
g) SELECT x.admno, name, y.stream, count(x.stcode) as 'No. of
Students' FROM student x, stream y WHERE x.stcode=y.stcode
GROUP BY x.stcode HAVING count(x.stcode)>1;
h) SELECT x.admno, name, y.stream FROM student x, stream y
WHERE x.stcode=y.stcode ORDER BY admno desc;
i) +-------+----------+--------+--------+------------+
| AdmNo | Name | StCode | StCode | Stream |
+-------+----------+--------+--------+------------+
| 211 | Jay | S03 | S01 | Science |
| 211 | Jay | S03 | S02 | Commerce |
| 211 | Jay | S03 | S03 | Humanities |
| 241 | Aditya | S03 | S01 | Science |
| 241 | Aditya | S03 | S02 | Commerce |
| 241 | Aditya | S03 | S03 | Humanities |
| 290 | Diksha | S01 | S01 | Science |
| 290 | Diksha | S01 | S02 | Commerce |
| 290 | Diksha | S01 | S03 | Humanities |
| 333 | Jasqueen | S02 | S01 | Science |
| 333 | Jasqueen | S02 | S02 | Commerce |
| 333 | Jasqueen | S02 | S03 | Humanities |
| 356 | Vedika | S01 | S01 | Science |
| 356 | Vedika | S01 | S02 | Commerce |
| 356 | Vedika | S01 | S03 | Humanities |
| 380 | Ashpreet | S03 | S01 | Science |
| 380 | Ashpreet | S03 | S02 | Commerce |
| 380 | Ashpreet | S03 | S03 | Humanities |
+-------+----------+--------+--------+------------+
Degree : 5, Cardinality : 18
Chapter 1:Quering and SQL Functions 30 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

j) ALTER TABLE STREAM ADD TeacherIncharge varchar(30);


UPDATE stream SET TeacherIncharge='Ramesh Singh' where
StCode='S01';
UPDATE stream SET TeacherIncharge='Prem Singha' where
StCode='S02';
UPDATE stream SET TeacherIncharge='Preeti' where
StCode='S03';
k) SELECT x.admno, name, y.stream, teacherincharge FROM
student x, stream y WHERE x.stcode=y.stcode;
l) Degree : 6, Cardinality : 18

Chapter 1:Quering and SQL Functions 31 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

NCERT Text Book Question and Answer (OLD)

1. Define a Function.
Ans. A Function in MySQL is a special type of pre-defined command set that
performs some operation and returns a single value.
2. List 3 categories of single row functions. Give two examples in each category.
Ans. Single row functions operate on a single value to return a single value.
The three categories of Single Row function are –
i) Numeric functions – Eg. pow(), sqrt(), mod(), round(), truncate()
ii) String functions – Eg.ASCII(), CHAR(), Substring(), INSTR() etc
iii) Date and Time functions – Eg.CURDATE(), NOW(), SYSDATE(), DATE()

3. How are numeric functions different from String functions?


Ans. Numeric functions perform operations on numeric values and return numeric
values.
String functions operate on character type data. They return either character
or numeric values
4. Which function is used to display the System Date?
Ans. CURDATE()
5. Which Date function displays the result like "Monday" or "Tuesday" etc.
Ans. DAYNAME(date)
6. Name a
i) Date function that returns a number.
ii) String function that returns a number.
iii) Date function that returns a date.
Ans. i) month(date), year(date), dayofmonth(date), dayofweek(date)
&dayofyear(date)
ii) instr(str1, str2), length(str), ASCII()
iii) curdate()
7. Write SQL statements to do the following:
i) Using the three separate words "We," "study," and "MySQL," produce the following
output:
"We study MySQL"
Ans. SELECT CONCAT('My', 'S', 'QL');
ii) Use the string "Internet is a boon" and extract the string "net".
Ans. SELECT SUBSTRING('Internet is boon',6,3);
iii) Display the length of the string "Informatics Practices".
Ans. SELECT LENGTH('Informatics Practices‟);
Output:
21
iv) Display the position of "My" in "Enjoying MySQL".
Ans. SELECT INSTR ('Enjoying MySQL', 'My');

Chapter 1:Quering and SQL Functions 32 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Output:
10
v) Display the name of current month.
Ans. SELECT MONTH(CURDATE());
vi) Display the date 10 years from now. Label the column "Future."
Ans. SELECT YEAR(CURDATE())+10 AS „FUTURE‟;
vii) Display the day of week on which your birthday will fall or fell in 2010.
Ans. SELECT DAYOFWEEK('2010-11-24');
8. Write the output that the following statements will produce:
a) SELECT ROUND(7.3456, 2);
b) SELECT TRUNCATE(2.3456, 2);
c) SELECT DAYOFMONTH('2009-08-25');
d) SELECT MONTH('2010-02-26');
e) SELECT RIGHT('Informatics', 4);
Ans. a) 7.35
b) 2.34
c) 25
d) 2
e) tics

Lab Exercises
1. Create the following table named "Charity" and write SQL queries for the tasks
that follow:
Table : Charity
P_ID LastName FirstName Address City Contribution
1 Bindra Jaspeet 5B, Gomti Nagar Lucknow 3500.50
2 Rana Monica 21 A, Bandra Mumbai 2768.00
3 Singh Jatinder 8, Punjabi Bagh Delhi 2000.50
4 Arora Satinder K/1,Shere Mumbai 1900.00
Punjab Colony
5 Krishnan Vineeta A-75,Adarsh
Nagar
i) Display all first names in lowercase.
ii) Display all last names of people of Mumbai city in uppercase.
iii) Display Person Id along with First 3 characters of his/her name.
iv) Display first name concatenated with last name for all the employees.
v) Display length of address along with Person ID.
vi) Display last 2 characters of City and Person ID.
vii) Display Last Names and First names of people who have "at" in the
second or third position in their first names.
viii) Display the position of „a‟ in Last name in every row.
ix) Display Last Name and First name of people who have "a" as the last
character in their First names.
x) Display the first name and last name concatenated after removing the
leading and trailing blanks.
xi) Display Person Id, last names and contribution rounded to the nearest
rupee of all the persons.
Chapter 1:Quering and SQL Functions 33 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

xii) Display Person Id, last name and contribution with decimal digits
truncated of all the persons.
xiii) Display Last name, contribution and a third column which has
contributiondivided by 10. Round it to two decimal points.
Ans. SQL command to creating table “Charity”-
CREATE TABLE CHARITY
(
P_ID int Primary Key,
LastName varchar(30),
FirstName varchar(30),
Address varchar(50),
City varchar(20),
Contribution decimal(10,2)
);
SQL command to Inserting data to the table “Charity”-

INSERT INTO charity VALUES


(1,‟Bindra‟,‟Jaspeet‟,‟5B,Gomti Nagar‟,‟Lucknow‟,3500.50);

INSERT INTO charity VALUES


(2,‟Rana‟,‟Monica‟,‟21 A, Bandra‟,‟Mumbai‟,2768.00);

INSERT INTO charity VALUES


(3,‟Singh‟,‟Jatinder‟,‟8, Punjabi Bagh‟,‟Delhi‟,2000.50);

INSERT INTO charity VALUES


(4,‟Arora‟,‟Satinder‟,‟K/1, Shere Punjab Colony‟,‟Mumbai‟,1900.00);

INSERT INTO charity VALUES


(5,‟Krishnan‟,‟Vineeta‟,‟A-75, Adarsh Nagar‟,null,null);

SQL Command to Display all record from table Charity


SELECT * FROM Charity;
i) Display all first names in lowercase.
SELECT Lower(FirstName) FROM Charity;
ii) Display all last names of people of Mumbai city in uppercase.
SELECT Upper(LastName) FROM Charity WHERE City like “Mumbai”;
iii) Display Person ID along with First 3 characters of his/her name.
SELECT P_ID, LEFT(FirstName,3) FROM Charity;
iv) Display first name concatenated with last name for all the employees.
SELECT Concat(FirstName,” “,LastName) FROM Charity;
v) Display length of address along with Person ID.
SELECT P_ID, Length(Address) FROM Charity;
vi) Display last 2 characters of City and Person ID.
SELECT P_ID, Right(City,2) FROM Charity;
vii) Display Last Names and First names of people who have "at" in the second or
third position in their first names.
SELECT FirstName, LastName FROM Charity
Chapter 1:Quering and SQL Functions 34 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

WHERE INSTR(FirstName,‟at‟) IN (2,3);


viii) Display the position of „a‟ in Last name in every row.
SELECT INSTR(LastName,‟a‟) FROM Charity ;
ix) Display Last Name and First name of people who have "a" as the last character
in their First names.
SELECT LastName,FirstName FROM Charity
WHERE FirstName LIKE “%a”;
x) Display the first name and last name concatenated after removing the leading
and trailing blanks.
SELECT Concat(TRIM(FirstName),TRIM(LastName)) FROM Charity;
xi) Display Person Id, last names and contribution rounded to the nearest rupee of
all the persons.
SELECT P_ID, LastName, ROUND(Contribution,-3) FROM Charity;
xii) Display Person Id, last name and contribution with decimal digits truncated of
all the persons.
SELECT P_ID, LastName, TRUNCATE(Contribution,0) FROM Charity;
xiii) Display Last name, contribution and a third column which hascontribution
divided by 10. Round it to two decimal points.
SELECT P_ID, LastName, Contribution,
ROUND((Contribution/10),2) FROM Charity;

2. Consider the table "Grocer" and write SQL queries for the tasks that follow:
Table: Grocer

i)
Display Item name, unit price along with Date of purchase for all the
Items.
ii) Display Item name along with Month (in number) when it was purchased
for all the items.
iii) Display Item name along with year in which it was purchased for all the
items.
iv) Display Item Id, Date of Purchase and day name of week (e.g. Monday) on
which it was purchased for all the items.
v) Display names of all the items that were purchased on Mondays or
Tuesdays.
vi) Display the day name of the week on which Rice was purchased.
vii) Display the Item name and unit price truncated to integer value (no
decimal digits)of all the items.
viii) Display current date
Ans. SQL command to creating table “Grocer”-

CREATE TABLE Grocer


(
Chapter 1:Quering and SQL Functions 35 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Item_ID integer PRIMARY KEY,


ItemName varchar(20),
UnitPrice decimal(10,2),
Quantity integer,
Date_Purchase date
);
SQL command to Inserting data to the table “Grocer”-

INSERT INTO Grocer VALUES(1,‟Rice‟,52.50,80,‟2010-02-01‟);


INSERT INTO Grocer VALUES(2,‟Wheat‟,25.40,50,‟2010-03-09‟);
INSERT INTO Grocer VALUES(3,‟Corn‟,50.80,100,‟2010-03-11‟);
INSERT INTO Grocer VALUES
(4,‟Semolina‟,28.90,50,‟2010-01-15‟);

i) Display Item name, unit price along with Date of purchase for all the Items.
SELECT ItemName, UnitPrice, Date_Purchase FROM Grocer;
ii) Display Item name along with Month (in number) when it was purchased for all
the items.
SELECT ItemName, Month(Date_Purchase) FROM Grocer;
iii) Display Item name along with year in which it was purchased for all the items.
SELECT ItemName, YEAR(Date_Purchase) FROM Grocer;
iv) Display Item Id, Date of Purchase and day name of week (e.g. Monday) on which
it was purchased for all the items.
SELECT ItemName, Date_Purchase, Dayname(Date_Purchase) FROM Grocer;
v) Display names of all the items that were purchased on Mondays or Tuesdays.
SELECT * FROM Grocer
WHERE Dayname(Date_Purchase) IN („Monday‟,‟Tuesday‟);
vi) Display the day name of the week on which Rice was purchased.
SELECT ItemName, dayname(Date_Purchase) FROM Grocer
WHERE ItemName like „Rice‟;

vii) Display the Item name and unit price truncated to integer value (no decimal
digits) of all the items.
SELECT ItemName, Truncate(UnitPrice) FROM Grocer;

Chapter 1:Quering and SQL Functions 36 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

LAB EXERCISE (Try Your-Self)

Consider a database LOANS with the following table:

Write SQL commands for the tasks 1 to 35 and write the output for the SQL
commands 36to 40:

Create Database and use it


1. Create the database LOANS.
2. Use the database LOANS.

Create Table / Insert Into


3. Create the table Loan_Accounts and insert tuples in it.

Simple Select
4. Display the details of all the loans.
5. Display the AccNo, Cust_Name, and Loan_Amount of all the loans.

Conditional Select using Where Clause


6. Display the details of all the loans with less than 40 instalments.
7. Display the AccNo and Loan_Amount of all the loans started before 01-04-2009.
8. Display the Int_Rate of all the loans started after 01-04-2009.

Using NULL
9. Display the details of all the loans whose rate of interest is NULL.
10. Display the details of all the loans whose rate of interest is not NULL.

Using DISTINCT Clause


11. Display the amounts of various loans from the table Loan_Accounts. A
loanamountshould appear only once.
12. Display the number of instalments of various loans from the table
Loan_Accounts. Aninstalment should appear only once.
Chapter 1:Quering and SQL Functions 37 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

Using Logical Operators (NOT, AND, OR)


13. Display the details of all the loans started after 31-12-2008 for which the number
ofinstalments are more than 36.
14. Display the Cust_Name and Loan_Amount for all the loans which do not have
numberof instalments 36.
15. Display the Cust_Name and Loan_Amount for all the loans for which the loan
amountis less than 500000 or int_rate is more than 12.
16. Display the details of all the loans which started in the year 2009.
17. Display the details of all the loans whose Loan_Amount is in the range 400000
to500000.
18. Display the details of all the loans whose rate of interest is in the range 11% to
12%.

Using IN Operator
19. Display the Cust_Name and Loan_Amount for all the loans for which the number
ofinstalments are 24, 36, or 48. (Using IN operator)
Using BETWEEN Operator
20. Display the details of all the loans whose Loan_Amount is in the range 400000
to500000. (Using BETWEEN operator)
21. Display the details of all the loans whose rate of interest is in the range 11% to
12%.(Using BETWEEN operator)

Using LIKE Operator


22. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which
theCust_Name ends with 'Sharma'.
23. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which
theCust_Name ends with 'a'.
24. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which
theCust_Name contains 'a'
25. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which
theCust_Name does not contain 'P'.26. Display the AccNo, Cust_Name, and
Loan_Amount for all the loans for which theCust_Name contains 'a' as the
second last character.

Using ORDER BY clause


27. Display the details of all the loans in the ascending order of their Loan_Amount.
28. Display the details of all the loans in the descending order of their Start_Date.
29. Display the details of all the loans in the ascending order of their Loan_Amount
andwithin Loan_Amount in the descending order of their Start_Date.

Using UPDATE, DELETE, ALTER TABLE


30. Put the interest rate 11.50% for all the loans for which interest rate is NULL.
Chapter 1:Quering and SQL Functions 38 | P a g e
Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4
Class Notes :2024-25

31. Increase the interest rate by 0.5% for all the loans for which the loan amount is
morethan 400000.
32. For each loan replace Interest with (Loan_Amount*Int_Rate*Instalments)
12*100.
33. Delete the records of all the loans whose start date is before 2007.
34. Delete the records of all the loans of 'K.P. Jain'
35. Add another column Category of type CHAR(1) in the Loan table.

Find the Output of the following queries


36. SELECT cust_name, LENGTH(Cust_Name), LCASE(Cust_Name),
UCASE(Cust_Name)FROM Loan_Accounts WHERE Int_Rate< 11.00;
37. SELECT LEFT(Cust_Name, 3), Right(Cust_Name, 3),
SUBSTR(Cust_Name, 1, 3) FROM Loan_Accounts WHERE Int_Rate>
10.00;
38. SELECT RIGHT(Cust_Name, 3), SUBSTR(Cust_Name, 5) FROM
Loan_Accounts;
39. SELECTDAYNAME(Start_Date) FROM Loan_Accounts;
40. SELECT ROUND(Int_Rate*110/100, 2) FROM Loan_AccountWHERE
Int_Rate> 10;

Write the output produced by the following SQL commands:


41. SELECT POW(4,3), POW(3,4);
42. SELECT ROUND(543.5694,2), ROUND(543.5694), ROUND(543.5694,-1);
43. SELECT TRUNCATE(543.5694,2), TRUNCATE(543.5694,-1);
44. SELECT LENGTH("Prof. M. L. Sharma");
45. SELECT CONCAT("SHEIKH", " HAROON") "FULL NAME";
46. SELECT YEAR(CURDATE()), MONTH(CURDATE()), DAY(CURDATE());
47. SELECT DAYOFYEAR(CURDATE()),
DAYOFMONTH(CURDATE()),DAYNAME(CURDATE());
48. SELECT LEFT("Unicode",3), RIGHT("Unicode",4);
49. SELECT INSTR("UNICODE","CO"), INSTR("UNICODE","CD");
50. SELECT MID("Informatics",3,4), SUBSTR("Practices",3);

Chapter 1:Quering and SQL Functions 39 | P a g e


Pr ep ar ed b y : T ap o sh Kar mak ar AIR F OR CE S CH OO L J O RHA T | Mob il e : 70 0 20 70 31 3
Lat e st Up d a te on : 1 6 Ju l y 20 2 4

You might also like