You are on page 1of 22

MySQL

● MySQL is an open-source relational database management system (RDBMS).


● This is written in C, C++
● Works on windows and Linux
● MySQL is a central component of the LAMP open-source web application software
stack (and other "AMP" stacks)
● LAMP is an acronym for "Linux, Apache, MySQL, Perl/PHP/Python
● dev.mysql.com is the official page
● MySQL was created by a Swedish company, MySQL AB, founded by David Axmark,
Allan Larsson and Michael "Monty" Widenius
● The first version of MySQL appeared on 23 May 1995
● Sun Microsystems acquired MySQL AB in 2008
● Oracle acquired Sun Microsystems on 27 January 2010
● The day Oracle announced the purchase of Sun, Michael "Monty" Widenius forked
MySQL, launching MariaDB, and took a swath of MySQL developers with him
● The developers release minor updates of the MySQL Server approximately every two
months.
● The sources can be obtained from MySQL's website or from
MySQL's GitHub repository, both under the GPL license
● phpMyAdmin is a free and open source tool written in PHP intended to handle the
administration of MySQL with the use of a web browser. It can perform various tasks
such as creating, modifying or deleting databases, tables, fields or rows; executing
SQL statements; or managing users and permissions
● Toad for MySQL is a software application from Dell Software that database
developers, database administrators and data analysts use to manage both relational
and non-relational databases using SQL. Toad supports many databases and
environments.

Creating an account

To create a user account


🡪create user 'username'@'localhost' identified by 'password';

🡪create user 'charan'@'localhost' identified by 'charan';

to know the users available on mysql

🡪select user, host from mysql.user;

To know which user logged in

select user();

Or

select current_user();

to drop a user account

🡪DROP USER 'username'@'localhost';

Drop user(s)

DROP USER [IF EXISTS] user [, user] ...

Rename user(s)

RENAME USER old_user TO new_user [, old_user TO new_user] ...

Modify password for user


ALTER USER 'jeffrey'@'localhost' IDENTIFIED BY 'new_password'
PASSWORD EXPIRE INTERVAL 180 DAY;

SET PASSWORD FOR 'jeffrey'@'localhost' = password_option;

SET PASSWORD = password_option;

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

if the above fails

UPDATE mysql.user SET authentication_string =


PASSWORD('MyNewPass') WHERE User = 'root' AND Host = 'localhost';

Lock the account

ALTER USER 'jeffrey'@'localhost' ACCOUNT LOCK;

to change from one user to other user from cmd line

mysql -uroot -proot

privileges

Initially there will be no privileges in mysql for any new account created

In MySQL USAGE is synonymous with "no privileges"

SHOW GRANTS;

SHOW GRANTS FOR 'root'@'localhost';

● The GRANT statement grants privileges to MySQL user accounts.


● GRANT additionally requires the SUPER privilege.

GRANT ALL ON db1.* TO 'jeffrey'@'localhost';

db1 is db name, * represents all tables;

GRANT SELECT ON db2.invoice TO 'jeffrey'@'localhost';

GRANT [type of permission] ON [database name].[table name] TO


‘[username]’@'localhost’;

To reload the privileges from db, so that recent changes are available

FLUSH PRIVILEGES;

To tell the server to reload the grant tables, perform a flush-privileges


operation use “flush privileges;”

REVOKE statement is related to GRANT and enables administrators to


remove account privileges

REVOKE INSERT ON *.* FROM 'jeffrey'@'localhost';

REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ...

To change privileges, first revoke. Such as: revoke all privileges on *.*
from 'user'@'host'; Then grant the appropriate privileges as desired:
grant SELECT,INSERT,UPDATE,DELETE ON 'db'.* TO 'user'@'host';

GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO


'someuser'@'somehost';

desc and describe are same, for showing table structure

ALTER USER 'jeffrey'@'localhost' WITH MAX_QUERIES_PER_HOUR 90;

DROP {DATABASE | SCHEMA} [IF EXISTS] db_name

Data types in MySQL

