Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

Lab04-Aggregate Functions, Group By, Numeric and String Functions

This document discusses aggregate functions, grouping, and string and numeric functions in MySQL. It provides examples of common aggregate functions like COUNT, MAX, MIN, SUM, and AVG. It also covers the GROUP BY clause for grouping query results and the HAVING clause for filtering groups. Finally, it lists many common string functions like UPPER, LOWER, LENGTH, and SUBSTR as well as numeric functions like ABS, CEIL, FLOOR, POW, and SQRT.

Uploaded by

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

Lab04-Aggregate Functions, Group By, Numeric and String Functions

This document discusses aggregate functions, grouping, and string and numeric functions in MySQL. It provides examples of common aggregate functions like COUNT, MAX, MIN, SUM, and AVG. It also covers the GROUP BY clause for grouping query results and the HAVING clause for filtering groups. Finally, it lists many common string functions like UPPER, LOWER, LENGTH, and SUBSTR as well as numeric functions like ABS, CEIL, FLOOR, POW, and SQRT.

Uploaded by

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

Indian Institute of Information Technology Sri City

Database Management Systems LAB-04


TOPIC : Aggregate functions, Grouping, String and Numeric functions

AGGREGATE FUNCTIONS: MySQL supports the following aggregate functions.


Aggregate function Description

AVG() Return the average of non-NULL values.

COUNT() Return the number of rows in a group, including rows


with NULL values.

MAX() Return the highest value (maximum) in a set of non-


NULL values.

MIN() Return the lowest value (minimum) in a set of non-


NULL values.

STDEV() Return the population standard deviation.

SUM() Return the summation of all non-NULL values in a set.

VARIANCE() Return the population standard variance.


SELECT VARIANCE(income)
FROM employee;

GROUPING: The GROUP BY clause is a SQL command that is used to group rows that have
the same values.

● The GROUP BY clause is used in the SELECT statement.


● Optionally it is used in conjunction with aggregate functions to produce summary reports
from the database.

ORDER BY CLAUSE:

Use the ORDER BY clause to display the output table of a query in either ascending or
descending alphabetical order. Whereas the GROUP BY clause gathers rows into groups and
sorts the groups into alphabetical order, ORDER BY sorts individual rows.

General syntax for using GROUP Functions:


SELECT <column, ..>, group_function(column)
FROM <table>
WHERE <condition>
[GROUP BY <column>]
[ORDER BY <column>];
Example 1: Maximum salary from employee table
SELECT emp_dept, MAX(income)
FROM employee;

Example 2: All columns in the SELECT list that are not in the group functions must be in the
GROUP BY clause.

Illegal
SELECT emp_dept, job, MAX(income)
FROM employee
GROUP BY emp_dept;

Legal
SELECT emp_dept, job, MAX(income)
FROM employee
GROUP BY emp_dept, job;

HAVING clause: We cannot use the WHERE clause to restrict groups.

Illegal
SELECT emp_dept, MAX(income)
FROM employee
WHERE MAX(income) >2000
GROUP BY emp_dept;

Legal
SELECT emp_dept, MAX(income)
FROM employee
GROUP BY emp_dept
HAVING MAX(income) >2000;

EXERCISES
Exercise 1:
#Create table employee with the following constraints;
CREATE TABLE employee(emp_id, emp_name ,emp_dept emp_age, place,
income); Set emp_id as the primary key with auto increment starting from 2505.

# insert the below given records into the table employee table

Load “employee.csv”(using the mysql workbench, easy) data into the employee table.
Questionnaire set:

1. Calculate the total number of employees name available in the table


2. Display the maximum salary of each department and also all departments put together 3.
Find the employees whose salary is between 100000 and 500000 but not exactly 120000. 4.
Get the count of employees whose income is more than 1 lakh.
5. List the employees according to ascending order of salary
6. For each department, retrieve the department name, the number of employees in the
department, and Maximum income for the department.
7. List the number of employees in each place.
8. List the number of employee in each country sorted high to low
9. List the number of employees in each place. (Only include places with more than 1
employee)
10. List the number of employees in each place, except the California, sorted high to
low. Only include places with 2 or more employees

Exercise2:

Tables for Exercise2

1. Create table customer (customer_name char(20),customer_street char(30),customer_city


char(30),PRIMARY KEY(customer_name));
2. Create table branch (branch_name char(15),branch_city char(30),assets
numeric(16,2),PRIMARY KEY(branch_name));
3. Create table account (account_number char(15),branch_name char (15),balance
numeric(12,2),PRIMARY KEY(account_number),FOREIGN KEY (branch_name)
REFERENCES branch(branch_name));
4. Create table depositor(customer_name char(20),account_number char(10),PRIMARY
KEY(customer_name,account_number),FOREIGN KEY (customer_name)
REFERENCES customer(customer_name),FOREIGN KEY (account_number)
REFERENCES account(account_number));
5. Create table loan(loan_number varchar(6),branch_name char(15),amount int,PRIMARY
KEY(loan_number),FOREIGN KEY (branch_name) REFERENCES
branch(branch_name));
6. Create table borrower(customer_name char(20),loan_number varchar(6),PRIMARY
KEY(customer_name,loan_number),FOREIGN KEY (customer_name) REFERENCES
customer(customer_name),FOREIGN KEY (loan_number) REFERENCES
loan(loan_number));

Questionnaire set:

1. Create the tables for above schema and load data from the respective .csv files 2. For all
customers who have loan from the bank,find their names,loan numbers and loan amount(with
and without renaming tables)
3. Find the customer names,loan numbers and loan amounts for all loans at perryridge
branch.
4. Find the names of all branches that have assets greater than at least one branch located at
Brooklyn.
5. List in alphabetical order all customers who have loans at the perryridge branch. 6. Print
the entire Loan relation in descending order of amount.If several loans have the same
amount,order them in ascending order by loan number.
7. Find the average balance for all accounts.
8. Find no.of tuples in customer relation.
9. Find the total of all loan amounts.
10. Find the average account balance at the Perryridge branch.
11. Find the average account balance at each branch.
12. Find the average account balance at each branch ,where the account balance is more than
1200.
13. Find the number of depositors for each branch.
14. Find the average balance for each customer who lives in ‘’Harrison” and has at least 3
accounts

CREATE TABLE employee(emp_id int, emp_name varchar(20), emp_dept


varchar(20), emp_age int, place varchar(20), income int, doj date);

ALTER TABLE employee auto_increment=2505;

MySQL String functions:


Function Description
ASCII Returns the ASCII value for the specific character
SELECT ASCII('a');

CHAR_LENGTH Returns the length of a string (in characters)


SELECT CHAR_LENGTH('iiitsricity');

CONCAT Adds two or more expressions together


SELECT CONCAT('ram', 'krish');

CONCAT_WS Adds two or more expressions together with a separator


SELECT CONCAT_WS(',', 'Ram','krish');

INSTR Returns the position of the first occurrence of a string in


another string SELECT INSTR('foobarbar', 'bar');

LCASE Converts a string to lower-case


SELECT LCASE(‘JOHN KEVIN’);

LENGTH Returns the length of a string (in bytes)


SELECT LENGTH('iiits dbms course');

MySQL Numeric functions:


Function Description

ABS Returns the absolute value of a number

AVG Returns the average value of an expression

CEIL Returns the smallest integer value that is >= to a number

COUNT Returns the number of records returned by a select query

DEGREES Converts a value in radians to degrees

DIV Used for integer division


EXP Returns e raised to the power of a specified number

FLOOR Returns the largest integer value that is <= to a number

GREATEST Returns the greatest value of the list of arguments

LEAST Returns the smallest value of the list of arguments

LN Returns the natural logarithm of a number

LOG Returns the natural logarithm of a number, or the logarithm


of a number to a specified base

LOG10 Returns the natural logarithm of a number to base 10

LOG2 Returns the natural logarithm of a number to base 2

MAX Returns the maximum value in a set of values

MIN Returns the minimum value in a set of values

MOD Returns the remainder of a number divided by another

PI number Returns the value of PI

POW Returns the value of a number raised to the power of another

RADIANS number Converts a degree value into radians

RAND Returns a random number

ROUND Rounds a number to a specified number of decimal

SIGN places Returns the sign of a number

SQRT Returns the square root of a number

SUM Calculates the sum of a set of values

TRUNCATE Truncates a number to the specified number of decimal places

MySQL String functions:


UPPER (string/ COLUMNNAME): Returns string with all characters in upper case.

LOWER (string/ COLUMNNAME): Returns string with all characters in lower case.

INITCAP (string/ COLUMNNAME): Returns string with first letter of the word capitalized.

LENGTH (string/ COLUMNNAME): Returns the length of the string measured in characters.

REVERSE (str): Returns the string str with the order of the characters reversed.

INSTR (str,substr): Returns the position of the first occurrence of substring substr in string

str. SUBSTR (str,pos): It returns a substring from string str starting at position pos.

SUBSTR (str,pos,len): It returns substring len characters long from string str, starting at position pos.

REPLACE(str,from_str,to_str): Returns the string str with all occurrences of the string from_str
replaced by the string to_str. REPLACE performs a case-sensitive match when searching for from_str.
LPAD (str,len,padstr): Returns the string str, left-padded with the string padstr to a length of len
characters. If str is longer than len, the return value is shortened to len characters.

RPAD (str,len,padstr): Returns the string str, right-padded with the string padstr to a length of len
characters. Ifstr is longer thanlen, the return value is shortened to len characters.

LTRIM (str): Returns the string str with leading space characters removed.

RTRIM (str): Returns the string str with trailing space characters removed.

TRIM ([{BOTH | LEADING | TRAILING} [ch] FROM] str): Returns the string str with all characters ch
prefixes or suffixes removed.

MySQL Date functions:

ADD_MONTHS (DATE,n): Returns date after adding the number of months specified in the

function. DAY(DATE): Returns the day of the date specified.

LAST_DAY (DATE): Returns last date of the month.

MONTHS_BETWEEN (DATE1, DATE2): Returns the number of months between the two dates.

NEXT_DAY (DATE, WEEKDAY): Returns the day of the week specified by WEEKDAY after

date.

Exercise-3
1) Display your name with the first letter being capital, where the entered name is in lower
case. 2) Display 2nd- 6th characters of your name.
3) Find the length of your full institute name.
4) Display all the Employee names with its first letter in upper case.
5) List the department name of each employee as a three letter code.
6) Display the month of the joining of each employee.
7) Display the date of joining of each employee in dd/mm/yy format.
8) Display the experience of each employee in terms of months.
9) Display the experience of each employee in terms of years and months.
10) Display the date of the next Friday after today's date.
11) Display the day of joining of each employee.
12) Display the date corresponding to 15 days after today's date.
13) Display the value 94204.27348 truncated up to 2 digits after the decimal point.
14) Display the value of the expression 5 + 89
15) Find out the square root of 6464312.

You might also like