You are on page 1of 2

MySQL Cheat Sheet

MySQL is a popular open-source relational database


management system known for its ease of use and scalability. CREATING TABLES QUERYING DATA INSERTING DATA
Sometimes, you will need a little help while working on a project. To create a table: To select data from a table, use the SELECT command. To insert data into a table, use the INSERT command:
That's why we created this MySQL Cheat Sheet. CREATE TABLE habitat ( An example of a single-table query: INSERT INTO habitat VALUES
id INT, SELECT species, AVG(age) AS average_age (1, 'River'),
Instructions for installing MySQL are available at: name VARCHAR(64) FROM animal (2, 'Forest');
https://dev.mysql.com ); WHERE id != 3
GROUP BY species
Use AUTO_INCREMENT to increment the ID automatically with HAVING AVG(age) > 3 You may specify the columns in which the data is added. The
CONNECTING TO A MYSQL SERVER each new record. An AUTO_INCREMENT column must be defined ORDER BY AVG(age) DESC; remaining columns are filled with default values or NULLs.
Connect to a MySQL server with a username and a password as a primary or unique key: INSERT INTO habitat (name) VALUES
using the mysql command-line client. CREATE TABLE habitat ( An example of a multiple-table query: ('Savanna');
MySQL will prompt for the password: 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 specific database on a MySQL server using a To update the data in a table, use the UPDATE command:
username and a password: Use +, -, *, / to do some basic math. UPDATE animal
mysql -u [username] -p [database] To create a table with a foreign key:
CREATE TABLE animal ( To get the number of seconds in a week: SET
id INT PRIMARY KEY AUTO_INCREMENT, SELECT 60 * 60 * 24 * 7; -- result: 604800 species = 'Duck',
To export data using the mysqldump tool: name = 'Quack'
name VARCHAR(64),
mysqldump -u [username] -p \
[database] > data_backup.sql
species VARCHAR(64), AGGREGATION AND GROUPING WHERE id = 2;
age INT, AVG(expr) − average value of expr for the group.
habitat_id INT, COUNT(expr) − count of expr values within the group.
To exit the client:
quit or exit
FOREIGN KEY (habitat_id) MAX(expr) − maximum value of expr values within the DELETING DATA
REFERENCES habitat(id) group. To delete data from a table, use the DELETE command:
); MIN(expr) − minimum value of expr values within the
For a full list of commands: DELETE FROM animal
help group. WHERE id = 1;
MODIFYING TABLES SUM(expr) − sum of expr values within the group.

CREATING AND DISPLAYING Use the ALTER TABLE statement to modify the table structure. To count the rows in the table: This deletes all rows satisfying the WHERE condition.
SELECT COUNT(*) To delete all data from a table, use the TRUNCATE TABLE
DATABASES To change a table name:
ALTER TABLE animal RENAME pet;
FROM animal; statement:
To create a database: TRUNCATE TABLE animal;
To count the non-NULL values in a column:
CREATE DATABASE zoo;
To add a column to the table: SELECT COUNT(name)
ALTER TABLE animal FROM animal;
To list all the databases on the server:
SHOW DATABASES;
ADD COLUMN name VARCHAR(64); CASTING
To count unique values in a column: From time to time, you need to change the type of a value.
To change a column name: SELECT COUNT(DISTINCT name) Use the CAST() function to do this.
To use a specified database: ALTER TABLE animal FROM animal; In MySQL, you can cast to these data types:
USE zoo; RENAME COLUMN id TO identifier; CHAR NCHAR BINARY DATE DATETIME
GROUP BY DECIMAL DOUBLE FLOAT REAL SIGNED
To delete a specified database: To change a column data type: To count the animals by species: UNSIGNED TIME YEAR JSON spatial_type
DROP DATABASE zoo; ALTER TABLE animal SELECT species, COUNT(id)
MODIFY COLUMN name VARCHAR(128); FROM animal
To list all tables in the database: GROUP BY species; To get a number as a signed integer:
SHOW TABLES; To delete a column: SELECT CAST(1234.567 AS signed);
ALTER TABLE animal To get the average, minimum, and maximum ages by habitat: -- result: 1235
To get information about a specified table: DROP COLUMN name; SELECT habitat_id, AVG(age),
DESCRIBE animal; MIN(age), MAX(age)
It outputs column names, data types, default values, and more To delete a table: FROM animal To change a column type to double:
about the table. DROP TABLE animal; GROUP BY habitat_id; SELECT CAST(column AS double);

LearnSQL.com is owned by Vertabelo SA


Try out the interactive SQL from A to Z in MySQL course at LearnSQL.com, and check out our other SQL courses. vertabelo.com | CC BY-NC-ND Vertabelo SA
MySQL Cheat Sheet
TEXT FUNCTIONS NUMERIC FUNCTIONS DATE AND TIME EXTRACTING PARTS OF DATES
To extract a part of a date, use the functions YEAR, MONTH, WEEK,
FILTERING THE OUTPUT To get the remainder of a division: There are 5 main time-related types in MySQL:
DAY, HOUR, and so on.
SELECT MOD(13, 2); -- result: 1 DATE TIME DATETIME TIMESTAMP YEAR
To fetch the city names that are not Berlin: SELECT YEAR(CAST('2021-12-31' AS date));
SELECT name To round a number to its nearest integer: DATE – stores the year, month, and day in the YYYY-MM-DD -- result: 2021
FROM city SELECT ROUND(1234.56789); -- result: 1235 format. SELECT MONTH(CAST('2021-12-31' AS date));
WHERE name != 'Berlin'; TIME – stores the hours, minutes, and seconds in the HH:MM:SS -- result: 12
To round a number to three decimal places:
format. SELECT DAY(CAST('2021-12-31' AS date));
TEXT OPERATORS SELECT ROUND(1234.56789, 3);
-- result: 31
To fetch the city names that start with a 'P' or end with an 's': -- result: 1234.568 DATETIME – stores the date and time in the YYYY-MM-DD
SELECT name HH:MM:SS format. The supported range is '1000-01-01
To round a number up:
FROM city
SELECT CEIL(13.1); -- result: 14
00:00:00' to '9999-12-31 23:59:59'. DATE ARITHMETICS
WHERE name LIKE 'P%' OR name LIKE '%s'; TIMESTAMP – stores the date and time. The range is '1970- To add or subtract an interval from a DATE, use the ADDDATE()
SELECT CEIL(-13.9); -- result: -13
To fetch the city names that start with any letter followed by 01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. function:
The CEIL(x) function returns the smallest integer not less than ADDDATE('2021-10-31', INTERVAL 2 MONTH);
'ublin' (like Dublin in Ireland or Lublin in Poland): MySQL converts TIMESTAMP values from the current time zone
x. To round the number down: -- result: '2021-12-31'
SELECT name to UTC for storage, and back from UTC to the current time zone
SELECT FLOOR(13.8); -- result: 13 ADDDATE('2014-04-05', INTERVAL -3 DAY);
FROM city for retrieval.
SELECT FLOOR(-13.2); -- result: -14 -- result: '2014-04-02'
WHERE name LIKE '_ublin'; YEAR – stores the year in the YYYY format.
The FLOOR(x) function returns the greatest integer not greater
CONCATENATION than x. To round towards 0 irrespective of the sign of a number: INTERVALS To add or subtract an interval from a TIMESTAMP or DATETIME,
Use the CONCAT() function to concatenate two strings:
SELECT TRUNCATE(13.56, 0); -- result: 13 An interval is the duration between two points in time. use the TIMESTAMPADD() function:
SELECT CONCAT('Hi ', 'there!');
SELECT TRUNCATE(-13.56, 1); -- result: -13.5 To define an interval: INTERVAL 1 DAY TIMESTAMPADD(MONTH, 2,
-- result: Hi there!
This syntax consists of the INTERVAL keyword, a value, and a '2014-06-10 07:55:00');
To get the absolute value of a number:
If any of the string is NULL, the result is NULL: time part keyword (YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, -- result: '2014-08-10 07:55:00'
SELECT ABS(-12); -- result: 12
SELECT CONCAT(Great ', 'day', NULL); MINUTE, SECOND, MICROSECOND). TIMESTAMPADD(MONTH, -2,
-- result: NULL To get the square root of a number: '2014-06-10 07:55:00');
You may combine different INTERVALs using the + or -
MySQL allows specifying a separating character (separator) using SELECT SQRT(9); -- result: 3 operator: -- result: '2014-04-10 07:55:00'
the CONCAT_WS() function. The separator is placed between INTERVAL 1 YEAR + INTERVAL 3 MONTH
the concatenated values: USEFUL NULL FUNCTIONS You may also use the standard SQL syntax: To add or subtract TIME from a DATETIME, use the ADDTIME()
SELECT CONCAT_WS(' ', 1, 'Olivier', To fetch the names of the cities whose rating values are not INTERVAL '1-3' YEAR_MONTH function:
'Norris'); -- result: 1 Olivier Norris missing: -- 1 year and 3 months ADDTIME('2018-02-12 10:20:24', '12:43:02');
SELECT name INTERVAL '3-12' HOUR_MINUTE -- result: '2018-02-12 23:03:26'
OTHER USEFUL TEXT FUNCTIONS FROM city -- 3 hours 12 minutes ADDTIME('2018-02-12 10:20:24', '-12:43:02');
To get the count of characters in a string: -- result: '2018-02-11 21:37:22'
WHERE rating IS NOT NULL;
SELECT LENGTH('LearnSQL.com'); WHAT TIME IS IT?
-- result: 12 COALESCE(x, y, ...) To answer this question, use:
To find the difference between two dates, use the DATEDIFF()
To convert all letters to lowercase: To replace NULL in a query with something meaningful: CURRENT_TIME or CURTIME – to get the current time.
function:
SELECT LOWER('LEARNSQL.COM'); SELECT domain, CURRENT_DATE or CURDATE – to get the current date.
DATEDIFF('2015-01-01', '2014-01-02');
-- result: learnsql.com COALESCE(domain, 'domain missing') NOW() or CURRENT_TIMESTAMP – to get the current
-- result: 364
FROM contacts; timestamp with both of the above.
To convert all letters to uppercase:
The COALESCE() function takes any number of arguments and
SELECT UPPER('LearnSQL.com');
returns the value of the first argument that is not NULL.
CREATING VALUES To find the difference between two times, use the TIMEDIFF()
-- result: LEARNSQL.COM To create a date, time, or datetime, write the value as a string and function:
To get just a part of a string: NULLIF(x, y) cast it to the proper type. SELECT TIMEDIFF('09:30:00', '07:55:00');
SELECT SUBSTRING('LearnSQL.com', 9); To save yourself 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 datetimes (in a given unit of
-- result: Learn / NULLIF(last_month, 0) You may skip casting in simple conditions; the database knows time), use the TIMESTAMPDIFF() function. Here's an example
To replace a part of a string: AS better_by_percent what you mean. 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 NULL if x equals y, else it FROM airport_schedule WEEK, '2018-02-26', '2018-03-21'
-- result: LearnPython.com returns the value of x value. WHERE departure_time < '12:00'; ); -- result: 3

LearnSQL.com is owned by Vertabelo SA


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

You might also like