MySQL 5.6 Cheatsheet (vers. 1.0)

MySQL 5.6 Cheatsheet (vers. 1.0)
Data Types
MySQL Column Data Types
BIGINT(x)
Integer
BLOB
string
CHAR(m)
string
DATE
date
DATETIME
date
DEC(m,d)
DECIMAL(m,d)
DOUBLE(m,d)
ENUM(‘Y,’N’,,...)
FIXED
FLOAT(m,d)
INT(m)
INTEGER(m)
integer
LONGBLOB
string
LONGTEXT
string
MEDIUMBLOB
string
MEDIUMINT(m)
integer
MEDIUMTEXT
string
NUMERIC
Same as
SET
string
SMALLINT(m)
integer
TEXT
string
TIME
time
TIMESTAMP
time
TYNYBLOB
string
TYNYINT(m)
integer
TYNYTEXT
string
VARCHAR(m)
string
YEAR
date
(*)
Logical Operators
AND
&&
OR
||
NOT
!
+/-9.223.372.036.854.775,807
Up to 65,535 characters
Up to 255 characters
Format YY-MM-DD
Format: YY-MM-DD HH:MM:SS
Synonym of
double precision stored as string (m+d
double precision floating number (m+d
String value restricted
Synonym of
Floating point decimal (m+d
Synonym of
(*)
+/-2,147,483,647
Up to 4,294,967,295 characters
Up to 4,294,967,295 characters
Up to 16,777,215 characters
(*)
+/-8,388,608
Up to 16,777,215 characters
DECIMAL
Can hold any number of strings
(*)
+/-32,767
Up to 5,535 characters
Format: HH:MM:SS
Format YY-MM-DD HH:MM:SS
Up to 255 characters
(*)
+/-127
Up to 255 characters
Up to 255 characters
4 digit year from 1901 to 2155
DECIMAL
digits)
digits)
to list
DECIMAL
digits)
INTEGER
Special:
SERIAL
Alias for: BIGINT UNSIGNED NOT NULL AUTO_INTREMENT, UNIQUE
(*) Can be declared as UNSIGNED, so that values start from 0.
m Is an integer value for the maxi display width or number of digits.
d Is an integer representing the number of decimal places.
Data Column Attributes
AUTO_INCREMENT
Next auto assigned numeric value
DEFAULT
Set column default value
NOT NULL
NULL is not allowed on column
NULL
NULL is allowed (default)
PRIMARY KEY
Assign primary key to column
UNSIGNED
Starts range at 0
Operators and Mathematical Functions
DIV
ABS(x)
CEILING(x)
CEIL(x)
CRC32(expr)
DEGREES(x)
EXP(x)
FORMAT(x,d)
GREATEST(x, y, z, …)
LEAST(x, y, z, …)
LN(x)
LOG(b, x)
Account management
CREATE USER `user_1`@`localhost` IDENTIFIED BY 'pwd';
SET PASSWORD FOR `user_1`@`localhost` = PASSWORD('mypass');
DROP USER `user_1`@`localhost`;
Show all MySQL Users
SELECT user, host, password FROM mysql.user;
Assign/Change Account Privileges
GRANT ALL ON test.* TO `user_1`@`localhost` = PASSWORD('mypass');
GRANT USAGE ON test.table TO `user_1`@`localhost` [WITH GRANT OPTION];
Table/View Operations
Create a New Table
Sample code with various data types declarations when creating a table
CREATE TABLE table_name (
item_id
INT(11) AUTO_INCREMENT PRIMARY KEY,
item_name VARCHAR(25),
provider_id INT(11),
status_id TINYINT)
ENGINE = MyIsam,
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
Add a Column
ALTER TABLE table_1 ADD COLUMN new_col MEDIUMTEXT;
Change Column Type
ALTER TABLE table_1 CHANGE col1 col_1 TEXT;
Remove a Column
ALTER TABLE table_1 DROP COLUMN col_1;
Rename Column
ALTER TABLE table_1 CHANGE col_3 col_4 TINYINT;
Rename a Table
ALTER TABLE table_1 RENAME TO table_2;
Add an Index to a column
CREATE INDEX index_name ADD INDEX(col_1);
Create/Drop a View
CREATE VIEW test.view_name AS SELECT * FROM table_name;
DROP VIEW view_name;
Describe a Table/View
EXPLAIN table_name;
EXPLAIN view_name;
EXPLAIN, DESCRIBE, DESC are synonyms.
Controls and Operators
IS NULL
IS NOT NULL
IFNULL(...)
String regular expression operator
Compares str1 and str2
Switch CASE expression
Check IF condition is TRUE or FALSE
If expr1 is not NULL,IFNULL() returns
expr1; otherwise it returns expr2
Returns NULL if expr1 = expr2 is true,
otherwise returns expr1
LOG2(x), LOG10(x)
MOD(n, m) / n%m / n MOD m
POW(x, y) / POWER(x, y)
RADIANS(x)
RAND(), RAND(n)
ROUND(x), ROUND(x, d)
SIGN(x)
SIN(x)
SQRT(x)
TAN(x)
TRUNCATE(x, d)
Data Manipulation
Select Records
SELECT * FROM `table_name` WHERE item_id = 1;
SELECT item_name, status_id FROM table_name WHERE status_id NOT IN (3, 4);
SELECT c.name, c.surname FROM customers AS c
INNER JOIN purchase AS a ON a.id_customer = c.id
WHERE a.price > 100
ORDER BY a.price DESC;
Insert Records
INSERT INTO `table_name` (`item_name`,`provider_id`) VALUES ('First Item', 123);
INSERT INTO `table_name` (SELECT * FROM other_table);
Update Records
UPDATE `table_name` SET item_name = ‘Old Item’, provider_id = 124 WHERE item_id = 1;
UPDATE `table_name` SET provider_id = provider_id + 1 WHERE item_id = 1;
UPDATE table_name SET item_name = (SELECT ext_item FROM ext_table WHERE id = 97);
Functions
User Management
Comparison for Text/String
expr LIKE ‘pattern’ [ESCAPE esc_char]
expr NOT LIKE ‘pattern’ [ESCAPE esc_char]
expr REGEXP ‘pattern’, expr RLIKE pattern
STRCMP(str1, str2)
NULLIF(expr1, expr2)
Delete Records
DELETE FROM `table_name` WHERE item_id = 1;
DELETE FROM `table_name` WHERE provider_id IN
Database Operations
Database Management
CREATE DATABASE [IF NOT EXISTS] test CHARSET utf8;
USE test;
DROP [IF EXISTS] DATABASE test;
Comparisons for Numeric
=
<>
!=
<=
>=
<=>
expr BETWEEN min AND max
expr IN (val1, val2…)
expr IS NOT IN (val1, val2...)
Flow Control
CASE expr
WHEN val THEN res1
WHEN val THEN res2
ELSE
res3
END
IF (condition, true_value, false_value)
IFNULL(expr1, expr2)
Logical AND
Logical OR
Logical NOT
Functions Date/Time
ADDDATE(date,INTERVAL,expr type)
ADDTIME(expr1, expr2)
CONVERT_TZ(dt, from_tz, to_tz)
CURDATE()
CURRENT_DATE(),CURRENT_DATE
CURRENT_TIME(),CURRENT_TIME
CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP
CURTIME()
DATE()
DATE_ADD(date,INTERVAL,expr type)
DATE_FORMAT(date, format)
DATE_SUB(date,INTERVAL,expr type)
DATEDIFF(expr, expr2)
DAY(date)
DAYNAME(date)
DAYOFMONTH(date)
DAYOFWEEK(date)
DAYOFYEAR(date)
EXTRACT(type, FROM date)
FROM_DAYS(n)
FROM_UNIXTIME(unix_timestamp)
GET_FORMAT({DATE|TIME|DATATIME},format)
HOUR(time)
LAST_DAY(date)
LOCALTIME(),LOCALTIME
LOCALTIMESTAMP,LOCALTIMESTAMP()
MAKEDATE(year, date_of_year)
MAKETIME(hour, minute, second)
MICROSECOND(expr)
MINUTE(time)
(1, 2, 4, 9);
MONTH(date)
MONTHNAME(date)
NOW()
PERIOD_ADD(p, n)
PERIOD_DIFF(p1, p2)
QUARTER(date)
SEC_TO_TIME(seconds)
SECOND(time)
STR_TO_DATE(str, format)
SUBDATE(date, INTERVAL expr unit)
SUBTIME(expr1, expr2)
SYSDATE()
TIME(expr)
TIME_FORMAT(time, format)
TIME_TO_SEC(time)
TIMEDIFF(expr1, expr2)
TIMESTAMP(expr), TIMESTAMP(expr1, expr2)
TIMESTAMPADD(unit,interval,datetime_expr2)
TIMESTAMPDIFF(unit,interval,datetime_expr2)
TO_DAYS(date)
TO_SECONDS(expr)
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
UTC_DATE()
UTC_TIME()
UTC_TIMESTAMP()
WEEK(date, mode)
WEEKDAY(date)
WEEKOFYEAR(date)
YEAR(date)
YEARWEEK(date)
Date/Time Specifier
%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), Sunday is the first day of the week;WEEK()
%u
Week (00..53), Monday is the first day of the week;WEEK()
%V
Week (01..53), Sunday is the first day of the week;WEEK()
%v
Week (01..53), Monday is the first day of the week;WEEK()
%W
Weekday name (Sunday..Saturday)
%w
Day of the week (0=Sunday..6=Saturday)
Copyright © 2017 Massimo Di Primio www.diprimio.com – All Rights Reserved
Version 1.0 – 2017-05-02 – Free for personal use
mode
mode
mode
mode
0
1
2; used with %X
3; used with %x
MySQL 5.6 Cheatsheet (vers. 1.0)
%X
%x
%Y
%y
%%
%x
Year for the week, Sunday 1st week day, numeric, four digits; used with %V
Year for the week, Monday 1st week day, numeric, four digits; used with %v
Year, numeric, four digits
Year, numeric (two digits)
A literal % character
x, for any “x” not listed above
String Functions
ASCII(str)
numeric value of left-most character
BIN(N)
string containing binary representation of a number
BIT_LENGTH(str)
length of argument in bits
CHAR(n)
the character for each integer passed
CHAR_LENGTH(str)
number of characters in argument
CHARACTER_LENGTH()
Synonym for CHAR_LENGTH()
CONCAT(str1,str2...)
concatenated string
CONCAT_WS(sep,str1,str2) concatenate with separator
ELT(N,str1,str2,...)
string at index number
EXPORT_SET(bit,on,off)
string for bit set
FIELD(str,str1,str2,...) the index (position) of str in str1, str1.. list
FIND_IN_SET(str,strlist) the index position of the first argument of strlist
FORMAT(X,D)
number formatted to specified number of decimal places
FROM_BASE64(str)
Decode to a base-64 string and return result
HEX(str)
hexadecimal representation of a decimal or string value
INSERT(str,pos,len,new)
Insert a substring at pos up to the specified len
INSTR(str,substr)
the index of the first occurrence of substring
LCASE(str)
Synonym for LOWER()
LEFT(str,sen)
Return the leftmost number of characters as specified
LENGTH(str)
Return the length of a string in bytes
LOAD_FILE(filename)
Load the named file
LOCATE(substr,str)
the position of the first occurrence of substring
LOWER(str)
Return the argument in lowercase
LPAD(str,len,pad)
string argument, left-padded with the specified string
LTRIM(str)
Remove leading spaces
MAKE_SET(bits,str1, ...) set of strings with the corresponding bit in bits set
MID(str,pos,len)
Return a substring starting from the specified position
OCT(N)
string containing octal representation of a number
OCTET_LENGTH(str)
Synonym for LENGTH()
ORD(str)
character code for leftmost character of the argument
POSITION(substr IN str)
Synonym for LOCATE()
QUOTE(str)
Escape the argument for use in an SQL statement
REPEAT(str,coount)
Repeat a string the specified number of times
REPLACE(str,from,to)
Replace occurrences of a specified string
REVERSE(str)
Reverse the characters in a string
RIGHT(str,len)
Return the specified rightmost number of characters
RPAD(str,len,pad)
Append string the specified number of times
RTRIM(str)
Remove trailing spaces
SOUNDEX(str)
Return a soundex string
expr1 SOUNDS LIKE expr2
Compare sounds
SPACE(N)
string of the specified number of spaces
STRCMP(str1,str2)
Compare two strings
SUBSTR(str,pos,len)
the substring as specified
SUBSTRING()
Alias for SUBSTR
SUBSTRING_INDEX(str,del, substring from a string before the specified number of
count)
occurrences of the delimiter
TO_BASE64(str)
the argument converted to a base-64 string
TRIM()
Remove leading and trailing spaces
UCASE(str)
Synonym for UPPER()
UNHEX(str)
string containing hex representation of a number
UPPER(str)
Convert to uppercase
WEIGHT_STRING(str)
the weight string for a string
Functions Aggregation
AVG([DISTINCTT], expr)
Return the average value of the argument
BIT_AND(expr)
Return bitwise AND
BIT_OR(expr)
Return bitwise OR
BIT_XOR(expr)
Return bitwise XOR
COUNT(expr)
Return a count of the number of rows returned
COUNT(DISTINCT expr,expr...)
Return the count of a number of different values
GROUP_CONCAT(expr)
Return a concatenated string
MAX(expr)
Return the maximum value
MIN(expr)
Return the minimum value
STD(expr)
Return the population standard deviation
STDDEV(expr)
Return the population standard deviation
STDDEV_POP(expr)
Return the population standard deviation
STDDEV_SAMP(expr)
Return the sample standard deviation
SUM([DISTINCT] expr)
Return the sum
VAR_POP(expr)
Return the population standard variance
VAR_SAMP(expr)
Return the sample variance
VARIANCE(expr)
Return the population standard variance
Information Functions: Information
BENCHMARK(count, expr)
Repeatedly execute an expression
CHARSET(str)
Return the character set of the argument
COERCIBILITY(str)
Return the collation coercibility value of the argument
COLLATION(str)
Return the collation of the string argument
CONNECTION_ID()
Return the connection ID (thread ID) for the connection
CURRENT_USER()
The authenticated user name and host name
CURRENT_USER
Alias for CURRENT_USER()
DATABASE()
Return the default (current) database name
FOUND_ROWS()
Return the number of rows as if no LIMIT clause
LAST_INSERT_ID(expr)
Value of the AUTOINCREMENT column for the last INSERT
ROW_COUNT()
The number of rows updated
SCHEMA()
Synonym for DATABASE()
SESSION_USER()
Synonym for USER()
SYSTEM_USER()
Synonym for USER()
USER()
The user name and host name provided by the client
VERSION()
Return a string that indicates the MySQL server version
Functions: Miscellaneous
DEFAULT(col)
Return the default value for a table column
GET_LOCK(str,timeout)
Get a named lock
INET_ATON(expr)
Return the numeric value of an IP address
INET_NTOA(expr)
Return the IP address from a numeric value
INET6_ATON(expr)
Return the numeric value of an IPv6 address
INET6_NTOA(expr)
Return the IPv6 address from a numeric value
IS_FREE_LOCK(expr)
Whether the named lock is free
IS_IPV4(expr)
Whether argument is an IPv4 address
IS_IPV4_COMPAT(expr)
Whether argument is an IPv4-compatible address
IS_IPV4_MAPPED(expr)
Whether argument is an IPv4-mapped address
IS_IPV6(expr)
Whether argument is an IPv6 address
IS_USED_LOCK(str)
Whether the named lock is in use; return connection id if true
MASTER_POS_WAIT(log,pos) Block until the slave has read and applied all updates
NAME_CONST(name,value) Causes the column to have the given name
DEFAULT(col)
Return the default value for a table column
RAND([N])
Return a random floating-point value
RELEASE_LOCK(str)
Releases the named lock
SLEEP(seconds)
Sleep for a number of seconds
UUID()
Return a Universal Unique Identifier (UUID)
UUID_SHORT()
Return an integer-valued universal identifier
VALUES(column)
Defines the values to be used during an INSERT
Function Compressing/Encryption
AES_DECRYPT(crypt_str, key_str)
Decrypt using AES
AES_ENCRYPT(str, key_str)
Encrypt using AES
ASYMMETRIC_DECRYPT(pub_key,priv_key)
Decrypt ciphertext using priv.or pub. key
ASYMMETRIC_DERIVE(@pub1, @priv2)
Derive symmetric key from asymmetric keys
ASYMMETRIC_ENCRYPT(algrthm,str,key)
Encrypt cleartext using private or public key
ASYMMETRIC_SIGN(algrthm,digest,pkey,type) Generate signature from digest
ASYMMETRIC_VERIFY(alg,dig,sig,pubk,dtype) Verify that signature matches digest
COMPRESS()
Return result as a binary string
CREATE_ASYMMETRIC_PRIV_KEY(algorithm)
Create private key
CREATE_ASYMMETRIC_PUB_KEY(algorithm,pkey) Create public key
CREATE_DH_PARAMETERS(key_len)
Generate shared DH secret
CREATE_DIGEST(digest_type,str)
Generate digest from string
DECODE()
Decodes a string encrypted using ENCODE()
DES_DECRYPT()
Decrypt a string
DES_ENCRYPT()
Encrypt a string
ENCODE()
Encode a string
ENCRYPT()
Encrypt a string
MD5()
Calculate MD5 checksum
OLD_PASSWORD()(deprec. 5.6.5)
Return the pre-4.1 implementation of PASSWORD
PASSWORD()
Calculate and return a password string
RANDOM_BYTES()
Return a random byte vector
SHA1(),SHA()
Calculate an SHA-1 160-bit checksum
SHA2()
Calculate an SHA-2 checksum
UNCOMPRESS()
Uncompress a string compressed
Return the length of a string before
UNCOMPRESSED_LENGTH()
compression
VALIDATE_PASSWORD_STRENGTH()
Determine strength of password
Procedure/Function Operations
Create Procedure
DELIMITER //
CREATE PROCEDURE p1 ()
BEGIN
DECLARE fanta INT DEFAULT 55;
DROP TABLE test_table;
LOOP
INSERT INTO other_table (item_name) VALUES (‘smartphone’);
END LOOP;
END//
DELIMITER ;
Show Operations
Common Show Operations
SHOW [GLOBAL | SESSION] VARIABLES [LIKE ‘pattern’];
SHOW STATUS LIKE ‘pattern’;
SHOW CHARACTER SET;
SHOW COLUMN FROM table [FROM db] [LIKE ‘pattern’ | WERE ‘expr’];
SHOW FIELDS FROM table [FROM db] [LIKE ‘pattern’ | WERE ‘expr’];
SHOW PRIVILEGES;
SHOW [FULL] PROCESSLIST;
SHOW GRANTS [FOR user@host];
SHOW [GLOBAL | SESSION] STATUS;
SHOW CREATE DATABASE db_name;
SHOW DATABASES LIKE ‘pattern’;
SHOW TABLES;
SHOW TABLE STATUS [FROM db] [LIKE ‘pattern’ | WERE ‘expr’];
SHOW CREATE TABLE table_name;
SHOW CREATE VIEW view_name;
SHOW OPEN TABLES [FROM db | LIKE ‘pattern’];
SHOW [FULL] COLUMNS FROM table [FROM db | LIKE ‘pattern’];
SHOW INDEX FROM table [FROM db_db];
SHOW [GLOBAL | SESSION] VARIABLES [LIKE ‘pattern’];
Master/Slave Replication
Show Replication Master/Slave
SHOW RELAYLOG EVENTS
SHOW MASTER STATUS
SHOW BINLOG EVENTS
SHOW SLAVE HOST
SHOW SLAVE STATUS
PURGE {BINARY | MASTER} LOGS
RESET MASTER
RESET SLAVE
START SLAVE
STOP SLAVE
Master/Slave Common Operations
CHANGE MASTER TO master_def, master_def …
master_def:
MASTER_HOST = ‘hostname’
| MASTER_USER = ‘username’
| MASTER_PASSWORD = ‘password
| MASTER_PORT = port_num
| MASTER_CONNECT_RETRY = count
| MASTER_LOG_FILE = ‘master_log_filename’
| MASTER_LOG_POS = master_log_pos
Tips’n-tricks
Verify & Repair Tables
$ mysqlcheck -u user_1 -pmypass --quick --d test
$ mysqlcheck -u user_1 -pmypass --quick --database test
$ mysqlcheck -u root –ppasswd --extended --all-databases
Repair Corrupted tables
$ myisamchk --quick --update-state /var/lib/mysql/test/*.MYI
Start MySQL wit no permissions and no Network(root password lost)
$ mysqld-safe
--skip-grant-tables \
--skip-networking \
--user=mysql &
$ mysql -u root
mysql> UPDATE mysql.user SET Passwort=PASSWORD(‘pwd’) WHERE user = ‘root’;
$ mysqlddmin -u root shutdown
$ /etc/init.d/mysql start
Kill a process
mysql> kill thead_id
Remove specific processes
$ mysl-zap [-signal] [-?Ift] pattern
Copyright © 2017 Massimo Di Primio www.diprimio.com – All Rights Reserved
Version 1.0 – 2017-05-02 – Free for personal use