Skip to content

Managing MySQL databases, users, and tables from the command line

Managing MySQL Databases, Users, and Tables from the Command Line
Learn how to create, manage, and delete MySQL databases, users, and tables directly from the command line.

  1. Log in to MySQL as the root user:
mysql -u root -p
  1. Enter the MySQL root password.
  2. To create a database user:
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';

This grants all permissions on all databases. To limit permissions, use specific privileges:

GRANT SELECT ON *.* TO 'username'@'localhost';

Or for a single database:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'localhost';
  1. Exit MySQL:
\q
  1. Log in as the new user:
mysql -u username -p
\
Create a new database:
CREATE DATABASE dbname;
USE dbname;
  1. Create a table and insert data:
CREATE TABLE example (
id smallint unsigned NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
CONSTRAINT pk_example PRIMARY KEY (id)
);
INSERT INTO example (id, name) VALUES (NULL, 'Sample data');
  1. Create a user as shown above.
  2. Create a file example.sql and include:
CREATE DATABASE dbname;
USE dbname;
CREATE TABLE tablename (
id smallint unsigned NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
CONSTRAINT pk_example PRIMARY KEY (id)
);
INSERT INTO tablename (id, name) VALUES (NULL, 'Sample data');

Replace dbname and tablename with your preferred names.

  1. Run the script:
mysql -u username -p < example.sql
  • Delete a table:
DROP TABLE tablename;
  • Delete a database:
DROP DATABASE dbname;

Warning: MySQL does not confirm deletion; all data will be lost immediately.

  • View all users:
SELECT user FROM mysql.user GROUP BY user;
  • Delete a user:
DELETE FROM mysql.user WHERE user = 'username';

For full MySQL documentation, visit MySQL Reference Manual.