Docsity

MySQL Cheat Sheet: Essential Commands, Data Types, and More, Cheat Sheet of Principles of Database Management

Toggle sidebar
bg1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// New method chaining used for executing an SQL SELECT statement
// Recommended way for executing queries
var employees = db.getTable('employee');
var res = employees.select(['name', 'age']).
where('name like :param').
orderBy(['name']).
bind('param', 'm%').execute();
// Traditional SQL execution by passing an SQL string
// It should only be used when absolutely necessary
var result = session.sql('SELECT name, age ' +
'FROM employee ' +
'WHERE name like ? ' +
'ORDER BY name').bind('m%').execute();
MySQL
Cheat Sheet
Ready to advance your coding skills and master
databases? Great! Then you will find our MySQL cheat
sheet absolutely handy.
Sounds promising? Let’s jump in then!
MySQL is a popular, open-source, relational database that you can use to build all sorts of web
databases — from simple ones, cataloging some basic information like book recommendations
to more complex data warehouses, hosting hundreds of thousands of records. Learning MySQL
is a great next step for those who already know PHP or Perl. In this case, you can create websites
that interact with a MySQL database in real-time and display searchable and categorized records
to users.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download MySQL Cheat Sheet: Essential Commands, Data Types, and More and more Cheat Sheet Principles of Database Management in PDF only on Docsity!

(^12) (^34) (^56) (^78) (^910) (^1112) (^1314) 15 // New method chaining used for executing an SQL SELECT statement // Recommended way for executing queries var employees = db.getTable('employee'); var res = employees.select(['name', 'age']). where('name like :param'). orderBy(['name']).bind('param', 'm%').execute(); // Traditional SQL execution by passing an SQL string // It should only be used when absolutely necessary var result = session.sql('SELECT name, age '

'FROM employee ' + 'WHERE name like? ' + 'ORDER BY name').bind('m%').execute();

MySQL

Cheat Sheet

Ready to advance your coding skills and master

databases? Great! Then you will find our MySQL cheat

sheet absolutely handy.

Sounds promising? Let’s jump in then!

MySQL is a popular, open-source, relational database that you can use to build all sorts of web

databases — from simple ones, cataloging some basic information like book recommendations

to more complex data warehouses, hosting hundreds of thousands of records. Learning MySQL

is a great next step for those who already know PHP or Perl. In this case, you can create websites

that interact with a MySQL database in real-time and display searchable and categorized records

to users.

MySQL 101: Getting Started How to Connect to MySQL Create a new MySQL User Account Create a New Database Delete a MySQL Database Essential MySQL Commands Working with Tables Working With Table Columns Data Types Working With Indexes Working with Views Working with Triggers Stored Procedures for MySQL Logical Operators Aggregate Functions Arithmetic, Bitwise, Comparison, and Compound Operators SQL Database Backup Commands Conclusions 03 03 03 04 04 04 05 06 08 12 12 14 15 16 17 18 18 18 Table of Contents

Essential MySQL Commands Create a New Database Delete a MySQL Database SELECT — choose specific data from your database UPDATE — update data in your database DELETE — deletes data from your database INSERT INTO — inserts new data into a database CREATE DATABASE — generate a new database ALTER DATABASE — modify an existing database CREATE TABLE — create a new table in a database ALTER TABLE — change the selected table DROP TABLE — delete a table CREATE INDEX — create an index (search key for all the info stored) DROP INDEX — delete an index To set up a new database use this line: To get rid of a database just type: If you are done for the day, just type “exit” in the command line to finish your session. You can then view all your databases with this command: Later on, you can quickly navigate to a particular database using this command: CREATE DATABASE yourcoolname DROP DATABASE dbName mysql> show databases; [root@server ~]# mysql -u root -p mydatabase < radius.sql

Working with Tables Create a New Simple Table Delete a Table View Tables Tables are the key element of MySQL databases as they let you store all the information together in organized rows. Each row consists of columns that feature a specified data type. You have plenty of options for customization using the commands below. The code snippet below features a table for a list of movies that we want to organize by different attributes: Use this command to create a new table: To get rid of the table specify the table name in the following command: Use the next commands to get more information about the tables stored in your database. show tables — call a list of all tables associated with a database. DESCRIBE table_name; — see the columns of your table. DESCRIBE table_name column_name; — review the information of the column in your table. CREATE TABLE [IF NOT EXISTS] table_name( column_list ); DROP TABLE tablename; CREATE TABLE movies( title VARCHAR(100), year VARCHAR(100), director VARCHAR(50), genre VARCHAR(20), rating VARCHAR(100), );

