Summary Mysql
Summary Mysql
Quickref.me
Contents
Getting Started.......................................................................................................4
Connect MySQL............................................................................................................................ 4
Commons..................................................................................................................................... 4
Database.................................................................................................................................. 4
Table........................................................................................................................................ 4
Process..................................................................................................................................... 4
Other........................................................................................................................................ 4
Backups....................................................................................................................................... 4
MySQL Examples.....................................................................................................5
Managing tables.......................................................................................................................... 5
Querying Data from a Table......................................................................................................... 5
Querying from Multiple Tables..................................................................................................... 6
Using SQL Operators to Combine Rows from Queries..................................................................6
Querying Rows with Conditions................................................................................................... 7
Using SQL Constraints.................................................................................................................. 7
Modifying Data............................................................................................................................. 8
Managing Views........................................................................................................................... 8
Managing Triggers....................................................................................................................... 9
WHEN....................................................................................................................................... 9
EVENT....................................................................................................................................... 9
TRIGGER_TYPE.......................................................................................................................... 9
Managing Indexes........................................................................................................................ 9
MySQL Data Types.................................................................................................10
Strings....................................................................................................................................... 10
Date & Time............................................................................................................................... 10
Numeric..................................................................................................................................... 10
MySQL Functions & Operators................................................................................11
Strings....................................................................................................................................... 11
Date and Time Functions........................................................................................................... 12
Numeric Functions and Operators............................................................................................. 14
Aggregate Functions.................................................................................................................. 15
JSON Functions and Operators................................................................................................... 15
Cast Functions and Operators.................................................................................................... 16
Flow Control Functions and Operators....................................................................................... 16
Information Functions................................................................................................................ 16
Encryption and Compression Functions..................................................................................... 17
Locking Functions...................................................................................................................... 17
Bit Functions and Operators...................................................................................................... 17
Miscellaneous Functions............................................................................................................ 18
Getting Started
Connect MySQL
mysql -u <user> -p # Connect to MySQL using username and password
mysql [db_name] # Open a specific database after connecting
mysql -h <host> -P <port> -u <user> -p [db_name]
# Connect to a remote MySQL server using host, port, username, and password
mysql -h <host> -u <user> -p [db_name] # Connect to a MySQL server with specified host and database
Commons
Database
CREATE DATABASE db; # Create a new database
DROP DATABASE db; # Delete a database
SHOW DATABASES; # List all databases
USE db; # Switch to a specific database
CONNECT db; # Alternate command to switch to a database
Table
SHOW TABLES; # List all tables in the current database
SHOW FIELDS FROM t; # List all fields in a specific table
DESC t; # Display the structure of a table
SHOW CREATE TABLE t; # Show the SQL statement to create a table
TRUNCATE TABLE t; # Remove all data from a table
DROP TABLE t; # Delete a table
Process
show processlist; # Display the list of current processes
kill pid; # Terminate a specific process by its ID
Other
exit or \q # Exit the MySQL session
Backups
mysqldump -u user -p db_name > db.sql # Create a backup of a database
mysqldump -u user -p db_name --no-data=true --add-drop-table=false > db.sql # Export bd data without the schema
mysql -u user -p db_name < db.sql # Restore a database from a backup file
MySQL Examples
Managing tables
CREATE TABLE t ( # Create a new table named 't' with three columns
id INT, # Column 'id' as an integer
name VARCHAR DEFAULT NOT NULL, # Column 'name' as a non-null string
price INT DEFAULT 0, # Column 'price' with default value 0
PRIMARY KEY(id) # Set 'id' as the primary key
);
DROP TABLE t; # Delete the table 't' from the database
TRUNCATE TABLE t; # Remove all data from the table 't', keeping its structure intact
ALTER TABLE t ADD column; # Add a new column to the table 't'
ALTER TABLE t DROP COLUMN c; # Remove column 'c' from the table 't'
ALTER TABLE t ADD constraint; # Add a new constraint to the table 't'
ALTER TABLE t DROP constraint; # Remove a constraint from the table 't'
ALTER TABLE t1 RENAME TO t2; # Rename the table 't1' to 't2'
ALTER TABLE t1 RENAME c1 TO c2; # Rename the column 'c1' to 'c2' in the table 't1'
SELECT DISTINCT c1 FROM t # Query unique values from column 'c1' with an optional filter condition
WHERE condition;
SELECT DISTINCT c1, c2 FROM t # Query unique values from columns 'c1' and ‘c2’, with an optional filter condition
WHERE condition;
SELECT c1, c2 FROM t # Sort the result set by 'c1' in ascending (default) or descending order
ORDER BY c1 ASC [DESC];
SELECT c1, c2 FROM t # Skip the specified number of rows (offset) and return at most the next 'n' rows
ORDER BY c1 # Sorts the results by column c1 in ascending order (default).
LIMIT n OFFSET offset;
SELECT c1, aggregate(c2) # Group rows by column 'c1' and apply an aggregate function on 'c2'
FROM t # we can have more colums like c1
GROUP BY c1;
SELECT c1, aggregate(c2) # Filter grouped rows using a condition in the HAVING clause
FROM t
GROUP BY c1
HAVING condition;
Querying from Multiple Tables
SELECT c1, c2 # Perform an inner join between tables 't1' and 't2' based on a condition
FROM t1
INNER JOIN t2 ON condition;
SELECT c1, c2 # Perform a left join, including all rows from 't1' and matching rows from 't2'
FROM t1
LEFT JOIN t2 ON condition;
SELECT c1, c2 # Perform a right join, including all rows from 't2' and matching rows from 't1'
FROM t1
RIGHT JOIN t2 ON condition;
SELECT c1, c2 # Perform a full outer join, including all rows from both tables
FROM t1
FULL OUTER JOIN t2 ON condition;
SELECT c1, c2 # Produce a Cartesian product of rows from 't1' and 't2'
FROM t1
CROSS JOIN t2;
SELECT c1, c2 # Another way to produce a Cartesian product of 't1' and 't2'
FROM t1, t2;
SELECT c1, c2 # Join table 't1' to itself using an inner join clause to find relationships within the same table.
FROM t1 A
INNER JOIN t1 B ON condition;
SELECT c1, c2 FROM t1 # Return rows that are common to both queries
INTERSECT
SELECT c1, c2 FROM t2;
SELECT c1, c2 FROM t1 # Return rows from the first query that are not in the second query
MINUS
SELECT c1, c2 FROM t2;
Querying Rows with Conditions
SELECT c1, c2 FROM t
WHERE c1 [NOT] LIKE pattern; # Query rows using pattern matching with wildcards ('%' or '_')
Using SQL Constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, NOT NULL)
CREATE TABLE t( # Set columns 'c1' and 'c2' as a composite primary key which will be unique
c1 INT, c2 INT, c3 VARCHAR, # and neither c1 nor c2 can be NULL.
PRIMARY KEY (c1, c2)
);
CREATE TABLE t1( # Set column 'c2' as a foreign key referencing 'c2' in table 't2'
c1 INT PRIMARY KEY, # and REFERENCES is a part of the FOREIGN KEY constraint in SQL
c2 INT,
FOREIGN KEY (c2) REFERENCES t2(c2)
);
CREATE TABLE t( # Ensure the combination of values in columns 'c2' and 'c3' is unique
c1 INT, c2 INT,
UNIQUE(c2, c3)
);
CREATE TABLE t( # Add a check constraint to ensure 'c1' is greater than 0 and 'c1' is greater than or equal to 'c2'
c1 INT, c2 INT,
CHECK(c1 > 0 AND c1 >= c2)
);
UPDATE t
SET c1 = new_value; # Update all rows in column 'c1' with a new value
UPDATE t
SET c1 = new_value,
c2 = new_value
WHERE condition; # Update values in columns 'c1' and 'c2' for rows matching a condition
DELETE FROM t
WHERE condition; # Delete rows from table 't' that match a specific condition
Managing Views
CREATE VIEW v(c1, c2)
AS
SELECT c1, c2
FROM t; # Create a new view 'v' consisting of columns 'c1' and 'c2' from table 't'
DROP VIEW view_name; # Delete a view named 'view_name' from the database
Managing Triggers
CREATE OR MODIFY TRIGGER trigger_name # Create or modify a trigger with a specific name
WHEN EVENT # Specify when the trigger is executed (BEFORE or AFTER the event)
ON table_name TRIGGER_TYPE # Specify the table and trigger type (FOR EACH ROW or FOR EACH STATEMENT)
EXECUTE stored_procedure; # Define the action or procedure the trigger executes
WHEN
BEFORE # Trigger is invoked before the event occurs
AFTER # Trigger is invoked after the event occurs
EVENT
INSERT # Trigger is invoked for INSERT operations
UPDATE # Trigger is invoked for UPDATE operations
DELETE # Trigger is invoked for DELETE operations
TRIGGER_TYPE
FOR EACH ROW # Execute the trigger for each row affected by the event
FOR EACH STATEMENT # Execute the trigger once for the entire SQL statement
Managing Indexes
CREATE INDEX idx_name
ON t(c1, c2); # Create an index named 'idx_name' on columns 'c1' and 'c2' of the table 't'
DROP INDEX idx_name; # Remove the index named 'idx_name' from the table
MySQL Data Types
Strings
CHAR # Fixed-length string (0 - 255 characters)
VARCHAR # Variable-length string (0 - 255 characters)
TINYTEXT # Tiny text string (0 - 255 characters)
TEXT # Text string (0 - 65,535 characters)
BLOB # Binary large object, stores binary data (0 - 65,535 bytes)
MEDIUMTEXT # Medium text string (0 - 16,777,215 characters)
MEDIUMBLOB # Medium binary large object (0 - 16,777,215 bytes)
LONGTEXT # Long text string (0 - 4,294,967,295 characters)
LONGBLOB # Long binary large object (0 - 4,294,967,295 bytes)
ENUM # String object with one value selected from a predefined list
SET # String object with multiple values selected from a predefined list
Numeric
TINYINT x # Integer with range (-128 to 127)
SMALLINT x # Integer with range (-32,768 to 32,767)
MEDIUMINT x # Integer with range (-8,388,608 to 8,388,607)
INT x # Integer with range (-2,147,483,648 to 2,147,483,647)
BIGINT x # Integer with range (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
FLOAT # Decimal number precise up to 23 digits
DOUBLE # Decimal number precise between 24 to 53 digits
DECIMAL # "DOUBLE" stored as a string for exact precision
Aggregate Functions
AVG() # Returns the average value of a numeric column
BIT_AND() # Performs a bitwise AND operation across all values in a column
BIT_OR() # Performs a bitwise OR operation across all values in a column
BIT_XOR() # Performs a bitwise XOR operation across all values in a column
COUNT() # Counts the number of rows in a result set
COUNT(DISTINCT) # Counts the number of distinct values in a column
GROUP_CONCAT() # Concatenates values from a group into a single string
JSON_ARRAYAGG() # Aggregates values into a JSON array
JSON_OBJECTAGG() # Aggregates key-value pairs into a JSON object
MAX() # Returns the maximum value in a column
MIN() # Returns the minimum value in a column
STD() # Alias for STDDEV(), returns the standard deviation
STDDEV() # Returns the standard deviation of values in a column
STDDEV_POP() # Returns the population standard deviation
STDDEV_SAMP() # Returns the sample standard deviation
SUM() # Returns the sum of values in a column
VAR_POP() # Returns the population variance
VAR_SAMP() # Returns the sample variance
VARIANCE() # Alias for VAR_POP(), returns the population variance
Information Functions
BENCHMARK() # Executes an expression repeatedly for performance testing
CHARSET() # Returns the character set of a string
COERCIBILITY() # Returns the coercibility value of a string
COLLATION() # Returns the collation of a string
CONNECTION_ID() # Returns the unique connection ID for the current session
CURRENT_ROLE() # Returns the active role for the current session
CURRENT_USER() # Returns the authenticated user name and host name
DATABASE() # Returns the name of the current database
FOUND_ROWS() # Returns the number of rows found by the last SELECT query
ICU_VERSION() # Returns the version of the ICU library used
LAST_INSERT_ID() # Returns the value of the last AUTO_INCREMENT column inserted
ROLES_GRAPHML() # Returns a GraphML representation of role relationships
ROW_COUNT() # Returns the number of rows affected by the last statement
SCHEMA() # Alias for DATABASE(), returns the name of the current database
SESSION_USER() # Returns the current session user name and host name
SYSTEM_USER() # Alias for USER(), returns the user name and host name of the connected user
USER() # Returns the user name and host name of the connected user
VERSION() # Returns the version of the MySQL server
Locking Functions
GET_LOCK() # Acquires a named lock with a timeout
IS_FREE_LOCK() # Checks if a named lock is available
IS_USED_LOCK() # Checks which connection is using a specific named lock
RELEASE_ALL_LOCKS() # Releases all locks held by the current connection
RELEASE_LOCK() # Releases a specific named lock
Miscellaneous Functions
ANY_VALUE() # Returns a value from a group, bypassing ONLY_FULL_GROUP_BY restrictions
BIN_TO_UUID() # Converts a binary UUID to a string UUID
DEFAULT() # Returns the default value for a column
GROUPING() # Indicates whether a column is aggregated in a GROUP BY query
INET_ATON() # Converts an IPv4 address from string to numeric format
INET_NTOA() # Converts a numeric IPv4 address to string format
INET6_ATON() # Converts an IPv6 address from string to binary format
INET6_NTOA() # Converts a binary IPv6 address to string format
IS_IPV4() # Checks if a string is a valid IPv4 address
IS_IPV4_COMPAT() # Checks if an address is an IPv4-compatible IPv6 address
IS_IPV4_MAPPED() # Checks if an address is an IPv4-mapped IPv6 address
IS_IPV6() # Checks if a string is a valid IPv6 address
IS_UUID() # Checks if a string is a valid UUID
MASTER_POS_WAIT() # Waits until the slave has read up to a specific position in the master binary log
NAME_CONST() # Creates a constant with a specified name and value
SLEEP() # Causes the session to sleep for a specified number of seconds
UUID() # Generates a Universal Unique Identifier (UUID)
UUID_SHORT() # Generates a short, numeric UUID
UUID_TO_BIN() # Converts a string UUID to binary format
VALUES() # Returns values from the most recent INSERT or UPDATE statement
Query: