MySQL Everyday Queries: Users, Backups and Table Information
Application queries get the attention, but everyday MySQL work is mostly administration: creating a login for a new app, checking who can see what, looking up a table size before a migration, and taking a backup you can actually restore. This roundup of mysql common queries collects those maintenance patterns in one place, using syntax for MySQL 8, which is the version most hosts run today. Each section pairs the command with the check you should run alongside it.
You will need an account with administrative privileges for the user and grant sections, and shell access for the backup commands, which run outside the SQL prompt. Work on a staging copy first if you are new to an operation. Knowing which rows live where still matters during admin work, and our sql select query examples cover the reading patterns you will use to verify every change below.
Exploring Databases and Tables
When you land on an unfamiliar server, orientation comes first. List the databases, switch to one, list its tables, then describe the table you care about. These four commands answer most first-day questions without touching any data.
SHOW DATABASES; USE shop_db; SHOW TABLES; DESCRIBE orders; SHOW CREATE TABLE orders;
SHOW DATABASES lists every database your account can see. USE selects the working database so later statements need no prefix. SHOW TABLES lists tables and views in that database. DESCRIBE, which can be shortened to DESC, shows each column with its type, whether NULL is allowed, key information, defaults, and extras such as auto-increment. SHOW CREATE TABLE goes further and prints the full statement that would recreate the table, including indexes and engine, which is the reliable way to check a foreign key or character set before altering anything. Save that output before a schema change; it is your reference for what the table looked like.
Size questions come next, usually when a disk fills or a backup window shrinks. The information_schema database holds metadata for the whole server, and querying it gives table sizes in a sortable form instead of one table at a time.
SELECT table_name,
table_rows,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb
FROM information_schema.tables
WHERE table_schema = 'shop_db'
ORDER BY data_length DESC;
This lists tables in shop_db from largest to smallest, splitting storage into data and indexes measured in megabytes. table_rows is an estimate for InnoDB tables, good enough for spotting the giant in the room, not an exact count; use COUNT(*) when an exact figure matters for one table. A table whose index size dwarfs its data may carry redundant indexes, and a table growing far faster than the rest deserves a retention conversation. Similar metadata queries help before the data-changing jobs described in sql insert update delete, where knowing table scale decides whether to batch the work.
Creating Users and Granting Permissions
Applications should never connect as root. Give each application its own user, a strong password, and only the privileges it needs on only its database. MySQL accounts are identified by both a name and a host, so ‘shop_app’@’localhost’ and ‘shop_app’@’%’ are different accounts with separate passwords and grants.
CREATE USER 'shop_app'@'localhost' IDENTIFIED BY 'use-a-long-random-password'; GRANT SELECT, INSERT, UPDATE, DELETE ON shop_db.* TO 'shop_app'@'localhost'; SHOW GRANTS FOR 'shop_app'@'localhost';
CREATE USER makes the account; replace the sample password with a long generated value stored in your deployment secrets, never in a shared document. The GRANT line allows reading and writing rows in every table of shop_db, which suits a typical web app, while withholding destructive and structural rights such as DROP and ALTER. The host part localhost limits the account to connections from the same machine; use a specific application server address instead of the wildcard percent host whenever you can. SHOW GRANTS prints the resulting permissions exactly as the server stored them, so you can confirm the grant landed as intended rather than assuming it did. In MySQL 8, grants take effect immediately, so the old habit of running FLUSH PRIVILEGES after GRANT is unnecessary; that command is only needed after directly editing the grant tables by hand, which you should avoid.
ALTER USER 'shop_app'@'localhost' IDENTIFIED BY 'a-new-long-random-password'; REVOKE DELETE ON shop_db.* FROM 'shop_app'@'localhost'; DROP USER 'old_app'@'localhost';
ALTER USER with IDENTIFIED BY rotates a password, the correct move after a suspected leak or a staff change. REVOKE removes a single privilege, here DELETE, leaving the rest intact; follow it with SHOW GRANTS to confirm the new state. DROP USER removes an account entirely, which is the right ending for a retired application. Audit accounts a few times a year by listing them from the mysql.user table, and remove anything nobody can explain. Least privilege is not a one-time setup; it is this small recurring tidy-up.
SELECT user, host FROM mysql.user ORDER BY user, host;
This one line lists every account on the server. Duplicate names with different hosts are normal, but an unfamiliar account, or any account allowed from the wildcard host with broad rights, deserves a question. Pair the list with SHOW GRANTS for anything suspicious, and keep the results with your access review notes.
Backing Up With mysqldump
mysqldump is the standard command-line backup tool. It writes a text file of SQL statements that can rebuild a database from scratch. Run it from your shell, not from inside the MySQL prompt. The basic form names the user, asks for a password prompt with -p, names the database, and redirects output into a file.
mysqldump -u root -p shop_db > shop_db-backup.sql mysqldump -u root -p --single-transaction --routines shop_db > shop_db-full.sql mysqldump -u root -p shop_db orders customers > orders-customers.sql
The first command dumps the whole shop_db database into one file. The second adds two valuable options: –single-transaction takes a consistent snapshot of InnoDB tables without locking writers out, which is the right choice for a live site, and –routines includes stored procedures and functions that a plain dump leaves behind. The third form backs up only the named tables, useful for copying reference data between environments. Date your backup filenames in practice, compress large dumps with your usual archive tool, and store at least one copy off the server itself. A backup that lives only on the machine it protects fails in exactly the scenarios you most need it.
Restoring a Backup and Importing Data
Restoring is the reverse trip through the mysql client. Create the empty target database first, then feed the dump file in. Test restores on a spare database regularly; an untested backup is a hope, not a plan, and restore day is the worst time to discover a truncated file.
mysql -u root -p -e "CREATE DATABASE shop_db_restore;" mysql -u root -p shop_db_restore < shop_db-full.sql mysql -u root -p -e "USE shop_db_restore; SHOW TABLES;"
The first line creates the restore target using -e to run one statement from the shell. The second imports the dump, recreating tables and inserting rows; large files can take a while, and errors print with the offending line number, which helps locate corruption. The third line verifies the result by listing tables, and you should follow it with row counts on key tables and a quick application login against the restored copy. For moving a single table between servers, dump just that table, import it the same way, and rely on the comparison habits from sql joins explained when you reconcile the two copies afterwards.
For loading a CSV into an existing table, LOAD DATA INFILE is the fast path when the server setting allows it, with the file columns mapped in order and the first row skipped when it holds headers. Small imports are often simpler from a graphical tool, but the SQL form is scriptable and repeatable, which is what maintenance work needs.
LOAD DATA INFILE '/var/lib/mysql-files/products.csv' INTO TABLE products FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS (product_name, category, price, stock);
Each clause describes the file format: fields separated by commas, text enclosed in double quotes, one row per line, the header row ignored, and the target columns listed in file order. The file must sit in the folder allowed by the secure_file_priv setting, which is why the path above uses the standard import directory. Check the affected rows and any warnings with SHOW WARNINGS right after loading, because skipped or truncated values are reported there rather than failing the whole import.
Watching Processes and Fixing Everyday Snags
When an application slows down, the process list shows what the server is doing right now. A long-running query, a lock wait, or a flood of sleeping connections each has a recognisable shape, and each has a different fix.
SHOW FULL PROCESSLIST; SHOW STATUS LIKE 'Threads_connected'; EXPLAIN SELECT id, product_name FROM orders WHERE customer_id = 42;
SHOW FULL PROCESSLIST lists active connections with their state, duration, and full query text, so a query running for hundreds of seconds stands out immediately. Note its id if you need to stop it with KILL, and prefer fixing the cause over repeated kills. SHOW STATUS with Threads_connected reports how many connections are open, a quick capacity check when an app starts refusing logins. EXPLAIN shows the plan for a SELECT, including which index it uses and how many rows it expects to scan; a full table scan on a big table explains slowness more often than any server setting. Index and plan reading grows naturally out of the summary work in sql group by having, since grouped reports are usually the heaviest queries on a small site.
Two more checks round out the kit. CHECK TABLE reports whether a table passes a basic integrity check, and OPTIMIZE TABLE can reclaim space after very large deletions on some engines, though InnoDB usually manages space well enough that optimisation is an occasional, scheduled job rather than a weekly ritual. Record what you ran and what changed in a short ops note each time. Six months later, that note is the difference between repeating a known fix in minutes and rediscovering it under pressure.
Conclusion
Everyday MySQL administration is a handful of repeatable moves: inspect with SHOW and information_schema, create least-privilege users and verify them with SHOW GRANTS, back up with mysqldump using a consistent snapshot, rehearse restores, and watch the process list when things slow down. Keep passwords in secrets storage, date your backups, and verify after every change. Those small disciplines keep a database boring, which is the highest compliment admin work can earn.
Tagged: database tables mysql admin mysql queries mysql tips mysql users mysqldump backup



One thought on “MySQL Everyday Queries: Users, Backups and Table Information”