Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL Cheetsheet

Download as pdf or txt
Download as pdf or txt
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 To create a table: To select data from a table, use the SELECT command. To insert data into a table, use the INSERT command:
project. 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 HAVING AVG(age) > 3 You may specify the columns in which the data is added. The
CONNECTING TO A MYSQL with each new record. An AUTO_INCREMENT column must ORDER BY AVG(age) DESC; remaining columns are filled with default values or NULLs.
be defined as a primary or unique key: INSERT INTO habitat (name) VALUES
SERVER CREATE TABLE habitat ( An example of a multiple-table query: ('Savanna');
Connect to a MySQL server with a username and a password id INT PRIMARY KEY AUTO_INCREMENT, SELECT city.name, country.name
using the mysql command-line client. name VARCHAR(64) FROM city
MySQL will prompt for the password: ); [INNER | LEFT | RIGHT] JOIN country
mysql -u [username] -p ON city.country_id = country.id; UPDATING DATA
To update the data in a table, use the UPDATE command:
To connect to a specific database on a MySQL server using a To create a table with a foreign key: Use +, -, *, / to do some basic math. UPDATE animal
username and a password: CREATE TABLE animal ( To get the number of seconds in a week: SET
mysql -u [username] -p [database] id INT PRIMARY KEY AUTO_INCREMENT, SELECT 60 * 60 * 24 * 7; -- result: 604800 species = 'Duck',
name VARCHAR(64), name = 'Quack'
species VARCHAR(64), WHERE id = 2;
To export data using the mysqldump tool:
mysqldump -u [username] -p \ age INT, AGGREGATION AND GROUPING
[database] > data_backup.sql habitat_id INT, AVG(expr) − average value of expr for the group.
FOREIGN KEY (habitat_id) COUNT(expr) − count of expr values within the group.
To exit the client: REFERENCES habitat(id) MAX(expr) − maximum value of expr values within the DELETING DATA
quit or exit ); group. To delete data from a table, use the DELETE command:
MIN(expr) − minimum value of expr values within the DELETE FROM animal
group. WHERE id = 1;
For a full list of commands:
help
MODIFYING TABLES SUM(expr) − sum of expr values within the group.
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.
CREATING AND DISPLAYING SELECT COUNT(*) To delete all data from a table, use the TRUNCATE TABLE
To change a table name: FROM animal; statement:
DATABASES ALTER TABLE animal RENAME pet; TRUNCATE TABLE animal;
To create a database: 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: ADD COLUMN name VARCHAR(64); CASTING
SHOW DATABASES; 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 To delete a table: FROM animal To change a column type to double:
more 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,
FILTERING THE OUTPUT To get the remainder of a division: There are 5 main time-related types in MySQL:
WEEK, 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'; -- result: 12
To round a number to three decimal places: TIME – stores the hours, minutes, and seconds in the
SELECT DAY(CAST('2021-12-31' AS date));
TEXT OPERATORS SELECT ROUND(1234.56789, 3); HH:MM:SS format.
-- result: 31
To fetch the city names that start with a 'P' or end with an -- result: 1234.568
DATETIME – stores the date and time in the YYYY-MM-DD
's': To round a number up: HH:MM:SS format. The supported range is '1000-01-01
SELECT name SELECT CEIL(13.1); -- result: 14 00:00:00' to '9999-12-31 23:59:59'.
DATE ARITHMETICS
FROM city SELECT CEIL(-13.9); -- result: -13 To add or subtract an interval from a DATE, use the
WHERE name LIKE 'P%' OR name LIKE '%s'; TIMESTAMP – stores the date and time. The range is ADDDATE() function:
The CEIL(x) function returns the smallest integer not less '1970-01-01 00:00:01' UTC to '2038-01-19 ADDDATE('2021-10-31', INTERVAL 2 MONTH);
To fetch the city names that start with any letter followed by
than x. To round the number down: 03:14:07' UTC. MySQL converts TIMESTAMP values from -- result: '2021-12-31'
'ublin' (like Dublin in Ireland or Lublin in Poland):
SELECT FLOOR(13.8); -- result: 13 the current time zone to UTC for storage, and back from UTC ADDDATE('2014-04-05', INTERVAL -3 DAY);
SELECT name
SELECT FLOOR(-13.2); -- result: -14 to the current time zone for retrieval. -- result: '2014-04-02'
FROM city
WHERE name LIKE '_ublin'; The FLOOR(x) function returns the greatest integer not YEAR – stores the year in the YYYY format.
greater than x. To round towards 0 irrespective of the sign of To add or subtract an interval from a TIMESTAMP or
CONCATENATION a number: INTERVALS DATETIME, use the TIMESTAMPADD() function:
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. 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 syntax consists of the INTERVAL keyword, a value, and -- result: '2014-08-10 07:55:00'
If any of the string is NULL, the result is NULL: a time part keyword (YEAR, QUARTER, MONTH, WEEK, DAY, TIMESTAMPADD(MONTH, -2,
To get the absolute value of a number:
SELECT CONCAT(Great ', 'day', NULL); HOUR, MINUTE, SECOND, MICROSECOND). '2014-06-10 07:55:00');
SELECT ABS(-12); -- result: 12
-- result: NULL -- result: '2014-04-10 07:55:00'
To get the square root of a number: You may combine different INTERVALs using the + or -
MySQL allows specifying a separating character (separator) SELECT SQRT(9); -- result: 3 operator:
using the CONCAT_WS() function. The separator is placed To add or subtract TIME from a DATETIME, use the
INTERVAL 1 YEAR + INTERVAL 3 MONTH
ADDTIME() function:
between the concatenated values:
SELECT CONCAT_WS(' ', 1, 'Olivier',
USEFUL NULL FUNCTIONS You may also use the standard SQL syntax:
INTERVAL '1-3' YEAR_MONTH
ADDTIME('2018-02-12 10:20:24',
'Norris'); -- result: 1 Olivier Norris To fetch the names of the cities whose rating values are not '12:43:02');
-- 1 year and 3 months
missing: -- result: '2018-02-12 23:03:26'
INTERVAL '3-12' HOUR_MINUTE
OTHER USEFUL TEXT FUNCTIONS SELECT name -- 3 hours 12 minutes
ADDTIME('2018-02-12 10:20:24',
To get the count of characters in a string: FROM city '-12:43:02');
SELECT LENGTH('LearnSQL.com'); WHERE rating IS NOT NULL; WHAT TIME IS IT? -- result: '2018-02-11 21:37:22'
-- result: 12 To answer this question, use:
COALESCE(x, y, ...) CURRENT_TIME or CURTIME – to get the current time. To find the difference between two dates, use the
To convert all letters to lowercase: To replace NULL in a query with something meaningful:
CURRENT_DATE or CURDATE – to get the current date. DATEDIFF() function:
SELECT LOWER('LEARNSQL.COM'); SELECT domain,
NOW() or CURRENT_TIMESTAMP – to get the current DATEDIFF('2015-01-01', '2014-01-02');
-- result: learnsql.com COALESCE(domain, 'domain missing')
timestamp with both of the above. -- result: 364
To convert all letters to uppercase: FROM contacts;
SELECT UPPER('LearnSQL.com'); The COALESCE() function takes any number of arguments CREATING VALUES To find the difference between two times, use the
-- result: LEARNSQL.COM and returns the value of the first argument that is not NULL. To create a date, time, or datetime, write the value as a string TIMEDIFF() function:
To get just a part of a string: and cast it to the proper type.
NULLIF(x, y) SELECT CAST('2021-12-31' AS date),
SELECT TIMEDIFF('09:30:00', '07:55:00');
SELECT SUBSTRING('LearnSQL.com', 9); -- result: '01:35:00'
To save yourself from division by 0 errors:
-- result: .com CAST('15:31' AS time),
SELECT last_month, this_month,
SELECT SUBSTRING('LearnSQL.com', 1, 5); CAST('2021-12-31 23:59:29' AS datetime);
this_month * 100.0 To find the difference between two datetimes (in a given unit
-- result: Learn
/ NULLIF(last_month, 0) You may skip casting in simple conditions; the database of time), use the TIMESTAMPDIFF() function. Here's an
To replace a part of a string: AS better_by_percent knows what you mean. example 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, FROM airport_schedule WEEK, '2018-02-26', '2018-03-21'
-- result: LearnPython.com else it 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