Skip to content

MySQL

MySQL reference: users and privileges, password resets, backups and restores, data export, handy queries, Docker and Connector/J.

11 min readUpdated

MySQL is an open-source relational database. This note collects tested commands and queries for everyday administration: creating databases and users, resetting passwords, backing up and restoring data, exporting results to TSV and CSV, a few useful query patterns, running MySQL in Docker and connecting from Java with Connector/J.

Create a database, user and privileges

Create a database with the utf8mb4 character set, create a user that can connect from localhost, and give it full access to that database:

CREATE DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE USER dbname@localhost IDENTIFIED BY 'P@ssword1';
GRANT ALL PRIVILEGES ON dbname.* TO dbname@localhost;

Use utf8mb4 rather than utf8: in MySQL utf8 is an alias of the deprecated utf8mb3, which cannot store characters outside the Basic Multilingual Plane, such as emoji. utf8mb4_0900_ai_ci is the default collation in MySQL 8.0 and later.

CREATE USER and GRANT take effect immediately. FLUSH PRIVILEGES is only needed after you change the grant tables directly with INSERT, UPDATE or DELETE.

Drop a database and user

DROP DATABASE IF EXISTS dbname;
DROP USER dbname@localhost;

Change a user’s password

ALTER USER 'dbname'@'localhost' IDENTIFIED BY 'P@ssword1';

Older guides use SET PASSWORD FOR 'dbname'@'localhost' = PASSWORD('P@ssword1'). The PASSWORD() function was removed in MySQL 8.0, so that form no longer works.

Reset a forgotten root password

Stop the server and start it without the grant tables, so you can log in without a password. --skip-networking blocks remote connections while the server is unprotected:

Terminal window
sudo systemctl stop mysql
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql --user=root

The service is called mysql on Debian and Ubuntu and mysqld on Red Hat based systems. In the mysql client, reload the grant tables and set the new password:

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'P@ssword1';
EXIT;

The FLUSH PRIVILEGES here is required: it loads the grant tables, without which ALTER USER fails while the server runs with --skip-grant-tables. Then stop the temporary server and start MySQL normally:

Terminal window
sudo mysqladmin -u root -p shutdown
sudo systemctl start mysql

On MySQL 5.6 and earlier the password was set with UPDATE mysql.user SET Password=PASSWORD('P@ssword1') WHERE User='root'; followed by FLUSH PRIVILEGES;.

Back up and restore

Back up a database with mysqldump

mysqldump writes the schema and data of a database as SQL statements. Through the local socket connection:

Terminal window
mysqldump -u root -p --opt dbname > dbname.sql

--opt is on by default; it groups options that produce a fast, compact dump. Add --complete-insert to write column names into each INSERT statement, which makes the dump easier to load into a table with a different column order:

Terminal window
mysqldump -u root -p --opt --complete-insert dbname > dbname.sql

If mysqldump cannot find the socket, it fails with this error:

mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect

In that case connect over TCP with the host and port instead:

Terminal window
mysqldump -h 127.0.0.1 -P 3306 -u root -p --opt --complete-insert dbname > dbname.sql

Schedule backups with cron

Open the root crontab:

Terminal window
sudo crontab -e

This line backs up DBNAME every day at 01:30 into a file named with the date and time:

Terminal window
30 1 * * * /usr/bin/mysqldump -u 'USERNAME' -p'PASSWORD' --opt DBNAME > /home/USER/path/to/DBNAME_`date +\%Y\%m\%d_\%H\%M`.sql

This line backs up all databases every day at 02:15 and compresses the dump with gzip:

Terminal window
15 2 * * * /usr/bin/mysqldump -u 'USERNAME' -p'PASSWORD' --all-databases | gzip > /home/USER/path/to/all-databases_$(date +\%F_\%T).sql.gz

In a crontab, % starts a new line of standard input, so every % in the command must be escaped as \%. A password on the command line is visible to other users in the process list; on shared machines, put the credentials in the [client] section of ~/.my.cnf (readable only by the owner) and drop -u and -p.

