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

XII-IP-UNIT-II-Database Query Using SQL

The document discusses MySQL functions for querying and manipulating data in databases. MySQL is an open-source database management system that supports web applications by allowing data to be stored and exchanged over the web. MySQL uses functions like POW(), ROUND(), MOD(), and string functions like UPPER(), LOWER(), LEFT(), RIGHT() to perform operations on data like mathematical calculations, extracting substrings, and case conversions.

Uploaded by

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

XII-IP-UNIT-II-Database Query Using SQL

The document discusses MySQL functions for querying and manipulating data in databases. MySQL is an open-source database management system that supports web applications by allowing data to be stored and exchanged over the web. MySQL uses functions like POW(), ROUND(), MOD(), and string functions like UPPER(), LOWER(), LEFT(), RIGHT() to perform operations on data like mathematical calculations, extracting substrings, and case conversions.

Uploaded by

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

Database Query using SQL

Class-12-IP (TERM-II)
MySQL server is a open-source relational database management
system which is a major support for web based applications. Databases
and related tables are the main component of many websites and
applications as the data is stored and exchanged over the web.
MySQL server is used for data operations like querying, sorting, filtering,
grouping, modifying and joining the tables.
Advantages of MySQL :
Fast and high Performance database.
Easy to use, maintain and administer.
Easily available and maintain integrity of database.
Provides scalability, usability and reliability.
Low cost hardware.
MySQL can read simple and complex queries and write operations.
InnoDB is default and widely used storage engine.
Provides strong indexing support.
Provides SSL support for secured connections.
Provides powerful data encryption and accuracy.
Provides Cross-platform compatibility.
Provides minimized code repetition.
FUNCTION-Functions are simply pieces of code that perform
some operations and then return a result. Some functions
accept parameters while other functions do not accept
parameters.

MySQL Math Functions are the MySQL built-in functions which refer the
numeric type functions and commands to operate the mathematical
logics. The Math functions in MySQL are the numeric functions used in
the SQL query commands mainly for the mathematical calculations and
produce the numeric literals as results. These Math Functions perform
numeric handling but if receives an error event during query
implementation then, it returns the NULL value as output.
POW() Function
This POW() function provides the value of one argument passed that is
raised to the power of other argument with numeric values specified
while executing in the server.
Code:
SELECT POW(2,5);
Output:
32
27. POWER() Function
Suppose, this POWER() is passed with two arguments Expr1 and Expr2
then, on implementation it outputs the value of Expr1 which is raised to
the power of Expr2 argument.
Code:
SELECT POWER(3,4);
Output:
81
places is provided for round off, it rounds off the number to the nearest
integer. ... If it is negative, then the number is rounded to the left side of
the decimal point.

SELECT ROUND(135.375, 2);


o/p-
135.38

SELECT ROUND(345.156, 0);


o/p-
345
SELECT ROUND(20.5);
o/p –
21

SELECT ROUND(20.5, 0);


o/p –
21

The number of decimal places ( d) can be positive or negative. If it is negative,


then the d digits left of the decimal point of the number n becomes zero.
SELECT ROUND(121.55,-2)
o/p –
100
It means the value of the fractional part of .5 or greater is rounded up to the next
integer if positive or rounded down to the next integer if negative.

SELECT ROUND(10.5);
o/p –
11
SELECT ROUND(10.6);
o/p –
11
SELECT ROUND(-10.5);
o/p—
-11
SELECT ROUND(-10.6);
o/p—
-11
The value of the fractional part less than .5 is rounded down to the next
integer if positive or up to the next integer if negative.
SELECT ROUND(10.4); --
o/p
10
SELECT ROUND(-10.4);
o/p—
-10
mysql> SELECT ROUND(125.315); SELECT ROUND(454.1234,-2);
Result: 125
Result: 500
mysql> SELECT ROUND(125.315, 0);
Result: 125 SELECT ROUND(444.1234,-2);
Result: 400
mysql> SELECT ROUND(125.315, 1);
Result: 125.3

mysql> SELECT ROUND(125.315, 2);


Result: 125.32

mysql> SELECT ROUND(125.315, -1);


Result: 130

mysql> SELECT ROUND(125.315, -2);


Result: 100

mysql> SELECT ROUND(-125.315);