MySQL supports a number of SQL data types in several categories: numeric types, date and time
types, string (character and byte) types, spatial types, and the JSON data type

Numeric types

1. Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
2. Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC
3. Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

1.
2. The DECIMAL and NUMERIC types store exact numeric data values. These types are used
when it is important to preserve exact precision

Ex:- salary DECIMAL(5,2)

Stores a value in the range of -999.99 to 999.99

3. The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four
bytes for single-precision values and eight bytes for double-precision values.

FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here (M,D) means than


values can be stored with up to M digits in total, of which D digits may be after the decimal
point.

Both 2 and 3rounds off to nearest fraction

Differences

1. To store decimal fractions using decimal we have to compulsory mention (m,d), in


float its not mandatory

2. if we say decimal(3,2) it can take a max of 9.99

3. decimal by default allows 65 digits of which


MySQL Date and Time

The date and time types for representing temporal values are DATE, TIME, DATETIME, TIMESTAMP,
and YEAR

date parts must always be given in year-month-day

The DATETIME type is used when you need values that contain both date and time information.
MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported
range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. It
has varying properties, depending on the MySQL version and the SQL mode the server is running in.

If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved
value is different from the value you stored.

1000-01-01 00:00:00' to '9999-12-31 23:59:59’

'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC

To define a column that includes a fractional seconds part, use the syntax type_name(fsp), where
type_name is TIME, DATETIME, or TIMESTAMP, and fsp is the fractional seconds

CREATE TABLE fractest( c1 TIME(2), c2 DATETIME(2), c3 TIMESTAMP(2) );

INSERT INTO fractest VALUES ('17:51:04.777', '2014-09-08 17:51:04.777', '2014-09-08


17:51:04.777');

SELECT * FROM fractest;


| 17:51:04.78 | 2014-09-08 17:51:04.78 | 2014-09-08 17:51:04.78 |

For DATETIME, DATE, and TIMESTAMP types, MySQL interprets dates specified with ambiguous year
values using these rules:

Year values in the range 00-69 are converted to 2000-2069.

Year values in the range 70-99 are converted to 1970-1999.

String Types

The CHAR and VARCHAR Types

The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved. They
also differ in maximum length and in whether trailing spaces are retained

The length of a CHAR column is fixed to the length that you declare when you create the table. The
length can be any value from 0 to 255

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0
to 65,535

a CHAR always takes the same amount of space regardless of what you store, whereas the storage
requirements for a VARCHAR vary depending on the specific string stored

create table xyz(a char(4), b varchar(4));

Value CHAR(4) Length


'' ' ' 4 bytes
'ab' 'ab ' 4 bytes
'abcd' 'abcd' 4 bytes

Value VARCHAR(4) Length


'' '' 1 byte
'ab' 'ab' 3 bytes
'abcd' 'abcd' 5 bytes

The BINARY and VARBINARY Types


The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except that they contain
binary strings rather than nonbinary strings. That is, they contain byte strings rather than character
strings

The BLOB and TEXT Types

A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types are
TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the
values they can hold. The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT

BLOB is used for storing binary data while Text is used to store large string.

you cannot choose the size of TEXT but you can for a VARCHAR

you cannot put an index on a TEXT column.So if you want to have an index on the column, you have
to use VARCHAR

MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB

The ENUM Type

An ENUM is a string object with a value chosen from a list of permitted values that are enumerated
explicitly in the column specification at table creation time

CREATE TABLE shirts (

name VARCHAR(40),

size ENUM('x-small', 'small', 'medium', 'large', 'x-large')

);

INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),

('polo shirt','small');
SELECT name, size FROM shirts WHERE size = 'medium';

+---------+--------+

| name | size |

+---------+--------+

| t-shirt | medium |

+---------+--------+

UPDATE shirts SET size = 'small' WHERE size = 'large';

COMMIT;

An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than
3000

The SET Type

A SET is a string object that can have zero or more values, each of which must be chosen from a list
of permitted values specified when the table is created

Record selection technology


DDL create alter drop truncate

DML insert update delete

TCL commit rollback savepoint

DCL grant revoke

