100% found this document useful (1 vote)
1K views75 pages

Unit - 2: Database Query Using SQL

The document discusses various SQL functions used for mathematical operations, string manipulation, and aggregation. It provides examples of functions like POW(), ROUND(), MOD(), ABS(), CEIL(), FLOOR(), TRUNCATE(), CONCAT(), LENGTH(), UPPER(), LOWER(), LEFT(), RIGHT(), COUNT(), SUM(), AVG(), MIN(), MAX() with sample queries. It also explains concepts like GROUP BY, HAVING, ORDER BY, UNION and differences between WHERE and HAVING clauses.

Uploaded by

Anooj Shete
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
100% found this document useful (1 vote)
1K views75 pages

Unit - 2: Database Query Using SQL

The document discusses various SQL functions used for mathematical operations, string manipulation, and aggregation. It provides examples of functions like POW(), ROUND(), MOD(), ABS(), CEIL(), FLOOR(), TRUNCATE(), CONCAT(), LENGTH(), UPPER(), LOWER(), LEFT(), RIGHT(), COUNT(), SUM(), AVG(), MIN(), MAX() with sample queries. It also explains concepts like GROUP BY, HAVING, ORDER BY, UNION and differences between WHERE and HAVING clauses.

Uploaded by

Anooj Shete
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/ 75

Unit -2

Database Query using SQL


Mathematical functions
• MySQL POW() or POWER ( ) function
• MySQL POW() returns the value of a number raised to the
power of another number.

Syntax : POW(M,N )

Example : SELECT POW ( 3 , 2) ;


• Output : 9

Example : SELECT POW (4 , - 2) ;


• Output : 0.0625
ROUND() function
• MySQL ROUND() rounds a number up to a specific
decimal places.
Syntax : ROUND(N,[D])

• Example : SELECT ROUND(4.43) ;


Output : 4

• Example : SELECT ROUND(- 4.53) ;


Output : - 5

• Example : SELECT ROUND(- 4.535,2) ;


Output : - 4.54
MOD() function
★ MySQL MOD() returns the remainder of a number
divided by another number. This function also works on
fractional values and returns the exact remainder.

★ The function returns NULL when the value of divisor is


0.

Syntax : MOD(N,M), N % M, N MOD M;


• Example : SELECT MOD (17,5) ;
Output : 2

• Example : SELECT MOD (17 MOD 5) ;


Output : 2
ABS() function
• MySQL ABS() returns the absolute value of a number.
• Syntax : ABS(N)

Example : SELECT ABS(5);


• Output : 5

Example : SELECT ABS(-5);


• Output : 5
CEIL() function
• MySQL CEIL() returns the smallest integer value not less
than the number specified as an argument.
Syntax : CEIL(N)

• Example : SELECT CEIL(2.2536);


Output : 3

• Example : SELECT CEIL(-2.2536);


Output : -2
DIV() / DIVISION() Operator
• MySQL div operator is used for integer
division.
Syntax : expression DIV num

• Example : SELECT 12 DIV 3;


Output : 4
FLOOR() function
• MySQL FLOOR() returns the largest integer value not
greater than the specified number.
Syntax : FLOOR ( N )
• Example : SELECT FLOOR (1.72) ;
Output : 1
• The above statement shows the return value 1 is smallest
the specified number 1.72.
• Example : SELECT FLOOR (-2.72) ;
• Output : -3
• The above statement shows the return value -3 is
smallest the specified number -2.72.
SING() function
• MySQL SIGN() returns the sign of a specific number.
Return 1 when the value of the argument is positive,
returns -1 when the value of the argument is negative and
return 0 when the value of the argument is 0.
Syntax : SIGN(X)
• Example : SELECT SIGN(-145), SIGN(0), SIGN(145);
• Output :
• SIGN(-145) SIGN(0) SIGN(145)
-------------------------------------------------------
-1 0 1
SQRT() function
• MySQL SQRT() returns the square root of a non-negative
number of the argument.
Syntax : SQRT(X)

• Example : SELECT SQRT(25);


Output : 5

• Example : SELECT SQRT(-25);


Output : NULL
TRUNCATE() function
• MySQL TRUNCATE() returns a number after
truncated to a certain decimal places.
Syntax : TRUNCATE(N , D)

• Example : SELECT TRUNCATE(2.465,1);