Restore a database

Load a dump into an existing database:

Terminal window
mysql -u root -p newdatabase < /path/to/newdatabase.sql

Back up a table to a text file

SELECT ... INTO OUTFILE writes the rows of a table as a tab-separated file:

SELECT * INTO OUTFILE 'table_backup_file' FROM name_of_table;

The file is written on the database server host, not on the client, by the MySQL server process. The secure_file_priv system variable limits the directory it may write to.

Automatic backups with automysqlbackup

automysqlbackup runs daily, weekly and monthly rotating backups of all databases. Install it on Debian or Ubuntu:

Terminal window
sudo apt install automysqlbackup

Run a backup by hand:

Terminal window
sudo automysqlbackup

The main configuration file is /etc/default/automysqlbackup:

Terminal window
sudo nano /etc/default/automysqlbackup

Backups are stored in /var/lib/automysqlbackup by default. To see the structure of the backups:

Terminal window
ls /var/lib/automysqlbackup
ls -R /var/lib/automysqlbackup/daily

Compare the structure of two databases

Dump only the schema of both databases (--no-data), one statement per line and without comments, and compare the files:

Terminal window
mysqldump --skip-comments --skip-extended-insert --no-data -u root -p dbName1 > file1.sql
mysqldump --skip-comments --skip-extended-insert --no-data -u root -p dbName2 > file2.sql
diff file1.sql file2.sql

Copy data between databases

Copy selected columns from a table in one database to a table in another database on the same server:

INSERT INTO `dbDestination`.`tblDestination` (`field1`, `field2`, `field3`)
SELECT `field1`, `field2`, `field3`
FROM `dbSource`.`tblSource`;

Copy one row into the same table

To duplicate a row with a new primary key, copy it into a temporary table, change the key there and insert it back:

CREATE TEMPORARY TABLE tmptable SELECT * FROM teacher WHERE id = 1;
UPDATE tmptable SET id = 2 WHERE id = 1;
INSERT INTO teacher SELECT * FROM tmptable WHERE id = 2;
DROP TEMPORARY TABLE tmptable;

Copy one column into another table

This copies the non-empty COUNTRY values of AUDIENCEENTITY into the TAGS collection table, keyed by the entity ID:

INSERT INTO AudienceEntity_TAGS (AudienceEntity_ID, TAGS)
SELECT ID, COUNTRY FROM AUDIENCEENTITY WHERE COUNTRY != '';
SELECT * FROM AudienceEntity_TAGS;

Export query results to TSV and CSV

Put the queries in a file, for example sql_requests.sql:

sql_requests.sql
SELECT * FROM COUNTRYENTITY;
SELECT * FROM CITYENTITY;

When its input is not a terminal, the mysql client prints results as tab-separated values with a header row. Redirect the output to a file for TSV, or convert the tabs with sed for CSV:

Terminal window
# Tab-separated
mysql -h 127.0.0.1 -P 3306 -u username -p databasename < sql_requests.sql > out.tsv
# Comma-separated
mysql -h 127.0.0.1 -P 3306 -u username -p databasename < sql_requests.sql | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > out.csv

For a single query, pass it with -e (--execute) instead of a file:

Terminal window
mysql -h 127.0.0.1 -P 3306 -u username -p databasename -e "SELECT * FROM COUNTRYENTITY" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > out.csv

The sed conversion wraps every field in double quotes. It does not escape double quotes or tabs inside the values, so check the data first.

To convert a CSV file to TSV:

Terminal window
awk 'BEGIN { FS=","; OFS="\t" } {gsub(/"/, "");$1=$1; print}' input.csv > output.tsv

To turn a CSV file into INSERT statements, using the first line as the column list:

Terminal window
awk 'NR==1{x=$0;next} {gsub(/,/,"\47,\47");printf "INSERT INTO COUNTRYENTITY (%s) VALUES (\47%s\47)\n",x,$0}' out.csv