DRL select
autocommit = on|off

innodb as storage engine

MyISAM as storage engine

set autocommit=0;
ALTER TABLE table_name ENGINE =innodb

set default_storage_engine=’innodb’

create table t1(i int) engine=innodb;

Show table status where name =’table name’

From 5.5.5 it is innodb, earlier it is myisam

Sorting query results


SELECT * FROM tname WHERE condition ORDER BY cname[,cname2] ASC|DESC [LIMIT offset, upto]

Generating Summary/ aggregate functions in SQL

max(), min(), sum(),avg(),count()

group by with multiple columns


10 cse
10 cse
12 IT
12 ece
04 ece

using sequences

auto_increment
create table employee (sno int unsigned auto_increment primary
key,id int,name varchar(20));

alter table tname auto_increment =where_to_start;

set @@auto_increment_increment=10;

auto_increment_offset determines the starting point for the


AUTO_INCREMENT column value

SET @@auto_increment_offset=5;
When the value of auto_increment_offset is greater than that of
auto_increment_increment, the value of auto_increment_offset is
ignored.

Make sure that auto_increment_increment >


auto_increment_offset
Name Description

Add time values (intervals) to a date value

ADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days)

SELECT ADDDATE('2008-01-02', 31);

ADDDATE() SELECT ADDDATE('2008-01-02', interval 31 day);

Add time

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');

ADDTIME() -> '03:00:01.999997'

Convert from one time zone to another

CONVERT_TZ(dt,from_tz,to_tz)

SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');

SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');

CONVERT_TZ()

Return the current date

SELECT CURDATE();
CURDATE() -> '2008-06-13'

Synonyms for CURDATE()


CURRENT_DATE()
CURRENT_DATE

Synonyms for CURTIME()

CURRENT_TIME() SELECT CURTIME();


CURRENT_TIME -> '23:50:26'

Synonyms for NOW()

SELECT NOW();
-> '2007-12-15 23:50:26'

CURRENT_TIMESTAMP()
CURRENT_TIMESTAMP

CURTIME() Return the current time


Extract the date part of a date or datetime expression

SELECT DATE('2003-12-31 01:02:03');


DATE() -> '2003-12-31'

Add time values (intervals) to a date value

DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL exprunit)

he date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be
added from the starting date

SELECT DATE_ADD('2100-12-31 23:59:59',


-> INTERVAL '1:1' MINUTE_SECOND);

-> '2101-01-01 00:01:00'

SELECT DATE_ADD('2010-12-31 23:59:59',


-> INTERVAL 1 DAY);
-> '2011-01-01 23:59:59'

SELECT DATE_ADD('1900-01-01 00:00:00',


-> INTERVAL '-1 10' DAY_HOUR);
-> '1899-12-30 14:00:00'

unit Value Expected expr Format
MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_HOUR 'DAYS HOURS'
YEAR_MONTH 'YEARS-MONTHS'

DATE_ADD()

DATE_FORMAT() Format date as specified


DATE_FORMAT(date,format)

SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');


-> 'Sunday October 2009'

SELECT DATE_FORMAT('1900-10-04 22:23:00',


-> '%D %y %a %d %m %b %j');
-> '4th 00 Thu 04 10 Oct 277'

SELECT DATE_FORMAT('1997-10-04 22:23:00',


-> '%H %k %I %r %T %S %w');
-> '22 22 10 10:23:00 PM 22:23:00 00 6'

%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)
%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; WEEK()mode 0
%u Week (00..53), where Monday is the first day of the week; WEEK()mode 1
%V Week (01..53), where Sunday is the first day of the week; WEEK()mode 2; used with %X
%v Week (01..53), where Monday is the first day of the week; WEEK()mode 3; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
Year for the week, where Monday is the first day of the week, numeric, four digits; used
%x with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
Subtract a time value (interval) from a date

DATE_SUB() Similar to date_add()

Subtract two dates

DATEDIFF(expr1,expr2)

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.

SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');


-> 1

SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');


DATEDIFF() -> -31

Synonym for DAYOFMONTH()

