SQL Queries
SQL Queries
AGGREGATE FUNCTIONS
Multiple Row Functions or Aggregate Functions operate on a set of rows to return a single value.
52. Find the highest and lowest marks scored in the database table and display it as 'Highest Marks' and 'Lowest Marks'.
SELECT MAX(marks) as 'Highest Marks', MIN(marks) as 'Lowest Marks' FROM
student;
53. Find the average marks.
SELECT AVG(marks) as 'Average Marks' FROM student;
54. Find the total fee collected.
SELECT SUM(fee) as 'Total Fee' FROM student;
55. Find the number of students in the table.
SELECT COUNT(*) as 'No. of Students' FROM student;
56. Find the number of students in the table if their result has been declared.
SELECT COUNT(result) as 'No. of Results Generated' FROM student;
or
SELECT COUNT(*) as 'No. of Results Generated' FROM student WHERE result IS NOT
NULL;
57. Find the number of students in the table whose result has not been declared.
SELECT COUNT(*) as 'No. of Results NOT Generated' FROM student WHERE result IS
NULL;
QUERYING DATA USING GROUP BY, HAVING, ORDER BY
58. Find the number of students in each class.
SELECT class, COUNT(class) FROM student GROUP BY class;
59. Find the number of students in classes '6A', '7A', and '8A'.
(DON'T USE WHERE, INSTEAD USE HAVING TO CHECK A CONDITION WHILE USING GROUP BY)
SELECT class, COUNT(class) FROM student GROUP BY class HAVING class
IN('6A','7A','8A');
60. Find the number of students in classes other than '6A', '7A', and '8A'.
SELECT class, COUNT(class) FROM student GROUP BY class HAVING class NOT
IN('6A','7A','8A');
61. Display the student records class-wise.
SELECT * FROM student ORDER BY class;
62. Display the student records class-wise arranged alphabetically based on their names.
SELECT * FROM student ORDER BY class, name;
63. Display the student records in descending order of class, arranged alphabetically based on their names.
SELECT * FROM student ORDER BY class DESC, name ASC;
Single Row Functions in MySQL
Single Row Functions operate on a single value and 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.
Single row functions can further be categorized as – Numeric functions, String functions and Date and Time functions.
NUMERIC FUNCTIONS
Numeric functions perform operations on numeric values and return numeric values.
POWER(X,Y) returns the value of X raised to the power of Y.
SELECT POW(2,4); 16
SELECT POW(2,-2); 0.25
SELECT POW(-2,3); -8
SELECT id,num1,POWER(num1,2) FROM t1;
ROUND(X,D) or ROUND(X) rounds the argument X to D decimal places. If number of decimal places is not specified or is
zero, the number rounds to the nearest integer OR (0 decimal places). If negative value is specified for precision, it counts off
that value left from the decimal point – rounds off the value to the nearest tens, hundred , thousand and so on. If positive value
is specified for precision, it counts off that value right from the decimal point.
SELECT ROUND(-1.23); -1
SELECT ROUND(-1.58); -2
SELECT ROUND(1.43); 1
SELECT ROUND(6.298, 1); 6.3
SELECT ROUND(6.235, 0); 6
SELECT ROUND(56.235, -1); 60
SELECT id,ROUND(num1,0) FROM t1;
TRUNCATE(X,D) returns the number X, truncated to D decimal places. If D is 0, the result has no decimal point or fractional
part. If D is negative, it causes D digits left of the decimal point of the value X to become zero. TRUNCATE does not round a
number. It simply chops off digits from a number.
SELECT TRUNCATE(7.543,1); 7.5
SELECT TRUNCATE(4.567,0); 4
SELECT TRUNCATE(-7.45,1); -7.4
SELECT TRUNCATE(346,-2); 300
SELECT id,TRUNCATE(num1,0) FROM employee;
MOD(n1, n2) or n1 MOD n2 or n1%n2 returns the remainder of a number divided by another number.
SELECT MOD(18, 4);
or
SELECT 18 MOD 4;
or
SELECT 18 % 4;
STRING (or CHARACTER) FUNCTIONS
String functions operate on character type data. String functions are used to extract, change, format or alter character strings.
These functions return either character or numeric values.
LENGTH(str) returns the length of a column or a string in bytes.
SELECT LENGTH('Informatics'); 11
SELECT LENGTH(name) FROM student;
CONCAT(str1,str2,...) returns the string that results from concatenating the arguments.
SELECT CONCAT('My', 'S', 'QL'); 'MySQL'
SELECT CONCAT('Class', NULL, 'XI'); NULL
SELECT CONCAT(roll,'',name) FROM student;
INSTR(str,substr) returns the position of the first occurrence of substring substr in string str.
SELECT INSTR ('Informatics', 'for'); 3
SELECT INSTR('Computers', 'pet'); 0
SELECT INSTR(name,'Kumar') FROM student;
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'); 'informatics'
SELECT LOWER(name) FROM student;
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'); 'INFORMATICS'
SELECT UPPER(name) FROM student;
LEFT(str,n) returns the specified number of characters (n)from the left side of string str.
SELECT LEFT('Informatics', 3); 'Inf'
select LEFT(name,3)FROM student;
RIGHT(str,n) returns the specified number of characters (n) from the right side of string str.
SELECT RIGHT('Informatics', 4); 'tics'
SELECT RIGHT(name,3) FROM student;
LTRIM(str) removes leading spaces i.e. removes spaces from the left side of the string str.
SELECT LTRIM(' Informatics'); 'Informatics'
SELECT LTRIM(name) FROM student;
RTRIM(str) removes trailing spaces i.e. removes spaces from the right side of the string str.
SELECT RTRIM('Informatics '); 'Informatics'
SELECT RTRIM(name) FROM student;
TRIM(str) removes both leading and trailing spaces from the string str.
SELECT TRIM(' Informatics '); 'Informatics'
SELECT TRIM(name) FROM student;
SUBSTRING(str,m,n) or MID(str,m,n) or SUBSTR(str,m,n) returns the specified number of characters from the middle of
the string. There are three arguments. The first argument is the source string. The second argument is the position of first
character to be displayed. The third argument is the number of characters to be displayed. If the third argument is missing, then
starting from the position specified, the rest of the string is returned. A negative value for the second argument i.e. the position
(pos) means, the beginning of the substring is pos characters from the end of the string, SUBSTR is the same as SUBSTRING.
SELECT SUBSTRING('Informatics',3); 'formatics'
SELECT SUBSTRING('Informatics' FROM 4); 'ormatics'
SELECT SUBSTRING('Informatics',3,4); 'form'
SELECT SUBSTRING('Computers', -3); 'ers'
SELECT SUBSTRING('Computers', -5, 3); 'ute'
SELECT SUBSTRING('Computers' FROM -4 FOR 2); 'te'
SELECT MID('Informatics',3,4); 'form'
select MID(name,3,2) FROM student;
ASCII(str) 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'); 50(ASCII value of character '2')
SELECT ASCII('dx'); 100(ASCII value of d)
SELECT ASCII('A'); 65(ASCII value of 'A')
DATE AND TIME FUNCTIONS
Date and Time functions perform various tasks on or manipulate Date type data. The default date format in MySQL is 'YYYY-
MM-DD' or YYYYMMDD.
CURDATE() returns the current date in YYYY-MM-DD format or YYYYMMDD format, depending on whether the function
is used in a string or numeric context.
SELECT CURDATE();
'2010-02-26'
DATE(expr) extracts the date part of a date or datetime expression.
SELECT DATE('2010-02-26 01:02:03');
'2010-02-26'
SELECT DATE('2009-10-16 01:02:03')
'2009-10-16'
DAYOFMONTH(date) or DAY(date) returns the day of the month for a given date; returns a number in the range 0 to 31.
SELECT DAYOFMONTH('2009-07-21'); 21
SELECT name, dayofmonth(doj) FROM student;
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'); 2
SELECT name, month(doj) FROM student;
MONTHNAME() returns the name of the month (January, February....) for a given date.
SELECT MONTHNAME("2017-06-15 09:34:21");
SELECT MONTHNAME(CURDATE());
SELECT name, monthname(doj) FROM student;
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('2010-02-26'); 2010
SELECT name, year(doj) FROM student;
DAYNAME(date) returns the name of the weekday (Sunday, Monday....) for the date passed.
SELECT DAYNAME('2010-02-26');
SELECT name, dayname(doj) FROM student;
DAYOFWEEK(date) returns the day of week in number as 1 for Sunday, 2 for Monday and so on.
SELECT DAYOFWEEK('2009-07-21'); 3
SELECT name, dayofweek(doj) FROM student;
DAYOFYEAR(date) returns the day of the year for the given date in numeric format in the range 1 to 366. e.g. 1 st Feb is the
32nd day of the year.
SELECT DAYOFYEAR('2009-07-21'); 202
SELECT DAYOFYEAR('2009-01-01'); 1
SELECT name, dayofyear(doj) FROM student;
NOW() 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.
SELECT NOW();
'2010-02-26 21:30:26'
SYSDATE() 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. It 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.
SELECT SYSDATE();
'2010-02-26 21:30:26'
SELECT SYSDATE() + 0;
20100226213026.000000
Difference between NOW() and SYSDATE()
The sleep(arg) function pauses for the number of seconds given by the argument.
NOW() Even after a pause of 20 seconds induced by sleep(20),now() shows the same time ie. the time at which the
statement began to execute.
SELECT now(), sleep(20), now();
'2010-05-08 14:57:12' 0 '2010-05-08 14:57:12'
SYSDATE() After 20 seconds induced by sleep(20), sysdate() shows time incremented by 20 seconds.
SELECT sysdate(), sleep(20), sysdate();
'2010-05-08 14:57:12' 0 '2010-05-08 14:57:32'