You are on page 1of 2

MySQL Cheat Sheet

MySQL is a popular open-s ource relational databas e


m anagem ent s ys tem known for its eas e of us e and s calability. CREATING TABLES QUERYING DATA INSERTING DATA
Som etim es , you will need a little help while working on a To create a table: To s elect data from a table, us e the SELECT com m and. To ins ert data into a table, us e the INSERT com m and:
project. That's why we created this MySQL Cheat Sheet. CREATE TABLE habitat ( An exam ple of a s ingle-table query: INSERT INTO habitat VALUES
id INT, SELECT species, AVG(age) AS average_age (1, 'River'),
Ins tructions for ins talling MySQL are available at: name VARCHAR(64) FROM animal (2, 'Forest');
https ://dev.m ys ql.com ); WHERE id != 3
GROUP BY species
U s e AUTO_INCREMENT to increm ent the ID autom atically HAVING AVG(age) > 3 You m ay s pecify the colum ns in which the data is added. The
CONNECTING TO A MYSQL SERVER with each new record. An AUTO_INCREMENT colum n m us t ORDER BY AVG(age) DESC; rem aining colum ns are filled with default values or NULL s .
Connect to a MySQL s erver with a us ernam e and a pas s word be defined as a prim ary or unique key: INSERT INTO habitat (name) VALUES
us ing the m ys ql com m and-line client. CREATE TABLE habitat ( An exam ple of a m ultiple-table query: ('Savanna');
MySQL will prom pt for the pas s word: id INT PRIMARY KEY AUTO_INCREMENT, SELECT city.name, country.name
mysql -u [username] -p name VARCHAR(64) FROM city
); [INNER | LEFT | RIGHT] JOIN country
ON city.country_id = country.id; UPDATING DATA
To connect to a s pecific databas e on a MySQL s erver us ing a To update the data in a table, us e the U PDATE com m and:
us ernam e and a pas s word: U s e + , - , * , / to do s om e bas ic m ath. UPDATE animal
To create a table with a foreign key:
mysql -u [username] -p [database] CREATE TABLE animal ( To get the num ber of s econds in a week: SET
id INT PRIMARY KEY AUTO_INCREMENT, SELECT 60 * 60 * 24 * 7; -- result: 604800 species = 'Duck',
To export data us ing the mysqldump tool: name VARCHAR(64), name = 'Quack'
mysqldump -u [username] -p \ WHERE id = 2;
[database] > data_backup.sql
species VARCHAR(64),
age INT,
AGGREGATION AND GROUPING
habitat_id INT, AVG(expr) − average value of expr for the group.
To exit the client: FOREIGN KEY (habitat_id) COUNT(expr) − count of expr values within the group.
quit or exit REFERENCES habitat(id) MAX(expr) − m axim um value of expr values within the DELETING DATA
group. To delete data from a table, us e the DELETE com m and:
);
For a full lis t of com m ands : MIN(expr) − m inim um value of expr values within the DELETE FROM animal
help group. WHERE id = 1;
MODIFYING TABLES SUM(expr) − s um of expr values within the group.
U s e the ALTER TABLE s tatem ent to m odify the table
CREATING AND DISPLAYING s tructure. To count the rows in the table: This deletes all rows s atis fying the WHERE condition.
SELECT COUNT(*) To delete all data from a table, us e the TRUNCATE TABLE
DATABASES To change a table nam e: FROM animal; s tatem ent:
To create a databas e: ALTER TABLE animal RENAME pet; TRUNCATE TABLE animal;
To count the non-N U LL values in a colum n:
CREATE DATABASE zoo;
To add a colum n to the table: SELECT COUNT(name)
ALTER TABLE animal FROM animal;
To lis t all the databas es on the s erver:
SHOW DATABASES; ADD COLUMN name VARCHAR(64); CASTING
To count unique values in a colum n: From tim e to tim e, you need to change the type of a value.
To change a colum n nam e:
SELECT COUNT(DISTINCT name) U s e the CAST() function to do this .
To us e a s pecified databas e: FROM animal;
ALTER TABLE animal In MySQL, you can cas t to thes e data types :
USE zoo;
RENAME COLUMN id TO identifier; CHAR NCHAR BINARY DATE DATETIME
GROUP BY DECIMAL DOUBLE FLOAT REAL SIGNED
To delete a s pecified databas e: To count the anim als by s pecies : UNSIGNED TIME YEAR JSON spatial_type
To change a colum n data type:
DROP DATABASE zoo; ALTER TABLE animal SELECT species, COUNT(id)
MODIFY COLUMN name VARCHAR(128); FROM animal
To lis t all tables in the databas e: GROUP BY species; To get a num ber as a s igned integer:
SHOW TABLES; To delete a colum n: SELECT CAST(1234.567 AS signed);
ALTER TABLE animal To get the average, m inim um , and m axim um ages by habitat: -- result: 1235
To get inform ation about a s pecified table: DROP COLUMN name; SELECT habitat_id, AVG(age),
DESCRIBE animal; MIN(age), MAX(age)
It outputs colum n nam es , data types , default values , and m ore To delete a table: FROM animal To change a colum n type to double:
about the table. DROP TABLE animal; GROUP BY habitat; SELECT CAST(column AS double);