DAY()

Return the name of the weekday

DAYNAME(date)

SELECT DAYNAME('2007-02-03');
DAYNAME() -> 'Saturday'
Return the day of the month (0-31)

DAYOFMONTH(date)

SELECT DAYOFMONTH('2007-02-03');
DAYOFMONTH() -> 3

Return the weekday index of the argument

Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). 

SELECT DAYOFWEEK('2007-02-03');
DAYOFWEEK() -> 7

Return the day of the year (1-366)

DAYOFYEAR(date)

SELECT DAYOFYEAR('2007-02-03');
DAYOFYEAR() -> 34

Extract part of a date

EXTRACT(unit FROM date)

The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD()

SELECT EXTRACT(YEAR FROM '2009-07-02');


-> 2009

SELECT EXTRACT(YEAR_MONTH FROM '2009-07-02 01:02:03');


-> 200907

SELECT EXTRACT(DAY_MINUTE FROM '2009-07-02 01:02:03');


EXTRACT() -> 20102

Convert a day number to a date

FROM_DAYS(N) to
Given a day number N, returns a DATE value.

SELECT FROM_DAYS(730669);
-> '2007-07-03'

FROM_DAYS()

Format Unix timestamp as a date

FROM_UNIXTIME(unix_timestamp),

FROM_UNIXTIME(unix_timestamp,format)

Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD


HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format

SELECT FROM_UNIXTIME(1447430881);
-> '2015-11-13 10:08:01'

SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
-> '%Y %D %M %h:%i:%s %x');
FROM_UNIXTIME() -> '2015 13th November 10:08:01 2015'

Return a date format string

GET_FORMAT({DATE|TIME|DATETIME}, {'EUR'|'USA'|'JIS'|'ISO'|'INTERNAL'})