\47 is the single quote character, written in octal so that it does not end the awk program.

Useful queries

List a table’s columns as a comma-separated string

SELECT GROUP_CONCAT(column_name ORDER BY ordinal_position)
FROM information_schema.columns
WHERE table_schema = 'database_name' AND table_name = 'table_name';

The result is one line:

COLUMN1,COLUMN2,COLUMN3,COLUMN4,etc...

To quote each column name with backticks, for use in another query:

SELECT GROUP_CONCAT("`", column_name, "`" ORDER BY ordinal_position)
FROM information_schema.columns
WHERE table_schema = 'database_name' AND table_name = 'table_name';
`COLUMN1`,`COLUMN2`,`COLUMN3`,`COLUMN4`,etc...

Set a random integer in a range

RAND() returns a value from 0 up to, but not including, 1. FLOOR(2 + RAND() * 8) therefore gives an integer from 2 to 9. This assigns a random category from 2 to 9 to every product in category 1:

UPDATE `store_products_categories` SET `category_id` = FLOOR(2 + RAND() * 8) WHERE category_id = 1;

Pick a random value from a list

ELT(n, value1, value2, ...) returns the nth value of the list, or NULL when n is less than 1 or greater than the number of values. A non-integer index is rounded, so 0.5 + RAND() * 2 gives 1 or 2 with equal probability:

UPDATE `TABLE` SET OPT = ELT(0.5 + RAND() * 2, true, false);
UPDATE `TABLE` SET VERDICT = ELT(0.5 + RAND() * 3, 'VALID', 'RISKY', 'INVALID');

Query comma-separated values

When a column stores a comma-separated list of IDs, IN() does not match individual items: it compares against the whole string. FIND_IN_SET(needle, list) returns the position of needle in a comma-separated list, or 0 if it is missing. Take these two tables, where exam_questions holds question IDs:

mysql> SELECT exam_id, exam_title, exam_questions FROM educa_exam;
+---------+---------------+----------------+
| exam_id | exam_title | exam_questions |
+---------+---------------+----------------+
| 1 | deneme exam 1 | 1,2,5 |
| 2 | deneme exam 2 | 1,4,8 |
+---------+---------------+----------------+
mysql> SELECT question_id, question_title FROM educa_question;
+-------------+----------------+
| question_id | question_title |
+-------------+----------------+
| 1 | question1 |
| 2 | question2 |
| 3 | question3 |
| 4 | question4 |
| 5 | question5 |
| 6 | question6 |
| 7 | question7 |
| 8 | question8 |
+-------------+----------------+

These queries return the questions of one exam, in the order they appear in the list. The first uses an implicit join, the second a LEFT JOIN:

SELECT *
FROM `educa_exam` AS `ex`, `educa_question` AS `eq`
WHERE `ex`.`exam_id` = 2
AND FIND_IN_SET(`eq`.`question_id`, `ex`.`exam_questions`)
ORDER BY FIND_IN_SET(`eq`.`question_id`, `ex`.`exam_questions`);
SELECT *
FROM `educa_exam` AS `ex`
LEFT JOIN `educa_question` AS `eq` ON FIND_IN_SET(`eq`.`question_id`, `ex`.`exam_questions`)
WHERE `ex`.`exam_id` = 1
ORDER BY FIND_IN_SET(`eq`.`question_id`, `ex`.`exam_questions`);

FIND_IN_SET cannot use an index, so on large tables a separate join table is the better design.

Data type storage requirements

The BLOB types (and the matching TEXT types) store a length prefix plus the data. L is the length of the value in bytes:

Data type Storage required
TINYBLOB L + 1 bytes, where L < 2^8 (256 bytes)
BLOB L + 2 bytes, where L < 2^16 (64 KB)
MEDIUMBLOB L + 3 bytes, where L < 2^24 (16 MB)
LONGBLOB L + 4 bytes, where L < 2^32 (4 GB)