Le a rnSQL.com is owne d by Ve rta be lo SA


Try out the interactive SQL from A to Z in MySQL course at LearnSQL.com, and check out our other SQL courses. ve rta be lo.com | CC BY-NC-ND Ve rta be lo SA
MySQL Cheat Sheet
TEXT FUNCTIONS NUMERIC FUNCTIONS DATE AND TIME EXT RACT ING PART S OF DAT ES
To get the rem ainder of a divis ion: There are 5 m ain tim e-related types in MySQL:
To extract a part of a date, us e the functions YEAR , MONTH ,
FILT ERING T HE OUT PUT WEEK , DAY , HOUR , and s o on.
To fetch the city nam es that are not Berlin:
SELECT MOD(13, 2); -- result: 1 DATE TIME DATETIME TIMESTAMP YEAR
SELECT YEAR(CAST('2021-12-31' AS date));
SELECT name To round a num ber to its neares t integer: DATE – s tores the year, m onth, and day in the YYYY-MM-DD -- result: 2021
FROM city SELECT ROUND(1234.56789); -- result: 1235 form at. SELECT MONTH(CAST('2021-12-31' AS date));
WHERE name != 'Berlin'; To round a num ber to three decim al places : TIME – s tores the hours , m inutes , and s econds in the -- result: 12
T EXT OPERAT ORS SELECT ROUND(1234.56789, 3); HH:MM:SS form at. SELECT DAY(CAST('2021-12-31' AS date));
-- result: 1234.568 -- result: 31
To fetch the city nam es that s tart with a 'P' or end with an DATETIME – s tores the date and tim e in the YYYY-MM-DD
's' : To round a num ber up: HH:MM:SS form at. The s upported range is '1000-01-01
SELECT name SELECT CEIL(13.1); -- result: 14 00:00:00' to '9999-12-31 23:59:59' . DAT E ARIT HMET ICS
FROM city SELECT CEIL(-13.9); -- result: -13 To add or s ubtract an interval from a DATE , us e the
TIMESTAMP – s tores the date and tim e. The range is '1970-
WHERE name LIKE 'P%' OR name LIKE '%s'; The CEIL(x) function returns the s m alles t integer not les s ADDDATE() function:
01-01 00:00:01' U TC to '2038-01-19 03:14:07'
To fetch the city nam es that s tart with any letter followed by than x . To round the num ber down: ADDDATE('2021-10-31', INTERVAL 2 MONTH);
U TC. MySQL converts TIMESTAMP values from the current
'ublin' (like Dublin in Ireland or Lublin in Poland): SELECT FLOOR(13.8); -- result: 13 -- result: '2021-12-31'
tim e z one to U TC for s torage, and back from U TC to the current
SELECT name SELECT FLOOR(-13.2); -- result: -14 ADDDATE('2014-04-05', INTERVAL -3 DAY);
tim e z one for retrieval.
FROM city -- result: '2014-04-02'
The FLOOR(x) function returns the greates t integer not YEAR – s tores the year in the YYYY form at.
WHERE name LIKE '_ublin'; greater than x . To round towards 0 irres pective of the s ign of a To add or s ubtract an interval from a TIMESTAMP or
CONCAT ENAT ION num ber: INT ERVALS DATETIME , us e the TIMESTAMPADD() function:
U s e the CONCAT() function to concatenate two s trings : SELECT TRUNCATE(13.56, 0); -- result: 13 An interval is the duration between two points in tim e. TIMESTAMPADD(MONTH, 2,
SELECT CONCAT('Hi ', 'there!'); SELECT TRUNCATE(-13.56, 1); -- result: To define an interval: INTERVAL 1 DAY '2014-06-10 07:55:00');
-- result: Hi there! -13.5 This s yntax cons is ts of the INTERVAL keyword, a value, and a -- result: '2014-08-10 07:55:00'
To get the abs olute value of a num ber: tim e part keyword (YEAR , QUARTER , MONTH , WEEK , DAY , TIMESTAMPADD(MONTH, -2,
If any of the s tring is NULL , the res ult is NULL :
SELECT ABS(-12); -- result: 12 HOUR , MINUTE , SECOND , MICROSECOND ). '2014-06-10 07:55:00');
SELECT CONCAT(Great ', 'day', NULL);
-- result: NULL To get the s quare root of a num ber: You m ay com bine different INTERVAL s us ing the + or - -- result: '2014-04-10 07:55:00'
SELECT SQRT(9); -- result: 3 operator:
MySQL allows s pecifying a s eparating character (s eparator)
us ing the CONCAT_WS() function. The s eparator is placed
INTERVAL 1 YEAR + INTERVAL 3 MONTH To add or s ubtract TIME from a DATETIME , us e the
between the concatenated values : USEFUL NULL FUNCTIONS You m ay als o us e the s tandard SQL s yntax: ADDTIME() function:
SELECT CONCAT_WS(' ', 1, 'Olivier', To fetch the nam es of the cities whos e rating values are not
INTERVAL '1-3' YEAR_MONTH ADDTIME('2018-02-12 10:20:24',
'Norris'); -- result: 1 Olivier Norris m is s ing:
-- 1 year and 3 months '12:43:02');
SELECT name INTERVAL '3-12' HOUR_MINUTE -- result: '2018-02-12 23:03:26'
OT HER USEFUL T EXT FUNCT IONS FROM city -- 3 hours 12 minutes ADDTIME('2018-02-12 10:20:24',
To get the count of characters in a s tring:
WHERE rating IS NOT NULL; '-12:43:02');
SELECT LENGTH('LearnSQL.com'); WHAT T IME IS IT ? -- result: '2018-02-11 21:37:22'
-- result: 12 COALESCE(x, y, ...) To ans wer this ques tion, us e:
To replace NULL in a query with s om ething m eaningful:
CURRENT_TIME or CURTIME – to get the current tim e. To find the difference between two dates , us e the DATEDIFF()
To convert all letters to lowercas e:
SELECT domain, CURRENT_DATE or CURDATE – to get the current date. function:
SELECT LOWER('LEARNSQL.COM');
COALESCE(domain, 'domain missing') NOW() or CURRENT_TIMESTAMP – to get the current DATEDIFF('2015-01-01', '2014-01-02');
-- result: learnsql.com
tim es tam p with both of the above. -- result: 364
To convert all letters to uppercas e: FROM contacts;
SELECT UPPER('LearnSQL.com'); The COALESCE() function takes any num ber of argum ents CREAT ING VALUES
and returns the value of the firs t argum ent that is not NULL . To find the difference between two tim es , us e the
-- result: LEARNSQL.COM To create a date, tim e, or datetim e, write the value as a s tring TIMEDIFF() function:
To get jus t a part of a s tring: NULLIF(x, y) and cas t it to the proper type. SELECT TIMEDIFF('09:30:00', '07:55:00');
SELECT SUBSTRING('LearnSQL.com', 9); To s ave yours elf from division by 0 errors : SELECT CAST('2021-12-31' AS date), -- result: '01:35:00'
-- result: .com SELECT last_month, this_month, CAST('15:31' AS time),
SELECT SUBSTRING('LearnSQL.com', 1, 5); this_month * 100.0 CAST('2021-12-31 23:59:29' AS datetime); To find the difference between two datetim es (in a given unit of
-- result: Learn / NULLIF(last_month, 0) You m ay s kip cas ting in s im ple conditions ; the databas e tim e), us e the TIMESTAMPDIFF() function. Here's an
To replace a part of a s tring: AS better_by_percent knows what you m ean. exam ple with the difference given in weeks :
SELECT REPLACE('LearnSQL.com', 'SQL', FROM video_views; SELECT airline, flight_no, departure_time SELECT TIMESTAMPDIFF(
'Python'); The NULLIF(x, y) function returns N U LL if x equals y , FROM airport_schedule WEEK, '2018-02-26', '2018-03-21'
-- result: LearnPython.com els e it returns the value of x value. WHERE departure_time < '12:00'; ); -- result: 3

Le a rnSQL.com is owne d by Ve rta be lo SA


Try out the interactive SQL from A to Z in MySQL course at LearnSQL.com, and check out our other SQL courses. ve rta be lo.com | CC BY-NC-ND Ve rta be lo SA

You might also like