The possible values for the first and second arguments result in several possible format strings (for the specifiers used, see
the table

Function Call Result


GET_FORMAT(DATE,'USA') '%m.%d.%Y'
GET_FORMAT(DATE,'JIS') '%Y-%m-%d'
GET_FORMAT(DATE,'ISO') '%Y-%m-%d'
GET_FORMAT() GET_FORMAT(DATE,'EUR') '%d.%m.%Y'
GET_FORMAT(DATE,'INTERNAL') '%Y%m%d'
GET_FORMAT(DATETIME,'USA') '%Y-%m-%d %H.%i.%s'
GET_FORMAT(DATETIME,'JIS') '%Y-%m-%d %H:%i:%s'
GET_FORMAT(DATETIME,'ISO') '%Y-%m-%d %H:%i:%s'
GET_FORMAT(DATETIME,'EUR') '%Y-%m-%d %H.%i.%s'
GET_FORMAT(DATETIME,'INTERNAL') '%Y%m%d%H%i%s'
GET_FORMAT(TIME,'USA') '%h:%i:%s %p'
GET_FORMAT(TIME,'JIS') '%H:%i:%s'
GET_FORMAT(TIME,'ISO') '%H:%i:%s'
GET_FORMAT(TIME,'EUR') '%H.%i.%s'
GET_FORMAT(TIME,'INTERNAL') '%H%i%s'
Extract the hour

HOUR(time)

SELECT HOUR('10:05:03');
-> 10

SELECT HOUR('272:59:59');
-> 272

Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range
HOUR() of TIME values actually is much larger, so HOURcan return values greater than 23

Return the last day of the month for the argument

LAST_DAY(date)

SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'

SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'

SELECT LAST_DAY('2003-03-32');
LAST_DAY -> NULL

LOCALTIME() LOCALTIME Synonym for NOW()

LOCALTIMESTAMP
LOCALTIMESTAMP() Synonym for NOW()

Create a date from the year and day of year

MAKEDATE(year,dayofyear)

SELECT MAKEDATE(2011,31), MAKEDATE(2011,32);


-> '2011-01-31', '2011-02-01'

SELECT MAKEDATE(2011,365), MAKEDATE(2014,365);


MAKEDATE() -> '2011-12-31', '2014-12-31'

Create time from hour, minute, second

MAKETIME(hour,minute,second)

SELECT MAKETIME(12,15,30);
MAKETIME() -> '12:15:30'

Return the microseconds from argument

SELECT MICROSECOND('12:00:00.123456');
-> 123456

SELECT MICROSECOND('2009-12-31 23:59:59.000010');


MICROSECOND() -> 10

Return the minute from the argument

MINUTE(time)
Returns the minute for time, in the range 0 to 59.

SELECT MINUTE('2008-02-03 10:05:03');


MINUTE() -> 5

MONTH() Return the month from the date passed

MONTH(date)
Returns the month for date, in the range 1 to 12 for January to December, or 0 for dates such as '0000-00-
00' or '2008-00-00' that have a zero month part.

SELECT MONTH('2008-02-03');
-> 2

Return the name of the month

MONTHNAME(date)

SELECT MONTHNAME('2008-02-03');
-> 'February'

MONTHNAME()

NOW() Return the current date and time

Add a period to a year-month

PERIOD_ADD(P,N)
Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM
Note that the period argument P is not a date value

SELECT PERIOD_ADD(200801,2);
-> 200803

PERIOD_ADD()

Return the number of months between periods

PERIOD_DIFF(P1,P2)

Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that
the period arguments P1 and P2are not date values

SELECT PERIOD_DIFF(200802,200703);
PERIOD_DIFF() -> 11

Return the quarter from a date argument

QUARTER(date)

SELECT QUARTER('2008-04-01');
-> 2

QUARTER()

Converts seconds to 'HH:MM:SS' format

SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes, and seconds, as a TIME value

SELECT SEC_TO_TIME(2378);
-> '00:39:38'

SEC_TO_TIME()

Return the second (0-59)

SECOND(time)

SELECT SECOND('10:05:03');
-> 3

SECOND()

STR_TO_DATE() Convert a string to a date

STR_TO_DATE(str,format)

SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y');
-> '2013-05-01'

SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');


-> '2013-05-01'
SELECT STR_TO_DATE('9','%m');
-> '0000-09-00'

SELECT STR_TO_DATE('9','%s');
-> '00:00:09'

Synonym for DATE_SUB() when invoked with three arguments

SUBDATE(date,INTERVAL expr unit), 

SUBDATE(expr,days)

SELECT DATE_SUB('2008-01-02', INTERVAL 31 DAY);


-> '2007-12-02'

SELECT SUBDATE('2008-01-02', INTERVAL 31 DAY);


-> '2007-12-02'

SELECT SUBDATE('2008-01-02 12:00:00', 31);


SUBDATE() -> '2007-12-02 12:00:00'

Subtract times

SUBTIME(expr1,expr2)

SUBTIME() returns expr1 − expr2 expressed as a value in the same format as expr1. 

expr1 is a time or datetime expression, and expr2 is a time expression.

SELECT SUBTIME('2007-12-31 23:59:59.999999','1 1:1:1.000002');


-> '2007-12-30 22:58:58.999997'

SELECT SUBTIME('01:00:00.999999', '02:00:00.999998');


SUBTIME() -> '-00:59:59.999999'

Return the time at which the function executes

SYSDATE() Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'

Extract the time portion of the expression passed

TIME(expr)

Extracts the time part of the time or datetime expression expr and returns it as a string.

SELECT TIME('2003-12-31 01:02:03');


-> '01:02:03'

SELECT TIME('2003-12-31 01:02:03.000123');


-> '01:02:03.000123'

TIME()

Format as time

TIME_FORMAT(time,format)

This is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes,
seconds, and microseconds. Other specifiers produce a NULL value or 0.

SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');


-> '100 100 04 04 4'

TIME_FORMAT()

TIME_TO_SEC() Return the argument converted to seconds

TIME_TO_SEC(time)

SELECT TIME_TO_SEC('22:23:00');
-> 80580

SELECT TIME_TO_SEC('00:39:38');
-> 2378

Subtract time

TIMEDIFF(expr1,expr2)
TIMEDIFF() returns expr1 − expr2 expressed as a time value. expr1 andexpr2 are time or date-and-time expressions,
but both must be of the same type.

SELECT TIMEDIFF('2000:01:01 00:00:00',


-> '2000:01:01 00:00:00.000001');
-> '-00:00:00.000001'

SELECT TIMEDIFF('2008-12-31 23:59:59.000001',


-> '2008-12-30 01:01:01.000002');
-> '46:58:57.999999'

TIMEDIFF()

With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments

TIMESTAMP(expr), 

TIMESTAMP(expr1,expr2)

SELECT TIMESTAMP('2003-12-31');
-> '2003-12-31 00:00:00'

SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');


TIMESTAMP() -> '2004-01-01 00:00:00'

Add an interval to a datetime expression

TIMESTAMPADD(unit,interval,datetime_expr)

Adds the integer expression interval to the date or datetime expression datetime_expr.

The unit for interval is given by the unit argument, which should be one of the following
values: MICROSECOND (microseconds), SECOND,MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02');
-> '2003-01-02 00:01:00'

SELECT TIMESTAMPADD(WEEK,1,'2003-01-02');
TIMESTAMPADD() -> '2003-01-09'

Subtract an interval from a datetime expression

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

Returns datetime_expr2 − datetime_expr1, where datetime_expr1 anddatetime_expr2 are date or datetime


expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time
part '00:00:00' where necessary

SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
TIMESTAMPDIFF() -> 128885

Return the date argument converted to days

TO_DAYS(date)

SELECT TO_DAYS('2007-10-07');
-> 733321

TO_DAYS() From 0000-00-00

TO_SECONDS() Return the date or datetime argument converted to seconds since Year 0

TO_SECONDS(expr)

Given a date or datetime expr, returns a the number of seconds since the year 0

SELECT TO_SECONDS('2009-11-29');
-> 63426672000
Return a Unix timestamp

UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned
integer.

If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-
01 00:00:00' UTC

The date argument may be a DATE, DATETIME, or TIMESTAMP string, or a number


in YYMMDD, YYMMDDHHMMSS, YYYYMMDD, orYYYYMMDDHHMMSS format

SELECT UNIX_TIMESTAMP();
-> 1447431666
SELECT UNIX_TIMESTAMP('2015-11-13 10:20:19');
-> 1447431619

mysql> SELECT UNIX_TIMESTAMP('1970-01-01 05:30:01');

+---------------------------------------+

| UNIX_TIMESTAMP('1970-01-01 05:30:01') |

+---------------------------------------+

| 1|

UNIX_TIMESTAMP() +---------------------------------------+

Return the current UTC date

Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format

UTC_DATE()
SELECT UTC_DATE()
-> '2003-08-14'
Return the current UTC time

UTC_TIME, UTC_TIME()

Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS.uuuuuuformat

UTC_TIME()
SELECT UTC_TIME();
-> '18:07:53'
Return the current UTC date and time

Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS'or YYYYMMDDHHMMSS.uuuuuu format

SELECT UTC_TIMESTAMP();
UTC_TIMESTAMP() -> '2003-08-14 18:08:04'

Return the week number

WEEK(date)

▪ If the week containing January 1 has 4 or more days in the new year, it is week 1.

▪ Otherwise, it is the last week of the previous year, and the next week is week 1.

SELECT WEEK('2008-02-20');
-> 7

WEEK()

WEEKDAY() Return the weekday index

WEEKDAY(date)

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).


SELECT WEEKDAY('2008-02-03 22:23:00');
-> 6

Return the calendar week of the date (1-53)

WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.

SELECT WEEKOFYEAR('2008-02-20');
WEEKOFYEAR() -> 8

Return the year

YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the “zero” date

SELECT YEAR('1987-01-01');
-> 1987

YEAR()

Return the year and week

YEARWEEK(date), YEARWEEK(date,mode)

Returns year and week for a date. 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

The mode argument works exactly like the mode argument to WEEK()

SELECT YEARWEEK('1987-01-01');
YEARWEEK() -> 198652

You might also like