PentOpsVault @syztem4our666

PentOpsVault
CheatSheets

MySQL CheatSheet

CheatSheet

Creating a Database: CREATE DATABASE

To create a database, use:

CREATE DATABASE database_name;

Example:

CREATE DATABASE company;

Output:

MariaDB [(none)]> CREATE DATABASE company;
Query OK, 1 row affected (0.001 sec)

To show databases, use:

SHOW DATABASES;

Output:

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| company            |
| sys                |
+--------------------+
5 rows in set (0.000 sec)

To use the created database "company", use:

USE database_name;

Example:

USE company;
 
MariaDB [(none)]> USE company;
Database changed

Creating a Table and Showing its Fields (CREATE TABLE - SHOW TABLES - DESCRIBE - DROP TABLE)

A database stores its data in tables. This is a data structure that organizes data in columns and rows; each column is a field (or attribute) and each row, a record. The intersection of a column with a row contains a specific data value.

To create a table, use:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    ...
);

Example:

CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    emp_name VARCHAR(50),
    emp_salary DECIMAL(10, 2),
    emp_hire_date DATE
);

To describe the table, use:

DESCRIBE table_name;

Output:

MariaDB [company]> DESCRIBE employees;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| emp_id      | int(11)      | NO   | PRI | NULL    |       |
| emp_name    | varchar(50)  | YES  |     | NULL    |       |
| emp_salary  | decimal(10,2)| YES  |     | NULL    |       |
| emp_hire_date | date       | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.006 sec)

To show all tables in the database, use:

SHOW TABLES;

Output:

MariaDB [company]> SHOW TABLES;
+--------------------+
| Tables_in_company  |
+--------------------+
| employees          |
+--------------------+
1 row in set (0.001 sec)

Loading Records into a Table and Retrieving Them (INSERT INTO – SELECT)

To insert a record into a table, use:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

Example:

INSERT INTO employees (emp_id, emp_name, emp_salary, emp_hire_date)
VALUES (1, 'John Doe', 75000.00, '2022-01-15');
 
Query OK, 1 row affected (0.016 sec)

To select all records from a table, use:

SELECT * FROM table_name;

Output:

MariaDB [company]> SELECT * FROM employees;
+--------+----------+------------+--------------+
| emp_id | emp_name | emp_salary | emp_hire_date|
+--------+----------+------------+--------------+
|      1 | John Doe |   75000.00 | 2022-01-15   |
+--------+----------+------------+--------------+
1 row in set (0.001 sec)

Data Types

Data TypeDescriptionRange / Size
CHARFixed length string0 - 255
VARCHARVariable length string0 - 255
TINYTEXTShort text string0 - 255
TEXTText string0 - 65,535
BLOBBinary large object0 - 65,535
MEDIUMTEXTMedium length text string0 - 16,777,215
MEDIUMBLOBMedium binary large object0 - 16,777,215
LONGTEXTLong text string0 - 4,294,967,295
LONGBLOBLong binary large object0 - 4,294,967,295
TINYINT xInteger-128 to 127
SMALLINT xInteger-32,768 to 32,767
MEDIUMINT xInteger-8,388,608 to 8,388,607
INT xInteger-2,147,483,648 to 2,147,483,647
BIGINT xInteger-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
FLOATDecimal (precise to 23 digits)Precision up to 23 digits
DOUBLEDecimal (24 to 53 digits)Precision up to 53 digits
DECIMALFixed-point decimalPrecision and scale defined manually
DATEDateYYYY-MM-DD
DATETIMEDate and timeYYYY-MM-DD HH:MM:SS
TIMESTAMPTimestampYYYYMMDDHHMMSS
TIMETimeHH:MM:SS
ENUMOne of a set of predefined valuesPredefined options
SETMultiple values from a setSelection of predefined options

Select Queries

OperationQuery
Select all columnsSELECT * FROM tbl;
Select specific columnsSELECT col1, col2 FROM tbl;
Select only unique recordsSELECT DISTINCT col FROM tbl WHERE condition;
Column aliasSELECT col AS newname FROM tbl;
Order results`SELECT * FROM tbl ORDER BY col [ASC
Group resultsSELECT col1, SUM(col2) FROM tbl GROUP BY col1;

Creating and Modifying

OperationQuery
Create a databaseCREATE DATABASE db_name;
Select a databaseUSE db_name;
List databases on the serverSHOW DATABASES;
Show a table's fieldsDESCRIBE tbl;
Create a new tableCREATE TABLE tbl (field1 datatype, field2 datatype);
Insert data into a tableINSERT INTO tbl VALUES ("val1", "val2");
Delete a rowDELETE FROM tbl WHERE condition;
Add a columnALTER TABLE tbl ADD COLUMN col datatype;
Remove a columnALTER TABLE tbl DROP COLUMN col;
Make a column a primary keyALTER TABLE tbl ADD PRIMARY KEY (col);
Return only 1 row matching querySELECT * FROM tbl LIMIT 1;
Amend the values of a columnUPDATE tbl SET column1="val1" WHERE condition;
Clear all values (leaving table structure)TRUNCATE TABLE tbl;
Delete the tableDROP TABLE tbl;
Delete the databaseDROP DATABASE db_name;

Matching Data

OperationQuery
Matching data using LIKESELECT * FROM tbl WHERE col LIKE '%value%';
Matching data using REGEXSELECT * FROM tbl WHERE col RLIKE 'regular_expression';

Joins

Join TypeDescriptionQuery
INNER JOINReturns only matching rows from both tablesSELECT * FROM tbl1 INNER JOIN tbl2 ON tbl1.id = tbl2.id;
OUTER JOINReturns all rows from both tables, with NULLs where there is no matchSELECT * FROM tbl1 OUTER JOIN tbl2 ON tbl1.id = tbl2.id;
LEFT JOINReturns all rows from the left table, with NULLs where there is no match in the right tableSELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl1.id = tbl2.id;
RIGHT JOINReturns all rows from the right table, with NULLs where there is no match in the left tableSELECT * FROM tbl1 RIGHT JOIN tbl2 ON tbl1.id = tbl2.id;

String Functions

FunctionDescriptionQuery
STRCMPCompare two stringsSTRCMP("str1", "str2");
LOWERConvert string to lower caseLOWER("str");
UPPERConvert string to upper caseUPPER("str");
LTRIMRemove leading spacesLTRIM("str");
SUBSTRINGExtract a substringSUBSTRING("str", index1, index2);
CONCATConcatenate two stringsCONCAT("str1", "str2");

MySQL Calculation Functions

FunctionDescriptionQuery
COUNTCount the number of rowsCOUNT(col);
AVGCalculate average valueAVG(col);
MINGet the minimum valueMIN(col);
MAXGet the maximum valueMAX(col);
SUMCalculate the sum of valuesSUM(col);

Create Table with Auto-Incrementing Primary Key

CREATE TABLE table_name (
  id INT AUTO_INCREMENT,
  column1 VARCHAR(2),
  column2 VARCHAR(32),
  PRIMARY KEY (id)
);

On this page

Edit on GitHub