Unit II Notes-Open Source Database
Unit II Notes-Open Source Database
Introduction:
MySQL is a relational database management system (RDBMS) that runs as a
server providing multi-user access to a number of databases. It is a popular
choice of database for use in web applications, and is a central component of
the widely used LAMP web application software stackLAMP is an acronym for
"Linux, Apache, MySQL, and Perl/PHP/Python". It is used in some of the most
frequently visited web sites on the Internet, including Flickr, Nokia.com, and
YouTube etc.
MySQL is written in C and C++. Its SQL parser is written in yacc, and a home-
brewed lexical analyzer named sql_lex.cc. It works on many different system
platforms, including Linux, Mac OS X, Microsoft Windows, AIX, BSDi,
FreeBSD, HP-UX, eComStation, i5/OS, IRIX, NetBSD, Novell NetWare,
OpenBSD, OpenSolaris, OS/2 Warp, QNX, Solaris, Symbian, SunOS, SCO
OpenServer, SCO UnixWare, Sanos and Tru64. Many programming languages
with language-specific APIs include libraries for accessing MySQL databases.
These include MySQL Connector/Net for integration with Microsoft's Visual
Studio (languages such as C# and VB are most commonly used) and the ODBC
driver for Java.
Please note that MySQL user accounts are different from UNIX/Linux login
accounts. For example, the MySQL root user and the Linux/Unix root user are
separate and have nothing to do with each other, even though the username is
the same in each case.
Unit-II Notes
Tip: Redhat Linux also supports service command, which can be use to start,
restart, stop any service:
# service mysqld start
# service mysqld stop
# service mysqld restart
To start the mysql program, try just typing its name at your command-line
prompt. If mysql starts up correctly, you'll see a short message, followed by a
mysql> prompt that indicates the program is ready to accept queries.
% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log
Unit-II Notes
Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 3
mysql>
To terminate a mysql session, issue a QUIT statement:
mysql> QUIT
You can also terminate the session by issuing an EXIT statement or (under
Unix) by typing Ctrl-D.
Integer Types
Type Range Space Taken
tinyint -128 to 127 1 byte
smallint -32768 to 32767 2 bytes
medium int -8388608 to 8388607 3 bytes
int -2147483648 to 2147483647 4 bytes
bigint -9223372036854775808 to 9223372036854775807 8 bytes
float(m,d) varies 4 bytes
double(m,d) varies 8 bytes
decimal varies M + 2 bytes
Date Types
Type Format Zero Value
datetime yyyy-nn-dd hh:mm:ss 0000-00-00 00:00:00
date yyyy-mm-dd 0000-00-00
time hh:mm:ss 00:00:00
year yyyy 0000
timestamp varies 0000000000
Other types 5
In addition to the types mentioned there are two other types worth mentioning.
The enum type defines a set of values, of which, only one may be chosen.
fieldname enum('a','b','c')
In addition to enum, the set field type also lets you define a set of values.
However, with set, more than one value in the list may be selected.
Column Modifiers
Name Applicable Types
auto_increment All int types
binary char, varchar
default all except blob and text
not null all
null all
primary key all
unique all
unsigned Numeric types
zerofill Numeric types
Auto_increment makes the field an automatic counter.
Binary makes the strings stored case sensitive. By default the values stored in
the char, varchar types are not case sensitive when searched.
Default allows you specify a default value for a field
Below is a create statement that uses a number of modifiers:
create table testTable
(testID int not null primary key auto_increment,
testName varchar(30),
testDate datetime,
testGiver varchar(30));
Create a Table
Next, you need to create a database table to hold your data. The SQL here
defines a table. Below is the command and the output from the command. The
database created below will be used in a web guestbook application.
mysql> create table guestTbl
-> (msgID int not null primary key auto_increment,
-> name varchar(30),
-> email varchar(30),
-> msgFrom varchar(30),
-> msgDate timestamp(14),
-> msgBody text);
Query OK, 0 rows affected (0.11 sec)
mysql>
In this example, the create command creates a table named guestTbl. The table
has six fields described below.
Unit-II Notes
msgID - a unique number assigned to each entry. The field hold an integer 6
value that is automatically incremented each time an entry is added.
name - a 30 character field holding the name of the guest.
email - a 30 character field holding the email address of the guest.
msgFrom - a 30 character field holding the location of the guest.
msgDate - the date and time the entry is added to the database.
msgBody - a text field holding a text message entered by the guest.
Our next step is to add data to the table.
The above command adds the title field/column to the table lists, and sets the
datatype to varchar(30). Modifiers can also be used. The following example
requires the column contains data.
alter table lists add title varchar(30);
Deleting Columns/Fields
The syntax for dropping a column or field from a table is pretty straightforward.
alter table tablename drop columnname;
You supply tablename and columnname. For example, to delete the column
just added above, the syntax would be:
alter table lists drop title;
connection, the MySQL server eventually notices, but shutting down the 9
connection explicitly allows the server to perform an orderly close on its end
immediately.
CONCAT(srcuser,'@',srchost)
mysql> SELECT t, srcuser, srchost FROM mail WHERE srchost LIKE 's%';
+---------------------+---------+---------+
| t | srcuser | srchost |
+---------------------+---------+---------+
| 2001-05-11 10:15:08 | barb | saturn |
| 2001-05-13 13:59:18 | barb | saturn |
| 2001-05-14 17:03:01 | tricia | saturn |
Queries such as the preceding one that test a given column to see if it has any
of several different values often can be written more easily by using the IN( )
operator. IN( ) is true if the column is equal to any value in its argument list:
mysql> SELECT t, srcuser, dstuser FROM mail
-> WHERE srcuser IN ('gene','barb','phil');
+---------------------+---------+---------+
| t | srcuser | dstuser |
+---------------------+---------+---------+
| 2001-05-11 10:15:08 | barb | tricia |
| 2001-05-12 15:02:49 | phil | phil |
mysql> SELECT srcuser, srcuser < 'c', size, size > 5000 FROM mail; 11
+---------+---------------+---------+-------------+
| srcuser | srcuser < 'c' | size | size > 5000 |
+---------+---------------+---------+-------------+
| barb | 1 | 58274 | 1 |
| tricia | 0 | 194925 | 1 |
| phil | 0 | 1048 | 0 |
| barb | 1 | 271 | 0 |
Some queries produce results containing duplicate records. For example, to see 12
who sent mail, you could query the mail table like this:
mysql> SELECT srcuser FROM mail;
+---------+
| srcuser |
+---------+
| barb |
| tricia |
| phil |
| barb |
| gene |
| phil |
| barb |
| tricia |
| gene |
But that result is heavily redundant. Adding DISTINCT to the query removes
the duplicate records, producing a set of unique values:
mysql> SELECT DISTINCT srcuser FROM mail;
+---------+
| srcuser |
+---------+
| barb |
| tricia |
| phil |
| gene |
+---------+
Solution
When you select rows, the MySQL server is free to return them in any order,
unless you instruct it otherwise by saying how to sort the result. There are lots
of ways to use sorting techniques. Sort a result set by adding an ORDER BY
clause that names the column or columns you want to sort by:
mysql> SELECT * FROM mail WHERE size > 100000 ORDER BY size;
+---------------------+---------+---------+---------+---------+
+---------------------+---------+---------+---------+---------+
Unit-II Notes
To sort a column in reverse (descending) order, add the keyword DESC after its
name in the ORDER BY clause:
mysql> SELECT * FROM mail WHERE size > 50000 ORDER BY size DESC;
+---------------------+---------+---------+---------+-
+---------------------+---------+---------+---------+------
You want to see only certain rows from a result set, like the first one or the last
five. MySQL supports a LIMIT clause that tells the server to return only part of
a result set. LIMIT is a MySQL-specific extension to SQL that is extremely
valuable when your result set contains more rows than you want to see at a
time.
To select the first n records of a query result, add LIMIT n to the end of your
SELECT statement:
+----+------+------------+-------+----------------------+------+
+----+------+------------+-------+----------------------+------+
LIMIT n tells the server to return the first n rows of a result set. LIMIT also has
a two-argument form that allows you to pick out any arbitrary section of rows
from a result. The arguments indicate how many rows to skip and how many to
return.
+----+------+------------+-------+---------------+------+ 14
| id | name | birth | color | foods | cats |
+----+------+------------+-------+---------------+------+
+----+------+------------+-------+---------------+------+
Types of Strings
MySQL can operate on regular strings or binary strings. "Binary" in this
context has little to do with the presence of non-ASCII values, so it's useful
right at the outset to make a distinction:
Binary data may contain bytes that lie outside the usual range of printable
ASCII characters.
+--------------------------------------+ 16
| Install MySQL in C:\mysql on Windows |
+--------------------------------------+
| Install MySQL in C:\mysql on Windows |
+--------------------------------------+
Other escape sequences recognized by MySQL are \b (backspace), \n (newline,
also called linefeed), \r (carriage return), \t (tab), and \0 (ASCII NUL).
For LEFT( ) and RIGHT( ), the second argument indicates how many characters
to return from the left or right end of the string. For MID( ), the second
argument is the starting position of the substring you want (beginning from 1)
and the third argument indicates how many characters to return.
The SUBSTRING( ) function takes a string and a starting position, returning
everything to the right of the position.
-> SUBSTRING_INDEX(name,'i',-1) 17
-> FROM metal;
+----------+-----------------------------+------------------------------+
| name | SUBSTRING_INDEX(name,'r',2) | SUBSTRING_INDEX(name,'i',-1)
|
+----------+-----------------------------+------------------------------+
| copper copper copper
| gold gold gold
| iron iron ron
| lead lead lead
mercury mercu mercury
To combine strings rather than pull them apart, use the CONCAT( ) function. It
concatenates all its arguments and returns the result:
mysql> SELECT CONCAT('Hello, ',USER( ),', welcome to MySQL!') AS
greeting;
+------------------------------------------+
| greeting |
+------------------------------------------+
| Hello, paul@localhost, welcome to MySQL! |
+------------------------------------------+
+----------------------------------------------+ 18
1 row in set (0.00 sec)
mysql> select locate('needle', 'haystackneedlehaystack',12);
+-----------------------------------------------+
| LOCATE('needle', 'haystackneedlehaystack',12)
+-----------------------------------------------+
| 0
+-----------------------------------------------+
1 row in set (0.00 sec)
| copper | 19
To reverse the sense of a pattern match, use NOT LIKE. The following query
finds strings that contain no i characters:
mysql> SELECT name FROM metal WHERE name NOT LIKE '%i%';
+---------+
| name |
+---------+
| copper |
| gold |
| lead |
characters 21
[:lower:] Lowercase alphabetic
characters
[:print:] Graphic or space characters
[:punct:] Punctuation characters
[:space:] Space, tab, newline, carriage
return
[:upper:] Uppercase alphabetic
characters
[:xdigit:] Hexadecimal digits (0-9, a-f, A-
F)
POSIX classes are intended for use within character classes, so you use them
within square brackets. The
following expression matches values that contain any hexadecimal digit
character:
mysql> SELECT name, name REGEXP '[[:xdigit:]]' FROM metal;
+----------+----------------------------+
| name | name REGEXP '[[:xdigit:]]' |
+----------+----------------------------+
| copper |1
| gold |1
| iron |0
The following alternation matches strings that begin with a vowel or end with
er:
mysql> SELECT name FROM metal WHERE name REGEXP '^[aeiou]|er$';
+--------+
| name |
+--------+
| copper
| iron
| silver
+--------+
TIME values are represented as strings in hh:mm:ss format, where hh, mm, 22
and ss are the hours, minutes, and seconds parts of the time. TIME values
often can be thought of as time-of-day values, but MySQL actually treats them
as elapsed time. Thus, they may be greater than 23:59:59 or even negative.
(The actual range is -838:59:59 to 838:59:59.)
TIMESTAMP values also include date and time parts, but are represented as
strings in CCYYMMDDhhmmss format.
Name Description 23
PERIOD_ADD() Add a period to a year-month
QUARTER() Return the quarter from a date argument
SEC_TO_TIME() Converts seconds to 'HH:MM:SS' format
SECOND() Return the second (0-59)
STR_TO_DATE() Convert a string to a date
SUBTIME() Subtract times
SYSDATE() Return the time at which the function executes
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIME() Extract the time portion of the expression passed
TIMEDIFF() Subtract time
With a single argument, this function returns the date or datetime
TIMESTAMP()
expression; with two arguments, the sum of the arguments
TIMESTAMPAD
Add an interval to a datetime expression
D()
TIMESTAMPDIF
Subtract an interval from a datetime expression
F()
TO_DAYS() Return the date argument converted to days
TO_SECONDS() Return the date or datetime argument converted to seconds since Year 0
UNIX_TIMESTA
Return a UNIX timestamp
MP()
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR() Return the calendar week of the date (0-53)
YEAR() Return the year
YEARWEEK() Return the year and week
ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or
datetime expression, and expr2 is a time expression.
mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1
1:1:1.000002');
-> '2008-01-02 01:01:01.000001'
mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998');
-> '03:00:01.999997'
-> '2004-01-01 13:00:00'
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Unit-II Notes
CURTIME() 24
Returns the current time as a value in 'HH:MM:SS' or HHMMSS.uuuuuu
format, depending on whether the function is used in a string or numeric
context. The value is expressed in the current time zone.
mysql> SELECT CURTIME();
-> '23:50:26'
mysql> SELECT CURTIME() + 0;
-> 235026.000000
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
-> '2003-12-31'
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 expr2 expressed as a value in days from one date
to the other. expr1 and expr2 are date or date-and-time expressions. Only the
date parts of the values are used in the calculation.
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
-> -31
DATE_FORMAT(date,format)
Formats the date value according to the format string.
The following specifiers may be used in the format string. The % character is
required before format specifier characters.
Specifi
Description
er
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, )
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
Unit-II Notes
Specifi 25
Description
er
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
Year for the week where Sunday is the first day of the week, numeric, four
%X
digits; used with %V
Year for the week, where Monday is the first day of the week, numeric, four
%x
digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal % character
%x x, for any x not listed above
DAYOFMONTH(date) 26
Returns the day of the month for date, in the range 1 to 31, or 0 for dates such
as '0000-00-00' or '2008-00-00' that have a zero day part.
mysql> SELECT DAYOFMONTH('2007-02-03');
-> 3
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, , 7 = Saturday).
These index values correspond to the ODBC standard.
mysql> SELECT DAYOFWEEK('2007-02-03');
-> 7
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
mysql> SELECT DAYOFYEAR('2007-02-03');
-> 34
EXTRACT(unit FROM date)
The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or
DATE_SUB(), but extracts parts from the date rather than performing date
arithmetic.
mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');
-> 2009
mysql> SELECT EXTRACT(YEAR_MONTH FROM '2009-07-02 01:02:03');
-> 200907
mysql> SELECT EXTRACT(DAY_MINUTE FROM '2009-07-02 01:02:03');
-> 20102
mysql> SELECT EXTRACT(MICROSECOND
-> FROM '2003-01-02 10:30:00.000123');
-> 123
FROM_DAYS(N)
Given a day number N, returns a DATE value.
mysql> SELECT FROM_DAYS(730669);
-> '2007-07-03'
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last
day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'
mysql> SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. dayofyear must be greater
than 0 or the result is NULL.
Unit-II Notes
-> 63426721458 29
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of
WEEK() enables you to specify whether the week starts on Sunday or Monday
and whether the return value should be in the range from 0 to 53 or from 1 to
53. The following table describes how the mode argument works.
Mod First day of Rang Week 1 is the first week
e week e
0 Sunday 0-53 with a Sunday in this year
with more than 3 days
1 Monday 0-53
this year
2 Sunday 1-53 with a Sunday in this year
with more than 3 days
3 Monday 1-53
this year
with more than 3 days
4 Sunday 0-53
this year
5 Monday 0-53 with a Monday in this year
with more than 3 days
6 Sunday 1-53
this year
7 Monday 1-53 with a Monday in this year
mysql> SELECT WEEK('2008-02-20');
-> 7
mysql> SELECT WEEK('2008-02-20',0);
-> 7
mysql> SELECT WEEK('2008-02-20',1);
-> 8
mysql> SELECT WEEK('2008-12-31',1);
-> 53
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, 6 = Sunday).
mysql> SELECT WEEKDAY('2008-02-03 22:23:00');
-> 6
mysql> SELECT WEEKDAY('2007-11-06');
-> 1
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
mysql> SELECT WEEKOFYEAR('2008-02-20');
-> 8
YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the zero date.
mysql> SELECT YEAR('1987-01-01');
-> 1987
YEARWEEK(date), YEARWEEK(date,mode)
Unit-II Notes
Returns year and week for a date. The mode argument works exactly like the 30
mode argument to WEEK(). The year in the result may be different from the
year in the date argument for the first and the last week of the year.
mysql> SELECT YEARWEEK('1987-01-01');
-> 198653
The default sort order is ascending, with smallest values first. To sort in reverse
(descending) order, add the DESC keyword to the name of the column you are
sorting by:
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name | birth |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
+----------+------------+
You can sort on multiple columns, and you can sort different columns in
different directions. For example,
mysql> SELECT name, species, birth FROM pet
-> ORDER BY species, birth DESC;
+----------+---------+------------+
| name | species | birth |
Unit-II Notes
+----------+---------+------------+ 31
| Chirpy | bird | 1998-09-11 |
| Whistler | bird | 1997-12-09 |
| Claws | cat | 1994-03-17 |
| Fluffy | cat | 1993-02-04 |
+----------+---------+------------+
The ORDER BY clauses in the queries shown thus far refer to the sorted
columns by name. You can also name the columns by their positions within
the output column list or by using aliases. Positions within the output list
begin with 1. The following query sorts results by the third output column,
miles:
mysql> SELECT name, trav_date, miles FROM driver_log ORDER BY 3;
+-------+------------+-------+
| name | trav_date | miles |
+-------+------------+-------+
| Ben | 2001-12-02 | 79 |
| Henry | 2001-11-27 | 96 |
| Henry | 2001-11-26 | 115 |
If an output column has an alias, you can refer to the alias in the ORDER BY
clause:
mysql> SELECT name, trav_date, miles AS distance FROM driver_log
-> ORDER BY distance;
+-------+------------+----------+
| name | trav_date | distance |
+-------+------------+----------+
| Ben | 2001-12-02 | 79 |
| Henry | 2001-11-27 | 96 |
| Henry | 2001-11-26 | 115 |
FIELD( ) compares its first argument to the following arguments and returns a
number indicating which one of them it matches. The following FIELD( ) call
compares value to str1, str2, str3, and str4, and returns 1, 2, 3, or 4,
depending on which one of them value is equal to:
FIELD(value,str1,str2,str3,str4)
The number of comparison values need not be four; FIELD( ) takes a variable-
length argument list. If value is NULL or none of the values match, FIELD( )
returns 0. FIELD( ) can be used to sort an arbitrary set of values into any order
Unit-II Notes
you please. For example, to display driver_log records for Henry, Suzi, and Ben, 32
in that order, do this:
mysql> SELECT * FROM driver_log
-> ORDER BY FIELD(name,'Henry','Suzi','Ben');
+--------+-------+------------+-------+
| rec_id | name | trav_date | miles |
+--------+-------+------------+-------+
| 3 | Henry | 2001-11-29 | 300 |
| 4 | Henry | 2001-11-27 | 96 |
| 2 | Suzi | 2001-11-29 | 391 |
| 7 | Suzi | 2001-12-02 | 502 |
| 1 | Ben | 2001-11-30 | 152 |
| 5 | Ben | 2001-11-29 | 131 |
+-----------+-------+ 33
Notice that because the query includes no ORDER BY clause, the records are
returned in unsorted order. If you add an ORDER BY day clause, it becomes
apparent that MySQL uses the internal numeric values for sorting:
mysql> SELECT day, day+0 FROM weekday ORDER BY day;
+-----------+-------+
| day | day+0 |
+-----------+-------+
| Sunday | 1 |
| Monday | 2 |
| Tuesday | 3 |
| Wednesday | 4 |
| Thursday | 5 |
| Friday | 6 |
| Saturday | 7 |
+-----------+-------+
CONCAT( ) normally takes multiple arguments and concatenates them into a
single string. But it can be used with just a single argument, which is useful
when all you want is its behavior of producing a string result:
mysql> SELECT day, day+0 FROM weekday ORDER BY CONCAT(day);
+-----------+-------+
| day | day+0 |
+-----------+-------+
| Friday | 6 |
| Monday | 2 |
| Saturday | 7 |
| Sunday | 1 |
| Thursday | 5 |
| Tuesday | 3 |
| Wednesday | 4 |
+-----------+-------+
Generating Summaries
GROUP BY (Aggregate) Functions
Aggregate (GROUP BY) Functions
Name Description
Return the average value of the
AVG()
argument
BIT_AND() Return bitwise and
BIT_OR() Return bitwise or
BIT_XOR() Return bitwise xor
COUNT(DISTIN Return the count of a number of
CT) different values
COUNT() Return a count of the number of rows
Unit-II Notes
Name Description 34
returned
GROUP_CONC
Return a concatenated string
AT()
MAX() Return the maximum value
MIN() Return the minimum value
Return the population standard
STDDEV()
deviation
SUM() Return the sum
Return the population standard
VARIANCE()
variance
COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows
retrieved by a SELECT statement. The result is a BIGINT value.
COUNT() returns 0 if there were no matching rows.
mysql> SELECT student.student_name,COUNT(*)
-> FROM student,course
-> WHERE student.student_id=course.student_id
-> GROUP BY student_name;
COUNT(*) is somewhat different in that it returns a count of the number of
rows retrieved, whether or not they contain NULL values.
COUNT(*) is optimized to return very quickly if the SELECT retrieves from one
table, no other columns are retrieved, and there is no WHERE clause. For
example:
mysql> SELECT COUNT(*) FROM student;
This optimization applies only to MyISAM tables only, because an exact row
count is stored for this storage engine and can be accessed very quickly. For
transactional storage engines such as InnoDB and BDB, storing an exact row
count is more problematic because multiple transactions may be occurring,
each of which may affect the count.
MAX([DISTINCT] expr)
Returns the maximum value of expr. MAX() may take a string argument; in
such cases, it returns the maximum string value. See Section 7.5.3, How
MySQL Uses Indexes. The DISTINCT keyword can be used to find the
maximum of the distinct values of expr, however, this produces the same result
as omitting DISTINCT.
MAX() returns NULL if there were no matching rows.
mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MAX(), MySQL currently compares ENUM and SET columns by their string
value rather than by the string's relative position in the set. This differs from
how ORDER BY compares them. This is expected to be rectified in a future
MySQL release.
Unit-II Notes
MIN([DISTINCT] expr) 35
Returns the minimum value of expr. MIN() may take a string argument; in such
cases, it returns the minimum string value. See Section 7.5.3, How MySQL
Uses Indexes. The DISTINCT keyword can be used to find the minimum of the
distinct values of expr, however, this produces the same result as omitting
DISTINCT.
MIN() returns NULL if there were no matching rows.
mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MIN(), MySQL currently compares ENUM and SET columns by their string
value rather than by the string's relative position in the set. This differs from
how ORDER BY compares them. This is expected to be rectified in a future
MySQL release.
Group By
Now we are going to use the group by statement. The group by statement, as
said before, is especially useful for aggregating, meaning to apply some
function. Let's see an example:
This query returns the total amount of money spent by each customer during
all their shoppings. The table returned looks like this:
cust_ SUM(total_pric
id e)
1 30
2 3
3 1
The way you have to understand the query is that we compute the sum of all
amounts for each customer. This is expressed by the GROUP BY cust_id. Now,
if we would try to do this for each product. This would correspond to the total
money gained per product. The query looks like this:
SUM(total_pric 36
item
e)
apple 7
balloon 1
pillow 25
plastic
1
bag
Solution
);
To generate a new sequence value, insert NULL into the column, or just omit it
from your INSERT statement. Either way, MySQL will create a new sequence
number for you.
-> (NULL,'housefly','2001-09-10','kitchen'), 37
-> (NULL,'millipede','2001-09-10','driveway'),
+----+-------------------+------------+------------+
+----+-------------------+------------+------------+
-> (3,'cricket','2001-09-11','basement');
INT is the column's basic type. You need not necessarily use INT, but the
column must be one of the integer types: TINYINT, SMALLINT, MEDIUMINT,
INT, or BIGINT. It's important to remember that AUTO_INCREMENT is a
column attribute that should be applied only to integer types. Older versions of
MySQL will allow you to create an AUTO_INCREMENT column using non-
integer types such as CHAR, but bad things will happen if you do that. (Even if
the initial sequence numbers appear to be generated normally, sooner or later
the column will fail. A typical error is "duplicate key" after inserting a few
records, even when you know the column should be able to hold more
Unit-II Notes
The maximum sequence value is determined by the specific integer type used,
so you should choose a type that is big enough to hold the largest value you'll
need. The maximum unsigned value of each integer type is shown in the
following table, which you can use to select an appropriate type.
TINYINT 255
SMALLINT 65,535
MEDIUMINT 16,777,215
INT 4,294,967,295
BIGINT 18,446,744,073,709,55
1,615
Sometimes people omit UNSIGNED so that they can create records that
contain negative numbers in the sequence column. (Using -1 to signify "has no
ID" would be an instance of this.) MySQL makes no guarantees about how
negative numbers will be treated, so you're playing with fire if you try to use
them in an AUTO_INCREMENT column. For example, if you resequence the
column, you'll find that all your negative values get turned into regular
(positive) sequence numbers.
The column is declared as a PRIMARY KEY to ensure that its values are 39
unique. Tables can have only one PRIMARY KEY, so if the table already has
some other PRIMARY KEY column, you can declare an AUTO_INCREMENT
column to have a UNIQUE index instead:
-> VALUES('cricket','2001-09-11','basement');
+------------------+
| last_insert_id( ) |
+------------------+
|9|
+------------------+
Performance.
The impetus for resequencing may stem from the notion that doing so
"compacts" a sequence column by removing gaps and allows MySQL to run
queries more quickly. This is not true. MySQL doesn't care whether or not
there are holes, and there is no performance gain to be had by renumbering an
The upper limit of a sequence column is determined by the column's data type.
If an AUTO_INCREMENT sequence is approaching the upper limit of its column
type, renumbering packs the sequence and frees up more values at the top.
This may be a legitimate reason to resequence a column, but it is still
unnecessary in many cases to do so. You may be able to expand the column's
range to increase its upper limit, without changing the values stored in the
column.
Solution
-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)); 41
mysql> INSERT INTO t (id) VALUES(NULL);
+----+
| id |
+----+
|1|
|2|
|3|
+----+
For MyISAM tables, you can begin the sequence at a specific initial value n by
including an AUTO_INCREMENT = n clause at the end of the CREATE TABLE
statement:
-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))
| id |
+-----+
| 100 |
| 101 |
| 102 |
+-----+
Alternatively, you can create the table and then set the initial sequence value
with ALTER TABLE:
-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id));
+-----+
| id |
+-----+
| 100 |
| 101 |