Result: -125
The MOD() function in MySQL is used to find the remainder of one number
divided by another. The MOD() function returns the remainder of dividend
divided by divisor. if the divisor is zero, it returns NULL.
Syntax-
SELECT MOD( 13,0 );
MOD(x, y) SELECT MOD('555229', '25');
Result: NULL
Or Result: 4
x MOD y You can also pass parameters to
If you pass 0 as the value for the
Or this function as string values parameter Y this function
x%y returns NULL
SELECT MOD(0, 5);
SELECT MOD(18, 4);
Result: 0
Result- 2
If you pass 0 as the value for
SELECT 18 MOD 4;
Result- 2 the parameter X this
function returns 0 always
What are text functions in MySQL?
A string function is a function that takes a string value as an input
regardless of the data type of the returned value.

UCASE() / UPPER Function


The MySQL UCASE function converts all characters in the specified string
to uppercase. If there are characters in the string that are not letters, they are
unaffected by this function.
Returns a Variant (String) containing the specified string, converted to uppercase. The
required string argument is any valid string expression. If string contains Null, Null is
returned.

SELECT UCASE("SQL Tutorial is FUN!");


o/p
SQL TUTORIAL IS FUN!
Syntax-
UCASE(string)
Or
UPPER(string)
LOWER/LCASE Function-
The MySQL LCASE function converts all characters in the specified string to
lowercase. If there are characters in the string that are not letters, they are
unaffected by this function. The LCASE function is a synonym for the LOWER
function.
SELECT LCASE("SQL Tutorial is FUN!");
o/p
sql tutorial is fun!
Syntax-
LCASE(string)
Or
LOWER(string)
MID() : This function in MySQL is used to extract a substring from a given
input string. If the starting position is a positive number, then the substring of
the given length will be extracted from the starting index. If negative, then the
substring of the given length will be extracted from the ending index.
Syntax-
MID(string, start, length)
Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or negative
number. If it is a positive number, this function extracts from the
beginning of the string. If it is a negative number, this function extracts
from the end of the string
length Required. The number of characters to extract
SUBSTRING() function in MySQL
It extracts a string with a specified length, starting from a given location in an
input string. The purpose of substring is to return a specific portion of the string.
Syntax : SUBSTRING(string, start, length) OR SUBSTRING(string FROM start
FOR length)

Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or
negative number. If it is a positive number, this function
extracts from the beginning of the string. If it is a negative
number, this function extracts from the end of the string
length Optional. The number of characters to extract. If omitted, the
whole string will be returned (from the start position)
The SUBSTR() and MID
() functions equals to
the SUBSTRING()
function.
SUBSTR() function
MySQL SUBSTR() returns the specified number of characters from a particular
position of a given string. SUBSTR() is a synonym for SUBSTRING().

Syntax-
SUBSTR(string, start, length)
Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or negative number.
If it is a positive number, this function extracts from the beginning of
the string. If it is a negative number, this function extracts from the end
of the string
length Optional. The number of characters to extract. If omitted, the whole
string will be returned (from the start position)
LENGTH() Function in MySQL
This function in MySQL is used to find the string length which is of type bytes.
Features :
This function is used to find the string length which is of type bytes.
This function comes under String Functions.
This function accepts only one parameter namely string.
This function returns the length in bytes only.
Syntax-
LENGTH(string)

Returns :
It returns the string length which is of type bytes.

LENGTH( str ) Returns the length of the string str , measured in bytes. A multibyte character
counts as multiple bytes. This means that for a string containing five 2-byte characters,
LENGTH() returns 10 , whereas CHAR_LENGTH() returns 5 .
mysql> SELECT LENGTH('text');
o/p-> 4
mysql> SELECT LENGTH(NULL);
Result: NULL
mysql> SELECT LENGTH('');
Result: 0
mysql> SELECT LENGTH(' ');
Result: 1
mysql> SELECT LENGTH('Tech on the Net');
Result: 15
mysql> SELECT LENGTH('techonthenet.com');
Result: 16
The LEFT() function extracts a number of characters from a string (starting
from left).
Syntax-
LEFT(string, number_of_chars)

Parameter Description
string Required. The string to extract from
number_of_chars Required. The number of characters to extract. If this parameter
is larger than the number of characters in string, this function will
return string
RIGHT() function in MySQL is used to extract a specified number of characters
from the right side of a given string. Second argument is used to decide, how
many characters it should return. Syntax : RIGHT( str, len )