Add an Additional Selection Clause Delete a Row Update Rows Edit a Column Include an additional pointer that indicates what type of data do you need. Use SELECT FROM syntax and WHERE clause to specify what rows to delete. Similarly, you can use different clauses to update all or specified rows in your table. To update all rows: You can alter any existing column with the following snippet: You can also update, select or delete rows using JOIN clause. It comes particularly handy when you need to manipulate data from multiple tables in a single query. Here’s how to update rows with JOIN: To update data only in a specified set of rows you can use WHERE clause: SELECT * FROM movies WHERE budget=’1’; SELECT * FROM movies WHERE year=’2020’ AND rating=’9’; DELETE FROM movies WHERE budget=’1’; UPDATE table_name SET column1 = value1, ...; ALTER TABLE movies MODIFY COLUMN number INT(3) UPDATE table_name INNER JOIN table1 ON table1.column1 = table2.column SET column1 = value1, WHERE budget=’5’ UPDATE table_name SET column_1 = value_1, WHERE budget=’5’

Sort Entries in a Column Search Columns Select a Range Concentrate Columns SELECT * FROM users ORDER BY last_name ASC; SELECT * FROM users ORDER BY last_name DESC; SELECT * FROM movies WHERE genre LIKE ‘com%’; SELECT * FROM movies WHERE title LIKE ‘%a’; SELECT * FROM movies WHERE rating BETWEEN 8 AND 10; SELECT CONCAT(first_name, ‘ ‘, last_name) AS ‘Name’, dept FROM users; SELECT * FROM movies WHERE genre NOT LIKE ‘hor%’; You can sort the data in all columns and rows the same way you do in Excel e.g. alphabetically or from ascending to descending value. Here’s how you can quickly find the information you need using WHERE and LIKE syntax: Or you can bring up a certain data range using the next command: You can mash-up two or more columns together with CONCAT function: You can also exclude certain items from search with NOT LIKE: Data Types Data types indicate what type of information you can store in a particular column of your table. MySQL has three main categories of data types:

  • Numeric
  • Text
  • Date/time

Blob and Text Data Types Text Storage Formats BLOB binary range enables you to store larger amounts of text data. The maximum length of a BLOB is 65,535 (2^16 − 1) bytes. BLOB values are stored using a 2-byte length prefix. NB: Since text data can get long, always double-check that you do not exceed the maximum lengths. The system will typically generate a warning if you go beyond the limit. But if nonspace characters get truncated, you may just receive an error without a warning.

- TINYBLOB — sets the maximum column length at 255 (2^8 − 1) bytes. TINYBLOB values are stored using a 1-byte length prefix. - MEDIUMBLOB — sets the maximum column length at 16,777,215 (2^24 − 1) bytes. MEDIUMBLOB values are stored using a 3-byte length prefix. - LONGBLOB — sets the maximum column length at 4,294,967,295 or 4GB (2^32 − 1) bytes. LONGBLOB values are stored using a 4-byte length prefix. Note : The max length will also depend on the maximum packet size that you configure in the client/server protocol, plus available memory. TEXT does the same job but holds values of smaller length. A TEXT column can have a maximum length of 65,535 (2^16 − 1) characters. However, the max length can be smaller if the value contains multibyte characters. TEXT value is also stored using a 2-byte length prefix. - TINYTEXT — store a value using a 1-byte length prefix. The maximum supported column length is 255 (2^8 − 1) characters. - MEDIUMTEXT — store a value using a 3-byte length prefix. The maximum supported column length is 16,777,215 (2^24 − 1) characters. - LONGTEXT — store a value using a 4-byte length prefix. The maximum supported column length is 4,294,967,295 or 4GB (2^32 − 1) characters. Note: Again, the length cap will also depend on your configured maximum packet size in the client/server protocol and available memory. - CHAR — specifies the max number of non-binary characters you can store. The range is from 0 to 255. - VARCHAR — store variable-length non-binary strings. The maximum number of characters you can store is 65,535 (equal to the max row size).

  • VARCHAR values are stored as a 1-byte or 2-byte length prefix plus data, unlike CHAR values. - BYNARY — store binary data in the form of byte strings. Similar to CHAR. - VARBYNARY — store binary data of variable length in the form of byte strings. Similar to VARCHAR. - ENUM — store permitted text values that you enumerated in the column specification when creating a table.
  • ENUM columns can contain a maximum of 65,535 distinct elements and have > 255 unique element list definitions among its ENUM. - SET — another way to store several text values that were chosen from a predefined list of values.
  • SET column can contain a maximum of 64 distinct members and have > 255 unique element list definitions among its SET.