Output : 2.4

• Example : SELECT TRUNCATE(142.465,-2);


Output : 100
Text Functions
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.
Example:
SELECT INSTR(“school", “ol");
Output is: 5
Mid () function
• Extract a substring from a string (start at
position 5, extract 3 characters):

Example:
SELECT MID(“school", 5, 2) ;
Output is:
ol
Substr() / substring() function
• Substring function is used to extract a
string containing a specific number of
characters from a particular position of a
given string.

Example :
SELECT substring(‘Informatics' ,4 ,5);
Output : ormat
ltrim() function
• ltrim function is used to remove spaces or
set of characters which are matching with
the trimming_text, from the start of a string
means from left side.

Example1 : SELECT ltrim(‘ test’);


Output : test
rtrim() function
• rtrim function is used to remove spaces or
set of characters which are matching with
the trimming_text, from the end of a string
means from right hand side.

• Example : SELECT rtrim('test ');


Output : test
trim() function
Trim function is used to remove spaces or set of
characters from the leading or trailing or both side from a
string.

Example :
SELECT trim(‘ resource ');
Output : resource
upper() function
upper function is used to convert a
string from lower case to upper
case.

• Example : SELECT upper(‘mysql');


Output : MYSQL
Lower() function

lower function is used to convert a string


from upper case to lower case.

Example :
SELECT lower(‘ABC') AS "Upper to
Lower" ;
Output : abc
chr() function
• chr function is used to return the
corresponding character against the given
code within the argument.

Example :
SELECT chr(90) ;
Output : Z
concat() function
• concat function is used to concatenate
all arguments except NULL, it will be
ignored.

Example:
SELECT concat(‘python', ‘mysql');
Output : pythonmysql
length() function
length function is used to find the
length of a string i.e. number of
characters in the given string.

Example :
SELECT length('resource');
• Output : 8
reverse() function
Reverse function is used to arrange a
string in reverse order.

Example : SELECT reverse(‘abc');


Output : cba
right() function
Right function is used to extract n number
of characters specified in the argument from
the right of a given string. When the value
of n is negative, the extraction will be the
first n characters.

Example : SELECT right('w3resource',5);


Output : ource
left() function
left function is used to extract n number of
characters specified in the argument from
the left of a given string. When the value of
n is negative, the extraction will be the last
n characters.

Example :
SELECT left('w3resource',3);
Output : w3r
initcap() function
initcap function is used to convert the first letter of
each word to uppercase and the remaining to
lower case.

Example : SELECT initcap('RABINDRANATH


TAGORE')
AS "First Character OR each word Capital";

Output : Rabindranath Tagore


Aggregate / group functions
• A single row function works on a single value.
SQL also provides us multiple row functions. A
multiple row function works on multiple values.
These functions are called aggregate functions or
group functions. These functions are:
• Count ( )
• Sum ( )
• Avg ( )
• Min ()
• Max ()
Sample data stored in these tables is
given below:
Count( ) function
counts the number of rows in a set
HOW MANY ROWS ARE THERE WHOSE
SALARY IS LESS THAN 4000 ?
• SELECT COUNT(Salary) FROM Teacher WHERE Salary
> 40000;

• Can use count(rno) instead of count(*)


Sum () function
finds the sum total of a numeric attribute

WHAT IS THE SUM OF SALARY OF


TEACHERS?

• SELECT SUM(Salary) AS Total_Salary FROM Teacher;


Output is:
Avg ( ) function
find the Average value of a numeric
attribute in a set.

WHAT IS THE AVERAGE OF COST?


• SELECT AVG(cost) FROM shoes;
Min( ) function
Finds a minimum value of a string or numeric attribute
in a set

WHAT IS THE MINIMUM SALARY OF TEACHER?


• SELECT MIN(Salary) AS Min_Salary FROM Teacher;
Output is:
Max( ) function
Finds a maximum value of a string or
numeric attribute in a set
WHAT IS THE MAXIMUM SALARY OF TEACHERS ?

• SELECT MAX(Salary) AS Max_Salary FROM Teacher;

• Output is:
Group by clause
• GROUP BY Clause is used to collect data from multiple
records and group the result by one or more column. It is
generally used in a SELECT statement. You can also use
some aggregate functions like COUNT, SUM, MIN, MAX,
AVG etc. on the grouped column.
• Example:
• SELECT type, SUM(qty) FROM shoes GROUP BY
type;
Having clause
• It permits conditional aggregation of data into groups.
SELECT type, SUM(qty) FROM shoes
GROUP BY type HAVING SUM(qty) > 1500;
Difference between where and having clause
Where clause Having clause
1) It can be used without the 1) It cannot be used without
Group By clause the Group by clause
2) Where clause selects 2) It selects rows after
rows before grouping grouping
3) It cannot contain 3) It contain aggregate
aggregated functions functions
4) It is used to impose 4) It is used to impose
condition on select condition on group function
statement as well as single and is used after group by
row function and is used clause in the query.
before group by clause.
Difference between having and group by
clause
• Having is used as a conditional Clause with
GROUP BY Clause. This conditional
clause returns rows where aggregate
function results matched with given
conditions only HAVING is used to exclude
records after grouping.
• Group by is used to organize similar data into
groups. It combines the multiple records in
single or more columns using some
functions.
Order by clause
• The ORDER BY keyword is used to sort the result-set in
ascending or descending order.
• The ORDER BY keyword sorts the records in ascending order by
default. To sort the records in descending order, use the DESC
keyword.
Example:1
The following SQL statement selects all customers from the
"Customers" table, sorted by the "Country" column in ascending
and then descending order:
Example
mysql> SELECT * FROM Customers ORDER BY Country;
mysql> SELECT * FROM Customers ORDER BY Country DESC;
Example 2
• Sorting data on multiple columns
• Display roll , name and marks of all student
in descending order of their marks and
ascending order of their names.
mysql> select roll,name,marks from student
Order by markd desc ,name;
Operations on Relations
• Union
• Intersection
• Minus
• Cartesian Product
• JOIN
Union
The UNION operator is used to combine the result-set of
two or more SELECT statements.
• Each SELECT statement within UNION must have the
same number of columns
• The columns must also have similar data types
• The columns in each SELECT statement must also be in
the same order