Parameter Description
string Required. The string to extract from
len Required. The number of characters to extract. If this parameter
is larger than the number of characters in string, this function will
return string
MySQL INSTR() Function
The INSTR() function returns the position of the first occurrence of a string
in another string. This function performs a case-insensitive search.
Syntax-
INSTR(string_1, string_2)
This function accepts 2 parameters.
string_1 –
The string where searching takes place.
string_2 –
The string/sub-string which will be searched in string_1.
Returns :
It returns the position of the first occurrence of a substring within a given
string.
Note –
The function will return 0 if
string_2 is not found in string_1.
INSTR() function only performs
case-insensitive searches.
LTRIM() : This function in MySQL
is used to remove leading
spaces from a string.
Syntax-
LTRIM(string)
RTRIM() : This function in MySQL
is used to remove trailing spaces
from a string.
Syntax-
RTRIM(string)
TRIM() function in MySQL
is used to clean up data. It is
also used to remove the
unwanted leading and trailing
characters in a string. Syntax :
TRIM([{BOTH | LEADING |
TRAILING} [remstr] FROM] str)
The DATE() function extracts the date part from a datetime expression.
Syntax-
DATE(expression)

Parameter Description
expression Required. A valid date/datetime value. Returns NULL if expression is
not a date or a datetime

SELECT DATE("2017-06-15 09:34:21");


o/p
2017-06-15
•If expression is not a date or a datetime value, the DATE
function will return NULL.

mysql> SELECT DATE('2014-02-14');