Date and Time Data Types As the name implies, this data type lets you store the time data in different formats.

- DATE — use it for values with a date part only. MySQL displays DATE values in the ‘YYYY-MM- DD’ format.

  • Supported data range is ‘1000-01-01’ to ‘9999-12-31’. - DATETIME — record values that have both date and time parts. The display format is ‘YYYY- MM-DD hh:mm:ss’.
  • Supported data range is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’. - TIMESTAMP — add more precision to record values that have both date and time parts, up till microseconds in UTC.
  • Supported data range is ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC. - TIME — record just time values in either ‘hh:mm:ss’ or ‘hhh:mm:ss’ format. The latter can represent elapsed time and time intervals.
  • Supported data range is ‘-838:59:59’ to ‘838:59:59’. - YEAR — use this 1-byte type used to store year values.
    • A 4-digit format displays YEAR values as 0000, with a range between 1901 to 2155.
    • A 2-digit format displays YEAR values as 00. The accepted range is ‘0’ to ‘99’ and MySQL will convert YEAR values in the ranges 2000 to 2069 and 1970 to 1999.

Update a View Rename a View Show All Views Delete a View A view always displays fresh data since the database engine recreates it each time, using the view’s SQL statement. To refresh your view use the next code: If you are dealing with multiple views at a time, it’s best to give them distinctive names. Here’s how that done: To call up all current views for all tables from the database, use this snippet: To delete a single view use the DROP command: You can also delete multiple views at a time: CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition; RENAME TABLE view_name TO new_view_name; SHOW FULL TABLES WHERE table_type = ‘VIEW’; DROP VIEW [IF EXISTS] view_name; Drop Multiple views: DROP VIEW [IF EXISTS] view1, view2, ...;

Working With Triggers A trigger is a database object, associated with a table. It activates whenever a specific event happens for the table. For example, you can set up triggers for events such as:

  • Row or deletes updates
  • Row information inserts This is a more advanced topic, so check the official MySQL trigger FAQ section for more details. How to Create a Trigger Review All Triggers in Your Database How to Delete a Trigger To create a simple trigger that will pop up before or after a certain operation such as INSERT, UPDATE or DELETE, use this code: Search your database for all the active triggers using LIKE and WHERE clauses. To remove a trigger, use the DROP command: CREATE TRIGGER trigger_name {BEFORE | AFTER} {INSERT | UPDATE| DELETE } ON table_name FOR EACH ROW trigger_body; SHOW TRIGGERS [{FROM | IN} database_name] [LIKE ‘pattern’ | WHERE search_condition]; DROP TRIGGER [IF EXISTS] trigger_name;

Logical Operators Logical operators enable you to add more than one condition in WHERE clause. This makes them super handy for more advanced search, update, insert and delete queries. In MySQL you have three main logical operators:

- AND — use it to filter records that rely on 1+ condition. This way you can call records that satisfy all the conditions separated by AND. - OR — call records that meet any of the conditions separated by OR. - NOT — review records that do not meet a certain condition (e.g. NOT blue). It’s a handy operator from excluding certain data. Plus, some additional special operators: - BETWEEN — select or search data between a range of set min and max values. - LIKE — compare one record to another. Handy operator for search. - IS NULL — compare some value with a NULL value. - IN — determine if a value or expression matches one of the values on your list. - ALL — compare a value or expression to all other values in a list. - ANY — compare a value or expression to any value in your list according to the specified condition. - EXISTS — test if a certain record exists.

Aggregate Functions Aggregate functions in MySQL allow you to run a calculation on a set of values and return a single scalar value. In essence, they are a great way to find the needed data faster and organize it better using GROUP BY and HAVING clauses of the SELECT statement. Below is an overview of these: MIN COUNT AVG SUM MAX Find the smallest value of the selected column in your table: Call up several rows that meet the specified criteria: Get the average value of a numeric column that you selected: Receive a total sum of a numeric column that you selected: Does the opposite and returns the largest value of the selected column: SELECT MIN (column_name) FROM table_name WHERE condition; SELECT COUNT (column_name) FROM table_name WHERE condition; SELECT AVG (column_name) FROM table_name WHERE condition; SELECT SUM(column_name) FROM table_name WHERE condition; SELECT MAX (column_name) FROM table_name WHERE condition;