• The syntax of UNION in its simplest form is:


• SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
• The UNION operator selects only distinct values by
default. To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
• Example:

• The following SQL statement returns the cities (only


distinct values) from both the "Customers" and the
"Suppliers" table:
Example
• SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
• Union does not display any duplicate rows unless ALL is
specified with it.
• Example: 1
Suppose a company deals in two different categories of
items. Each category contains a number of items and for
each category there are different customers. In the database
there are two customer tables: Customer_Cat_1 and
Customer_Cat_2. If it is required to
produce a combined list of all the customers, then it can be
done as follows:

SELECT Cust_Code from Customer_Cat_1


UNION
SELECT Cust_Code from Customer_Cat_2;
Example 2
• If a customer exists with same customer code
in both the tables, its code will be displayed
only once - because Union does display
duplicate rows. If we explicitly want the
duplicate rows, then we can enter the
statement:
SELECT Cust_Code from Customer_Cat_1
UNION ALL
SELECT Cust_Code from Customer_Cat_2;
Sample Data
Intersection
• The SQL INTERSECT clause/operator is used to combine
two SELECT statements, but returns rows only from the first
SELECT statement that are identical to a row in the second
SELECT statement. This means INTERSECT returns only
common rows returned by the two SELECT statements.
Example:
• SELECT supplier_id FROM suppliers
INTERSECT SELECT supplier_id FROM
order_table;

• In this SQL INTERSECT example, if


a supplier_id appeared in both
the suppliers and order_table, it would
appear in your result set.
Minus
• The SQL MINUS operator is used to return all rows in the
first SELECT statement that are not returned by the
second SELECT statement. Each SELECT statement will
define a dataset. The MINUS operator will retrieve all
records from the first dataset and then remove from the
results all records from the second dataset.
Example
• SELECT supplier_id FROM suppliers
MINUS SELECT supplier_id FROM
order_table;

• This SQL MINUS example returns all


supplier_id values that are in the suppliers
table and not in the orders table. What this
means is that if a supplier_id value existed
in the suppliers table and also existed in
the orders table, the supplier_id value
would not appear in this result set.
Cartesian Product or Cross Join of
tables :
• 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:
Example
• The number of columns in the Cartesian product is the
sum of the number of columns in both the tables. In SQL,
Cartesian product of two rows is obtained by giving the
names of both tables in FROM clause. An example of
Cartesian product is shown below:

SELECT * FROM order_table, product;


• To give the output of this query, MySQL will pair the rows
of the mentioned tables as follows:
• Here we observe that the Cartesian product contains all the
columns from both tables.
• Each row of the first table (Order_table) is paired with each
row of the second table (Product).
• If we change the sequence of table names in the FROM
clause, the result will remain the same but the sequence of
rows and columns will change. This can be observed in the
following statement and the corresponding output.
• SELECT * FROM product, order_table;
What is JOIN in MySQL?
★ A join enable you to retrieve records from two (or more)
logically related tables in a single result set.
★ JOIN clauses are used to return the rows of two or more
queries using two or more tables that shares a meaningful
relationship based on a common set of values.
★ These values are usually the same of column name and
datatype.
★ These columns, or possibly a single column from each
table, are called the join key or common key.
★ Mostly the join key is the primary key of one table and a
foreign key in another table.
★ The join can be performed as long as the data in the
columns are matching.
Types of join
• (INNER) JOIN: Returns records that have matching
values in both tables
• LEFT (OUTER) JOIN: Returns all records from the
left table, and the matched records from the right
table
• RIGHT (OUTER) JOIN: Returns all records from the
right table, and the matched records from the left
table
• FULL (OUTER) JOIN: Returns all records when
there is a match in either left or right table
• Types of Joins
Example : consider customer and order
table for join concept .
Customer table

customer_id first_name last_name


1 George Washington
2 John Adams
3 Thomas Jefferson
4 James Madison
5 James Monroe
Order table
order_id order_date amount customer_id
1 07/04/1776 234.56 1
2 03/14/1760 78.50 3
3 05/23/1784 124.00 2
4 09/03/1790 65.50 3
5 07/21/1795 25.50 10
6 11/27/1787 14.40 9
INNER JOIN
★ The INNER JOIN is such a JOIN in which all
rows can be selected from both participating
tables as long as there is a match between the
columns.

★ INNER JOIN combines the tables.

★ An INNER JOIN allows rows from either table


to appear in the result if and only if both tables
meet the conditions specified in the ON clause.
Example of Inner join
• select first_name, last_name, order_date, order_amount
from customers c
inner join orders o
on c.customer_id = o.customer_id
Output is:
first_name last_name order_date order_amount
George Washington 07/4/1776 234.56
John Adams 05/23/1784 124.00
Thomas Jefferson 03/14/1760 78.50
Thomas Jefferson 09/03/1790 65.50
LEFT JOIN
★ The LEFT JOIN fetches all records from
the table on the left side of the join
statement.

★ If a record from the left table has no


matching record in the table on the right
side of the join, then the corresponding
column from the right table returns a NULL
value.
Example
• select first_name, last_name, order_date, order_amount
from customers c
left join orders o
on c.customer_id = o.customer_id
• Output is:
first_name last_name order_date order_amount
George Washington 07/04/1776 234.56
John Adams 05/23/1784 124.00
Thomas Jefferson 03/14/1760 78.50
Thomas Jefferson 09/03/1790 65.50
James Madison NULL NULL
James Monroe NULL NULL
RIGHT JOIN
★ The RIGHT JOIN fetched all
records from the table on the right side
of the join statement, even if the table
on the left has no matching record.

★ The columns for unmatched rows


from the left table return NULL values.
Example:
• select first_name, last_name, order_date, order_amount
from customers c
right join orders o
on c.customer_id = o.customer_id
Output is:

first_name last_name order_date order_amount


George Washington 07/04/1776 234.56
Thomas Jefferson 03/14/1760 78.50
John Adams 05/23/1784 124.00
Thomas Jefferson 09/03/1790 65.50
NULL NULL 07/21/1795 25.50
NULL NULL 11/27/1787 14.40
CROSS JOIN
★ A CROSS JOIN is the complete cross product of two
tables.

★ For each record in the first table, all the records in the
second table are joined.

★ Creating a potentially huge result set.

★ This command has the same effect as leaving off the


join condition.

★ This result set is also known as a Cartesian product.


NATURAL JOIN
★ A NATURAL JOIN is such a join that
performs the same task as an INNER or
LEFT JOIN, in which the ON or USING
clause refers to all columns that the tables
to be joined have in common.

You might also like