Run MySQL in Docker

Start a MySQL container with a database, a user and a root password, and publish port 3306:

Terminal window
docker run --name mysqldb -e MYSQL_USER=mysql -e MYSQL_PASSWORD=mysql -e MYSQL_DATABASE=sample -e MYSQL_ROOT_PASSWORD=<YourPassword> -p 3306:3306 -d mysql:latest --character-set-server=utf8mb4 --collation-server=utf8mb4_0900_ai_ci

The arguments after the image name are passed to the MySQL server. Check that the container runs, open a shell in it and connect with the mysql client:

Terminal window
docker ps -a
docker exec -it mysqldb bash
mysql -uroot -p

Connect from Java with Connector/J

Add MySQL Connector/J to pom.xml:

pom.xml
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>

Since version 8.0.31 the driver is published as com.mysql:mysql-connector-j. Older versions use mysql:mysql-connector-java, and 5.1 versions use the driver class com.mysql.jdbc.Driver instead of com.mysql.cj.jdbc.Driver. See the upgrade guide in the references when you move from 5.1 to 8.0.

This program connects to the sample database of the Docker container above, creates a table, inserts four rows and prints them. JDBC 4 loads the driver automatically, so Class.forName(...) is not needed:

Main.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", "root", "<YourPassword>");
Statement sta = conn.createStatement()) {
String sql = "DROP TABLE IF EXISTS Registration";
sta.executeUpdate(sql);
System.out.println("Dropped table in given database...");
sql = "CREATE TABLE Registration "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";
sta.executeUpdate(sql);
System.out.println("Created table in given database...");
sta.executeUpdate("INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)");
sta.executeUpdate("INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)");
sta.executeUpdate("INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)");
sta.executeUpdate("INSERT INTO Registration VALUES (103, 'Sumit', 'Mittal', 28)");
System.out.println("Inserted records into the table...");
try (ResultSet rs = sta.executeQuery("SELECT * FROM Registration")) {
while (rs.next()) {
long id = rs.getLong("id");
String first = rs.getString("first");
String last = rs.getString("last");
int age = rs.getInt("age");
System.out.println("id: " + id + ", first: " + first + ", last: " + last + ", age: " + age);
}
}
}
}
}

The try-with-resources blocks close the result set, statement and connection even when a query fails.

Generate ER diagrams

In MySQL Workbench, run the Reverse Engineer wizard on a database to get an EER diagram, then export it as PNG, SVG, PDF or PostScript.

Sequel Pro on macOS can export a database as a Graphviz dot file, which gives a basic table-based ERD. Sequel Pro is no longer maintained; Sequel Ace is its maintained fork. Connect to the server, open the database, choose File > Export > Graphviz Dot file and save the file. Then install Graphviz with Homebrew:

Terminal window
brew install graphviz

Render the diagram as SVG:

Terminal window
dot -Tsvg your_database.dot > your_database.svg

To convert the SVG to PNG with ImageMagick (version 7 also accepts magick in place of convert):

Terminal window
convert your_database.svg your_database.png

To convert every SVG in the directory to PNG with a transparent background:

Terminal window
mogrify -background none -format png *.svg

Or convert with rsvg-convert from librsvg:

Terminal window
cat your_database.svg | rsvg-convert -o your_database.png

References

Related notes

6 min read

SQL joins

INNER, LEFT, RIGHT, FULL OUTER, CROSS and self joins in SQL, with two small example tables, the queries and their results.

  • Databases
3 min read

Database migration: MySQL to PostgreSQL

Migrate a MySQL database to PostgreSQL with pgloader in Docker, and fix the two authentication errors you are likely to hit.

  • Databases
5 min read

JDBC

JDBC driver, DataSource and XADataSource class names per database, with GlassFish and Payara connection pool examples.

  • Java & Jakarta EE
  • Databases

Type to search the whole site.