Result: '2014-02-14'
mysql> SELECT DATE('2014-02-14 18:20:19');
Result: '2014-02-14'
mysql> SELECT DATE('2014-02-15 06:18:01.000001');
Result: '2014-02-15'
mysql> SELECT DATE('The date is 2014-02-14');
Result: NULL mysql> SELECT DATE(NULL);
Result: NULL
NOW() function in MYSQL
This function in MySQL is used to check the current date and time value. The
return type for NOW() function is either in 'YYYY-MM-DD HH:MM:SS' format or
YYYYMMDDHHMMSS. uuuuuu format, depending on whether the function is
used in a string or numeric context.
Syntax-
Now()
Parameter :
This method does not accept any parameter.
Returns :
It returns the current date and time value.
Finding the current date and time using NOW Function. Here
we will get the result in ‘YYYY-MM-DD HH:MM:SS’ format.
SELECT NOW();
Getting the current date and time using NOW Function in numeric format. Here
the result will be in YYYYMMDDHHMMSS.uuuuuu format.
SELECT NOW()+ 0 ;
MONTH() function in MySQL is used to find a month from the given date. It
returns 0 when the month part for the date is 0 otherwise it returns month
value between 1 and 12.
Syntax-
MONTH(date)
Parameter :
This function accepts one parameter
date : The date or DateTime from which we want to extract the month.
Returns : It returns the value range from 1 to 12.
Finding the Current Month Using
MONTH() Function. Finding the Month from given
SELECT MONTH(NOW()); DateTime Using Month() Function.
SELECT MONTH('2015-09-26 08:09:22');
o/p
9
MONTHNAME() function in MySQL is used to find month name from the
given date. It Returns 0 when MONTH part for the date is 0 or greater than
12 otherwise it returns month name between January to December. Syntax :
MONTHNAME(date)
Syntax-
MONTHNAME(date)
Parameter : This method accepts one parameter as mentioned above
and described below :
•date : The date or datetime from which we want to extract the month
name.
Returns : It returns month name from the given date.
Finding the Month name from given
datetime Using MONTHNAME()
Finding the Current Month name Using
Function.
MONTHNAME() Function.
SELECT MONTHNAME('2015-01-26
SELECT MONTHNAME(NOW());
08:09:22');
o/p-
January
YEAR() function in MySQL is used to find year
from the given date. If the date is NULL, the SELECT YEAR("2022-01-08");
YEAR() function will return NULL. Otherwise, o/p-
it returns value range from 1000 to 9999. 2022
Syntax : YEAR(date)
DAY() Function in MySQL
This function in MySQL is used to return the
day of the month for a specified date (a
number from 1 to 31). This function equals
the DAYOFMONTH() function.
Syntax : DAY(date)
Getting the day of the month from a specified date “2020-11-24”.
SELECT DAY("2020-11-24");
Output :
24
Example-2 :
Getting the day of the month from a specified date “2020-11-22 07:12:23”.
SELECT DAY("2020-11-22 07:12:23");
Output :
22
DAYNAME() function : Getting the weekday name for a specified date.
This function in MySQL is used to “2022-01-08”.
SELECT DAYNAME(" 2022-01-08 ");
return the weekday name for a Output :
specified date. Saturday
Example-2 :
Getting the weekday name from a specified
date “2022-01-08 07:12:23”.
SELECT DAYNAME("2022-01-08 07:12:23");
Output :
Saturday
Example-3 :
Getting the weekday name for the current
system date.
SELECT DAYNAME(CURDATE());
Output :
Saturday
MySQL's aggregate function is used to perform calculations on multiple
values and return the result in a single value like the average of all values, the
sum of all values, and maximum & minimum value among certain groups of
values.
Except for COUNT(*) , aggregate functions ignore null values. Aggregate
functions are often used with the GROUP BY clause of the SELECT statement.
The MySQL MAX() function is used to return the maximum value in a set of
values of an expression. This aggregate function is useful when we need to
find the maximum number, selecting the most expensive product, or getting
the largest payment to the customer from your table.
Syntax-
SELECT MAX(DISTINCT aggregate_expression)
FROM table_name(s)
[WHERE conditions];
to find the maximum income of the employee available in
the table:
1.mysql> SELECT MAX(income) AS "Maximum Income"
FROM employees;
The MIN() function in MySQL is used to return the minimum value in a set of
values from the table. It is an aggregate function that is useful when we need to find
the smallest number, selecting the least expensive product, etc.
Syntax- Parameter Description
MIN(expression)
expression Required. A numeric value (can be a field or a formula)

SELECT MIN(column_name)
FROM table_name
WHERE condition;

to fetch minimum value of daily_typing_pages


MySQL AVG() Function
The AVG() function returns the average value of an expression.
Syntax-
AVG(expression)
expression Required. A numeric value (can be a field or a formula) to calculate average of all the dialy_typing_pages
The MySQL sum() function is used to return the total summed value of an expression.
It returns NULL if the result set does not have any rows. It is one of the kinds of
aggregate functions in MySQL.
Syntax-
SUM(expression)
calculates the total number of working hours of all employees

to calculate the total working hours of employees whose working_hours >= 12.
MySQL count() function is used to returns the count of an expression. It allows us to
count all rows or only some rows of the table that matches a specified condition. It is a
type of aggregate function whose return type is BIGINT.

We can use the count function in three forms, which are explained below:
•Count (*)
•Count (expression)
•Count (distinct)

COUNT(*) Function: This function uses the SELECT statement to returns the count
of rows in a result set. The result set contains all Non-Null, Null, and duplicates
rows.
COUNT(expression) Function: This function returns the result set without containing
Null rows as the result of an expression.

COUNT(distinct expression) Function: This function returns the count of distinct rows
without containing NULL values as the result of the expression.
to calculates the total number of employees name available in the table

specifies the rows whose value in the column emp_age is greater than 32
counts the Non-Null and distinct rows in the column emp_age
SQL commands are mainly categorized into four categories-
DDL – Data Definition Language-[CREATE, DROP, ALTER, TRUNCATE, COMMENT, RENAME]
DQl – Data Query Language- [SELECT]
DML – Data Manipulation Language-[INSERT,UPDATE, DELETE, LOCK, CALL, EXPLAIN PLAN]
DCL – Data Control Language-[GRANT, REVOKE]
The MySQL GROUP BY clause is used in a SELECT statement to collect data
across multiple records and group the results by one or more columns.

1.SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
count repetitive number of cities in the column address
return the emp_name and total working hours of each employee
minimum working hours of the employees form the table "employees"
The MySQL HAVING clause is used in combination with the GROUP BY clause
to restrict the groups of returned rows to only those whose the condition is
TRUE.
Syntax-
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

The 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. If you omit the GROUP BY clause, the HAVING clause behaves like
the WHERE clause.
Syntax-
SELECT select_list
FROM table_name
WHERE search_condition
GROUP BY group_by_expression
HAVING group_condition;

What is difference between HAVING and where clause?


A HAVING clause is like a WHERE clause, but applies only to groups as a whole
(that is, to the rows in the result set representing groups), whereas the WHERE
clause applies to individual rows. A query can contain both a WHERE clause
and a HAVING clause.
to return the emp_name and sum of their working hours.
The MySQL ORDER BY clause is used to sort the query result sets in
either ascending or descending order. ... “[ASC | DESC]” is the keyword
used to sort result sets in either ascending or descending order. Note ASC is
used as the default.
Syntax-

SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
MySQL ORDER BY: without using ASC/DESC attribute
MySQL ORDER BY: with ASC attribute
MySQL ORDER BY: with DESC attribute
MySQL ORDER BY: using both ASC and DESC attributes

You might also like