Sign In
Sign In

How to Create Tables in MySQL

How to Create Tables in MySQL
Hostman Team
Technical writer
MySQL
27.06.2024
Reading time: 13 min

Data starts with creating tables. Relational tables must follow certain rules. In MySQL, special queries are used to create tables, specifying the attributes (fields) of the table and the data types for each field and optionally providing field descriptions.

In this article, we will describe how to work with tables in MySQL, explain the CREATE TABLE syntax, and show you how to create tables and properly enter data. 

Creating Tables in MySQL

There are three main ways to create tables.

  1. If the table is created from scratch, the first commands must describe all fields. For this, MySQL uses the CREATE TABLE statement with the following syntax: 

CREATE TEMPORARY  TABLE IF NOT EXISTS table_name

column_name_1 data_type_1,
column_name_2 data_type_2, 
...,
column_name_N data_type_N,
) ;

Required parameters: 

  • table_name is the name of the table being created (must be unique, and for convenience, the name should describe what the table represents); 

  • column_name_1 is the name of the column; 

  • data_type_1 defines the type of data that will be stored in the column. 

Optional parameters: 

  • TEMPORARY. If used in the statement, a temporary table is created. It exists only in the current session and disappears when reconnecting to the database. Temporary tables are usually used to store intermediate data during complex selections. Only the user who created it has access to the temporary table. 

  • IF NOT EXISTS prevents an error if a table with that name already exists. It does not check if the structure of the existing table matches the one we tried to create; it only checks the name.

  1. The second way to create a table in MySQL is based on a query: 
CREATE TEMPORARY  TABLE IF NOT EXISTS table_name

column_name_1 data_type_1,
column_name_2 data_type_2, 
...,
column_name_N data_type_N,

IGNORE | REPLACE
AS query_expression;

Required parameter: 

  • query_expression is an SQL query based on the results of which the table is created. For example, the query might look like this: 
SELECT id, column_1 FROM table WHERE id > 15 

Optional parameter: 

  • IGNORE | REPLACE specifies how to handle rows that duplicate unique key values. The full query statement might look like this: 
CREATE TABLE movies_copy 
(id INT, title CHAR(50) UNIQUE, year YEAR, summary TEXT)
IGNORE
SELECT id, title, year, storyline as summary FROM movies;
  1. The third way is when a new table is created based on the structure of another table. We can say that we are copying another table:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] table_name
LIKE old_tbl_name;
  • old_tbl_name is the name of the table we want to "clone". 

This method creates a table with the same structure as the original but does not copy the data stored in it. We get the same table but empty. 

Data Types in MySQL

MySQL supports various data types. Choosing the right type significantly affects the performance of the database, especially with large sizes. All data types can be divided into several groups. 

Numeric Data Types

Numeric types are divided into integer and floating-point.

To store integers, data types TINYINT, SMALLINT, MEDIUMINT, INT, or BIGINT are used. Each of them allows storing values in the range from -2(N-1) to 2(N-1)-1, where N is the number of bits required for storage. If necessary, it is possible to use the UNSIGNED attribute to disallow negative values. In this case, the value range can be shifted to start from 0, for example, from 0 to 255 for TINYINT. The most common data type is INT.

MySQL uses three data types for floating-point numbers:

  • FLOAT (uses 4 bytes) — stores up to 24 decimal places;

  • DOUBLE (uses 8 bytes) — stores up to 54 decimal places;

  • DECIMAL (the number of bytes depends on the chosen precision).

The DECIMAL data type is used to store exact fractional numbers. For example, it is used for storing financial data where precise results are needed during calculations. Synonyms (aliases) for DECIMAL include NUMERIC, DEC, and FIXED. For DECIMAL, you can choose the number of values you want to see before and after the decimal point, which determines the number of bytes it will use. DECIMAL can take two parameters DECIMAL(precision, scale). The precision parameter specifies the maximum number of digits the number can store, ranging from 1 to 65. The scale parameter specifies the maximum number of digits the number can contain after the decimal point, ranging from 0 to the precision value, with a default of 0. For example, with parameters DECIMAL(5,2), you can store the number 69839.12 or 71468.2.

Character (String) Data Types

  • CHAR has a fixed length of up to 255 characters. It is useful when you need to store short strings or when all data is approximately the same length. Since the length is fixed, the allocated space is also fixed. If the table is created with CHAR(10) (10 is the length of the string to be stored), all strings will have a length of 10. If fewer characters are entered, the remaining space will be filled with spaces, meaning that space in the database is allocated for nothing.
  • VARCHAR stores variable-length character strings from 0 to 65535 characters, provided the MySQL version is higher than 5.0.3. It is useful when you do not know the length of the text to be stored. It uses only the necessary amount of space for the data.
  • TEXT is intended for storing large amounts of character data. There are 4 types of TEXT: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. They differ in the maximum length of the string they can contain. Due to its size, it is often stored separately, sorted differently, and not indexed to full length. The BLOB family has similar features. These data types can store large amounts of information in binary form. The BLOB family is very similar to TEXT. BLOB types include TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.
  • ENUM stores a predefined set of string values specified when the column is created. It is suitable if a field frequently repeats certain values that are few and the list doesn't need frequent updates, such as car body types or planets in the solar system. All these values are stored as integers and take up less space than strings, using 1-2 bytes.
  • SET is a string object that can contain 0 or more values, each chosen from a predefined list specified when the table is created (maximum size is 64 elements). For example, to store book genres in a column with a SET type. SET stores values as integers, using 1-8 bytes.

Date and Time Data Types

Several types are available for date and time.

  • DATE stores only the date in 'YYYY-MM-DD' format and uses 3 bytes.
  • TIME stores only the time in 'hh:mm:ss' format and uses 3 bytes, with a range from '-838:59:59.00' to '838:59:59.00'.
  • YEAR stores the year, with a range of 1901-2155, using 1 byte.
  • DATETIME uses 8 bytes. It allows storing values from the year 1001 to 9999 with a precision of 1 second in the format: 'YYYY-MM-DD hh:mm:ss'. It is not dependent on the time zone.
  • TIMESTAMP uses 4 bytes, thus having a much smaller date range: from '1970-01-01 00:00:01' to '2038-01-19 03:14:07'. It is stored as the number of seconds elapsed since the Unix epoch (January 1, 1970, GMT). The displayed value depends on the time zone. Later versions added support for storing time in microseconds.

When both date and time are needed, two types are required: DATETIME and TIMESTAMP.

Constraints in MySQL

To ensure database integrity, MySQL uses specific constraints (CONSTRAINT). They can be divided into two types: column-level and table-level constraints (applied to a specific column or the entire table). Constraints are declared during table creation. They include:

  • NOT NULL — indicates that the column cannot contain a NULL value.

  • UNIQUE — prevents duplicate values (all values in the column must be unique).

  • PRIMARY KEY — only unique non-NULL values can be stored in the column. Only one such column can exist in a table.

  • FOREIGN KEY — creates a relationship between two tables based on a specific column.

  • CHECK — controls the values in the column, checking if they are acceptable.

  • DEFAULT — sets a default value for the column. If the field is omitted when entering a record, the default value will be inserted.

Index Types in MySQL

An index is a structure that stores the value of a table column (or several columns) and references the rows where these values are located. Creating indexes helps increase MySQL's efficiency, significantly speeding up queries. Most indexes have a tree-like data structure (are B-tree indexes). Indexes take up memory space, so typically only the fields that are used for data retrieval are indexed. Without an index, a query search goes through all table records, which can be time-consuming and computationally intensive. 

Indexes in MySQL speed up operations:

  • Searching for rows matching a WHERE query;

  • Retrieving rows during joins;

  • Finding minimum (MIN()) and maximum (MAX()) values of a specific indexed column;

  • Sorting or grouping tables, provided the operation uses the leftmost prefix of the used index.

There are following types of Indexes in MySQL

  • Primary key — This column uniquely identifies each row in the table. Usually specified when creating the table. If not done manually, MySQL will create a hidden key. The primary key contains unique values. If it consists of several columns, the combination of values must be unique. The primary key cannot have NULL values. A table can have only one primary key.

  • Unique index — Ensures the uniqueness of values in one or more columns. Unlike the primary key, you can create many unique indexes. It can have NULL values.

  • Composite index — An index on multiple columns. MySQL allows creating composite indexes containing up to 16 columns. Typically used to speed up queries that need to retrieve data from multiple fields.

Indexes are not recommended for small tables. The improvement from using indexes will not be noticeable. Indexes should be created primarily for slow queries or the most frequently used ones. Collect query performance statistics and conduct an assessment to determine this. Creating indexes for everything is not a good idea.

Example 1: Creating a Table

Let's create a MySQL table from scratch to store a collection of movies:

CREATE TABLE movies (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title CHAR(100) NOT NULL,
year YEAR NOT NULL,
running_time_min INT NOT NULL,
storyline TEXT
);

This table includes the following columns:

  • id: Unique identifier for the movie.

  • title: The movie's title.

  • year: The release year of the movie.

  • running_time_min: The movie's duration in minutes.

  • storyline: A brief description of the movie's plot.

All fields have the NOT NULL constraint. The primary key is the id field. Initially, the table only has columns with specified data types. 

Now let's insert some data into the table. For this, MySQL uses the INSERT INTO statement with VALUES.  

INSERT movies3(title, year, running_time_min, storyline) 
VALUES ('Harry Potter and the Philosophers Stone', 2001, 152, "An orphaned boy enrolls in a school of wizardry, where he learns the truth about himself, his family and the terrible evil that haunts the magical world."),
('Harry Potter and the Chamber of Secrets', 2002, 162,"An ancient prophecy seems to be coming true when a mysterious presence begins stalking the corridors of a school of magic and leaving its victims paralyzed."),
('The Green Mile', 1999, 188,'Death Row guards at a penitentiary, in the 1930s, have a moral dilemma with their job when they discover one of their prisoners, a convicted murderer, has a special gift.'),
('Forrest Gump', 1994, 142,"The presidencies of Kennedy and Johnson, the Vietnam War, the Watergate scandal and other historical events unfold from the perspective of an Alabama man with an IQ of 75, whose only desire is to be reunited with his childhood sweetheart."),
('Cast Away', 2000, 143,"A FedEx executive undergoes a physical and emotional transformation after crash landing on a deserted island.");

The result will be this table:

Image1

Example 2: Creating a Table from a Query

Now, let's create a table based on a query. We will select all movies released after 1999:

CREATE TABLE movies_query 
AS
SELECT id, title, year, running_time_min 
FROM movies 
WHERE year > 1999;

The result:

Image3

Example 3: Creating a Table Based on Another Table's Structure

We can create a table based on the structure of another table:

CREATE TABLE movies_copy 
LIKE movies;

This creates an empty table with the same structure as the movies table but without data.

Image2

Foreign Keys

When there are multiple tables in a database, you might need to link them. Foreign keys are used in MySQL for this purpose. A foreign key is a column (or group of columns) that creates a relationship between tables. It refers to the primary key in another table. The table with the primary key is called the parent table, and the table with the foreign key is the child table.

Creating a Foreign Key

CONSTRAINT symbol FOREIGN KEY
index_name (col_name, ...)
REFERENCES tbl_name (col_name,...)
ON DELETE reference_option
ON UPDATE reference_option

Mandatory Parameters:

  • FOREIGN KEY [index_name] (col_name, ...): Specifies the field to be used as a foreign key.

  • index_name: Name of the index.

  • col_name: Name of the column.

  • REFERENCES tbl_name (col_name, ...): Specifies the column of the parent table with which our foreign key will be associated.

  • tbl_name: Name of the table.

  • col_name: Name of the column.

Optional Parameters:

  • CONSTRAINT symbol: Used to create and delete constraints.

  • ON DELETE/ON UPDATE: Defines what to do when the parent table is deleted or updated. Options include:

    • CASCADE: Automatically deletes or updates records in the child table when the parent table's records are deleted or updated.

    • SET NULL: Sets the value to NULL in the child table when the parent table's records are deleted or updated.

    • RESTRICT: Prevents deletion or updating of records in the parent table if they are used in the child table.

Example 4: Creating a Table with a Foreign Key

Let's create a table for movie genres:

CREATE TABLE genres (
id INT AUTO_INCREMENT PRIMARY KEY,
genre VARCHAR(200) UNIQUE NOT NULL
);

Populate the table:

INSERT INTO genres (genre) 
VALUES ('drama'),
('fantasy'),
('sci-fi'),
('cartoon');

We will get the id for each genre.

Example of creating a new table in MySQL with a FOREIGN KEY:

CREATE TABLE movies2 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title CHAR(100) NOT NULL,
year YEAR NOT NULL,
running_time_min INT NOT NULL,
genre_id INT,
FOREIGN KEY (genre_id) REFERENCES genres (id)
);

Our table:

Image4

To display the genres instead of just numbers, you can use a LEFT JOIN with the genres table:

SELECT movies2.id, title, year, genre 
FROM movies2
LEFT JOIN genres ON genres.id = genre_id;

Image6

Manipulating Tables

Various commands can be used to work with an already created table. Here are some basic MySQL commands for renaming, modifying, deleting, and adding columns, and changing data types.

Renaming a Table

Option 1. Used if we initially indicated which database we were working in:

USE movies_db;
RENAME TABLE movies2 TO cinema;

Option 2. Applies if the database is not specified:

RENAME TABLE movies_db.movies2 TO movies_db.cinema;

You can also use the RENAME TABLE command to move a table from one database to another:

RENAME TABLE movies_db.movies2 TO cinema_db.cinema;

Adding a New Column

In MySQL, the ALTER TABLE statement is used to change a table in some way.

ALTER TABLE cinema
ADD Language VARCHAR(50) NULL;

Deleting a Column

ALTER TABLE cinema
DROP COLUMN Language;

Renaming and Modifying Columns

Use the CHANGE command to rename and redefine a column:

ALTER TABLE cinema CHANGE year date INT NOT NULL;

If you don't want to change the column name, specify the old name twice:

ALTER TABLE cinema CHANGE year year INT NOT NULL;

Use the MODIFY command to change the column definition without renaming it:

ALTER TABLE cinema
MODIFY COLUMN title VARCHAR(100);

Use the RENAME COLUMN command to change a column's name:

ALTER TABLE cinema RENAME COLUMN running_time_min TO running_time;

Deleting Operations

To clear a table of data, use the TRUNCATE TABLE command:

TRUNCATE TABLE cinema;

To completely remove a table from the database, use the DROP TABLE command:

DROP TABLE cinema;

Adding and Removing Foreign Keys

To add a foreign key:

ALTER TABLE cinema
ADD FOREIGN KEY (producer_id) REFERENCES producer (Id);

Conclusion

These operators and examples cover the basic operations with tables, enabling you to perform many useful tasks. These skills can be applied, including for working with MySQL cloud databases deployed on platforms like Hostman.

MySQL
27.06.2024
Reading time: 13 min

Similar

MySQL

How to Show Users in MySQL

MySQL stands as a widely recognized relational database system, extensively utilized for handling structured data. It provides administrators with robust utilities to oversee users' accounts effectively. Whether the goal is to retrieve a full user list, check access rights, or filter specific accounts, MySQL offers multiple ways to accomplish these tasks. Understanding these methods can help ensure better control over database security and access management. In this write-up, we’ll explore all possible approaches to show users in MySQL. Prerequisites Before proceeding, ensure you meet these prerequisites: MySQL is set up on your machine. Superuser permissions for MySQL (root or an account with sufficient rights). A MySQL interface (such as MySQL Shell, Workbench, or a command terminal with the MySQL CLI tool). Understanding MySQL Users In MySQL, accounts represent users who can interact with the database by executing tasks like reading, updating, or deleting data. Each account consists of a username and a host, which specifies the allowed connection source. For instance, 'user'@'localhost' restricts access to the same computer where MySQL is running, whereas 'user'@'%' allows access from any IP address(location). We can handle user accounts with simple commands, as illustrated below: Task Command Create User CREATE USER 'anees'@'localhost' IDENTIFIED BY 'password'; Grant Permissions GRANT ALL PRIVILEGES ON mydb.* TO 'anees'@'localhost'; See Existing Users SELECT user, host FROM mysql.user; Delete User DROP USER 'anees'@'localhost'; MySQL controls user access using privileges, ensuring that each account can execute only permitted actions, thereby maintaining database security. Different Methods to Show MySQL Users MySQL offers multiple ways to view user accounts, each designed for a particular need. Whether you require a basic user list, detailed account insights, or filtered results, MySQL offers flexible options to fetch user details. Common approaches include querying the mysql.user table, executing SHOW GRANTS to review privileges, and using SELECT statements with filtering conditions. These methods help database administrators effectively manage accounts, maintain secure access, and enforce proper control within the database. 1. Querying the mysql.user Table The mysql.user is MySQL's built-in system table that stores all user account details, including usernames, host specifications, authentication methods, and assigned privileges. Administrators can retrieve data from this table to gain a comprehensive view of all accounts and their respective access rights. It plays a crucial role in auditing permissions, checking authentication plugins, and filtering users based on defined parameters. However, accessing this table requires administrative rights, and the privilege data may appear intricate for those unfamiliar with its structure. Despite this, it remains one of the most detailed and effective tools for handling user accounts in MySQL. Here’s how to fetch all users using this table: SELECT User, Host FROM mysql.user; The User column depicts account names, while the Host column indicates the originating host that allows user connections: 2. Retrieving Unique Users with DISTINCT In MySQL, the DISTINCT clause can be applied within a SELECT statement on the mysql.user table to retrieve distinct user accounts. Since MySQL associates each account with both a username and a host, the same username may appear multiple times with varying host values. Utilizing DISTINCT removes redundant usernames, yielding a streamlined list of unique accounts. This approach is particularly beneficial for obtaining a summarized view of all database users, especially in environments where multiple hosts are involved: SELECT DISTINCT User FROM mysql.user; This technique is ideal when you require only the usernames without including host-related details. 3. Extracting User Privileges with SHOW GRANTS The SHOW GRANTS statement in MySQL helps us extract the permissions granted to a particular user. SHOW GRANTS presents access rights in a structured format that mirrors the GRANT commands used to grant those privileges. This feature makes it an essential tool for reviewing user privileges and ensuring security compliance. Employ this command to fetch a particular user alongside its access rights: SHOW GRANTS FOR 'user'@'host'; Substitute the username and host with the relevant user information, as depicted in the snippet below: 4. Checking Users via MySQL Workbench This method offers a graphical interface (GUI) for handling MySQL user accounts, making it suitable for those who prefer a visual approach over command line operations (CLI). MySQL Workbench enables users to view existing accounts, assigned roles, and granted privileges via its Users and Privileges section. This structured view reduces the risk of errors compared to manually running SQL commands, making it beginner-friendly.  To view user accounts in MySQL Workbench, launch the application and establish a connection to your MySQL server: Next, in the Navigator panel, choose Administration, expand the Management section, and click the "Users and Privileges" to access the user management window: Within the Users tab, a list of existing MySQL user accounts alongside their corresponding hosts will be displayed: We can choose a user to review or modify its privileges, authentication method, and other settings. Fetching Logged-In User Details in MySQL The SELECT USER(); query in MySQL fetches the current session’s authenticated user, including the originating host. It’s a fast and efficient way to examine the active user without needing additional tools or administrative rights. This method works on all MySQL installations, including remote connections, and has minimal system overhead. However, it only exhibits the authenticated user and lacks information regarding roles or permissions: SELECT USER(); The resultant outcome demonstrates that root@localhost is currently logged in user on our system: Alternatively, we can employ the below-listed query to fetch the current user details: SELECT CURRENT_USER(); How Can We Check the Existence of a Particular User in MySQL? To confirm if a particular MySQL account is available, we can query the mysql.user table with the EXISTS clause. The succeeding command checks for a user’s presence: SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username' AND host = 'host'); It returns one if the account is present and zero if not: If you are uncertain about the host, you may exclude the host condition or execute the command below: SELECT User, Host FROM mysql.user WHERE User = 'anees'; If the desired account is found, it depicts the username and hostname; otherwise, it shows "Empty Set": Effective Ways to Display MySQL Accounts Here are key guidelines to follow for efficient handling and presenting MySQL accounts to maintain security and streamline user administration: To efficiently handle MySQL accounts, ensure you have administrative privileges before running commands like retrieving data from the mysql.user table or utilizing SHOW GRANTS. Avoid revealing confidential details such as passwords by only selecting the necessary columns, like User and Host, rather than employing "SELECT *". When searching for certain user accounts, apply WHERE to refine the results and avoid fetching irrelevant data. To obtain a refined list of distinct accounts, apply DISTINCT, as MySQL records users with both their usernames and hosts. To depict a user's permissions in a clear format, execute SHOW GRANTS FOR 'username'@'hostname';.  If you're not comfortable with the command line interface, utilize MySQL Workbench, which provides a user-friendly interface to handle accounts. Ensure limited access to the mysql.user table to protect sensitive data, and periodically audit user accounts and privileges to maintain security. Conclusion Effectively handling MySQL users/accounts is crucial for enhancing security and proper access control within your database. Whether you're using SQL queries like SELECT and SHOW GRANTS, or MySQL Workbench for a more intuitive experience, multiple approaches are available for listing and managing accounts. It's important to consider optimal practices, such as using appropriate privileges, limiting data exposure, and regularly auditing user accounts, to ensure your MySQL setup remains secure. In this write-up, we explained how to confidently manage users, monitor permissions, and uphold the reliability of your database system.
13 February 2025 · 7 min to read
MySQL

How to Create a MySQL Database Dump

MySQL is the most popular relational database management system that performs various operations with tables, such as adding, deleting, searching, sorting, and outputting data based on user queries. It's important to understand that MySQL controls databases but is not itself a database. Therefore, MySQL and the database are separate entities: MySQL is a program that operates on information. The database is the information recorded on a hard disk. Based on this architecture, MySQL supports exporting information — creating a database dump. This functionality allows several useful operations: Database Backup: Unexpected situations when using cloud (or local) servers can lead not only to system failures but also to data loss. Therefore, it’s important to regularly create database dumps, which can be stored on other secure storage devices. Database Transfer from One Server to Another: Manually copying database elements may be challenging or impossible when migrating from one server to another. A dump makes it possible to transfer data quickly. A database dump is essentially a sequential set of SQL instructions that create an exact copy of the original database, including both its structure and content. This guide will cover the primary methods for creating a database dump and importing it back into MySQL to restore data. Preparing a Test Database We will create a cloud database to test the examples in this guide. If you already have a MySQL database where you can test the dump creation function, you can skip this step. In the Hostman panel, we will create a MySQL 8 database, leaving all other parameters as default. You can connect to the cloud database via a terminal. The necessary command can be copied from the control panel. Let's connect to our database: mysql -u USER -p'PASSWORD' -h HOST -P 3306 -D DATABASE For example, a real connection command might look like this: mysql -u gen_user -p'sU}NEyx#<2P~\e' -h 91.206.179.29 -P 3306 -D default_db Next, we need to create a simple table consisting of three columns: CREATE TABLE People ( id INT, name VARCHAR(255) NOT NULL, bord DATE ); And populate it with some values: INSERT INTO People VALUES (120, 'Natalie', NOW()), (121, 'Meredith', NOW()), (122, 'James', NOW()); This fills the new database so that we can later create a dump from it. By the way, on the Users tab of the database management page, there are buttons that open interfaces for graphical MySQL database administration tools — phpMyAdmin and Adminer. Method 1: Console Terminal A more traditional but less interactive way to create a MySQL database dump is by using the appropriate command in a console terminal. To do this, you need to connect to MySQL via an SSH connection and then enter the dump creation command: mysqldump -u USER -p'PASSWORD' -h ADDRESS -P PORT DATABASE > FILE Let's break down each of the specified parameters: USER: The username used to authenticate in MySQL. PASSWORD: The password for the user to authenticate in MySQL. ADDRESS: The IP address of the remote MySQL server. PORT: The port of the remote MySQL server. DATABASE: The name of the database to be dumped. FILE: The name of the file where the database dump will be saved on the local machine. There are two possible ways to create a dump via the console: Local MySQL: The dump is created from a database located on a local MySQL server. In this case, we don’t need to specify the ADDRESS and PORT parameters. Remote MySQL: The dump is created from a database located on a remote MySQL server. In this case, you need to specify ADDRESS and PORT. Local MySQL dump command example: mysqldump -u admin -p'qwerty123' default_db > just_dump.sql Remote MySQL dump command example: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db > just_dump.sql In both cases, for security reasons, you can omit the explicit password specification — this way, the system will prompt you to enter the password manually: mysqldump -u admin -p default_db > just_dump.sqlmysqldump -u admin -p -h 91.206.179.29 -P 3306 default_db > just_dump.sql Warnings and Errors After executing the command, several warnings and errors may appear in the console output. Let’s break down each message in detail. Password Security Warning The first warning from MySQL notifies you about the insecurity of using a password as an explicit parameter: mysqldump: [Warning] Using a password on the command line interface can be insecure. To suppress this warning, use the -p flag without specifying the password directly. Global Transaction Identifier (GTID) Warning The next warning concerns the inclusion of the Global Transaction Identifier (GTID) in the resulting dump and suggests disabling it with the --set-gtid-purged=OFF flag: Warning: A partial dump from a server that has GTIDs will by default include the GTIDs of all transactions, even those that changed suppressed parts of the database. If you don't want to restore GTIDs, pass --set-gtid-purged=OFF. To make a complete dump, pass --all-databases --triggers --routines --events. GTID (Global Transaction Identifier) is a unique 128-bit identifier associated with each transaction, which improves overall data consistency. Disabling GTID may lead to data inconsistency (for example, due to duplication of certain SQL statements). Data Dump Consistency Warning Another GTID-related warning indicates that the dump operation is not atomic: Warning: A dump from a server that has GTIDs enabled will by default include the GTIDs of all transactions, even those that were executed during its extraction and might not be represented in the dumped data. This might result in an inconsistent data dump.In order to ensure a consistent backup of the database, pass --single-transaction or --lock-all-tables or --master-data. This means that database changes performed by other applications during the dump creation may be missing, leading to data inconsistency. To avoid this issue, use one of the following flags: --single-transaction to create the dump within a single transaction. --lock-all-tables to block any other operations on the database during the dump. Access Denied Error You might encounter an error preventing the dump creation due to insufficient privileges: mysqldump: Error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation' when trying to dump tablespaces Even if the user specified in the command has all database privileges, they may lack the global PROCESS privilege. To grant this privilege, execute the following command: GRANT PROCESS ON *.* TO 'admin'@'localhost'; However, this is not the best solution from a security perspective. Instead of granting global privileges, it's better to use the --no-tablespaces flag during the dump command execution. With all the additional flags, the dump creation command will look like this: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql In this case, only one harmless warning will remain about explicitly specifying the password: mysqldump: [Warning] Using a password on the command line interface can be insecure. Non-existent Database Error If you accidentally specify the name of a non-existent database, an unclear error will appear denying access to the database for the specified user: ERROR 1044 (42000): Access denied for user 'admin'@'%' to database 'default_db' This can cause confusion, so always double-check the accuracy of the database name specified in the command. Dump File After successfully executing the dump command, you can check the file system using: ls You should see the corresponding database dump file: just_dump.sql  resize.log  snap Although you can open this file in any text editor, its size may be quite large, especially if the original database contained a lot of information: cat just_dump.sql At the beginning of the file, there is information about the created dump, followed by SQL instructions: -- MySQL dump 10.13 Distrib 8.0.40, for Linux (x86_64) -- -- Host: 37.220.80.65 Database: default_db -- ------------------------------------------------------ -- Server version 8.0.22-13 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; ... /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2025-01-19 5:33:16 The output file doesn't have to be saved in the current directory; you can specify any other directory: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --no-tablespaces --set-gtid-purged=OFF --single-transaction > /tmp/just_dump.sql In this case, we create the dump file just_dump.sql in the /tmp directory. Dumping Multiple Databases In real projects, MySQL often handles multiple databases. You can use a special flag to dump all existing databases: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 --all-databases --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql This command differs from the previous one only in that the --all-databases flag is specified instead of a specific database name. Alternatively, you can list the databases you want to include in the dump: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 db_first db_second db_third --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql Structure Without Data You can create a dump containing only the database structure (table schemas) without any data by using the --no-data flag: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --no-data --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql Specific Tables Instead of dumping an entire MySQL database, you can dump only specific tables by listing their names after the database name: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db table1 table2 --no-data --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql On the other hand, you can dump a database excluding specific tables using the --ignore-table parameter: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --ignore-table=default_db.logs --no-data --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql Note that the table name must always be preceded by the database name and separated by a dot. To exclude multiple tables, list each one with the --ignore-table option: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --ignore-table=default_db.table1 --ignore-table=default_db.table2 --no-data --no-tablespaces --set-gtid-purged=OFF --single-transaction > just_dump.sql Character Encoding In some cases, it may be necessary to explicitly specify the character encoding for the dump: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --no-tablespaces --set-gtid-purged=OFF --single-transaction --default-character-set=utf8 > just_dump.sql Typically, UTF-8 is the preferred character encoding. Archiving the Dump Sometimes it’s useful to compress the dump immediately after creation. You can do this by piping the mysqldump output into gzip, then saving the compressed archive: mysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --no-tablespaces --set-gtid-purged=OFF --single-transaction | gzip > just_dump.sql.gz If you check the current directory with the ls command, you’ll see the compressed dump: just_dump.sql  just_dump.sql.gz  resize.log  snap Restoring Data A database dump is usually created to restore data in the future, for example, in case of data loss or server migration. To load the database dump into MySQL and restore data, use the following command: mysql -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db < just_dump.sql If the dump file size is too large, MySQL may have a default limit that prevents loading it. To adjust the maximum allowed dump size, you can use the --max_allowed_packet flag: mysql -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db --max_allowed_packet=64M < just_dump.sql In this example, the maximum allowed dump size is set to 64 MB. mysql -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 default_db < just_dump.sqlmysqldump -u admin -p'qwerty123' -h 91.206.179.29 -P 3306 --all-databases --no-tablespaces --set-gtid-purged=OFF > just_dump.sql Method 2: Using phpMyAdmin If you're using phpMyAdmin, creating a database dump can be done through the graphical interface without manually executing commands — phpMyAdmin handles everything for you. Log In to phpMyAdmin. Open the phpMyAdmin interface and log in with your credentials.  Select the database. In the left sidebar, choose the database you want to export. This will open a page displaying the list of existing tables within the selected database. Configure the export. Click the Export button. It will take you to a dedicated page to configure the database export (dump). You can also access the export page from the phpMyAdmin home page, but doing so may not display all databases available for export. It's better to first navigate to the specific database and then click Export. Note that phpMyAdmin allows exporting only databases that contain tables. Empty databases cannot be exported. There are two export options in phpMyAdmin: Quick Export. It creates the dump using default export settings. Custom Export. It Allows you to manually configure the export settings, such as excluding specific tables, changing character encoding, and adjusting format options. phpMyAdmin supports exporting to various formats beyond just SQL, such as PDF, JSON, CSV, YAML, and others. The configuration options for creating a dump in phpMyAdmin are more user-friendly and visually intuitive than command-line flags. Start the export. Once you've configured all the export parameters, scroll down and click the Export button. The dump file will be generated and downloaded through your browser. Method 3: Using Adminer Creating a database dump in Adminer is very similar to phpMyAdmin. In fact, Adminer’s graphical interface is even simpler. Log In to Adminer: Start by logging into Adminer, then navigate to the export page by clicking the Export link in the left sidebar. Configure the Export. Adminer does not have predefined export types, so the system immediately offers all configuration options. You can select specific database tables to include in the dump. The dump file can be either saved (in a specific format or as a GZIP archive) or opened in a new window for manual copying of SQL instructions. Conclusion The native way to create a MySQL database dump, without requiring additional tools, is by using the mysqldump command with additional parameters. An alternative is to use visual database management tools with graphical interfaces. Utilities like phpMyAdmin or Adminer simplify database interactions by providing a user-friendly and interactive environment. This is particularly useful for those who are not well-versed in SQL syntax, turning tasks such as creating a dump into a series of simple mouse clicks.
13 February 2025 · 12 min to read
MySQL

How to Import and Export Databases in MySQL or MariaDB

Database management is a crucial aspect of Linux server and web application administration. Importing and exporting databases are essential tasks for DevOps and system administrators. At a minimum, developers should know how to back up databases and transfer them between servers. This guide explains how to import and export database dumps in MySQL or MariaDB on a Linux server (using Ubuntu as an example). Working with Databases MySQL and MariaDB are popular relational database management systems (RDBMS) used for storing data in large applications. MariaDB is a fork of MySQL developed by its original creators due to licensing concerns following Oracle's acquisition of MySQL. Both MariaDB and MySQL share identical or similar APIs and operating mechanisms. Creating a Database Connect to MySQL or MariaDB with root privileges: For MySQL: mysql -u root -p   For MariaDB: mariadb -u root -p   Create a database (if it doesn't already exist): CREATE DATABASE IF NOT EXISTS <database_name>; Viewing Databases To see the list of available databases: SHOW DATABASES; Switching Databases To switch to a specific database: USE <database_name>; Viewing Tables To list all tables in the selected database: SHOW TABLES; Common SQL Commands Creating a table: CREATE TABLE IF NOT EXISTS users (  user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,  username VARCHAR(100) NOT NULL); This creates a table named users with fields user_id and username. Inserting data into the table: INSERT INTO users (username) VALUES ('John Doe'); This adds a new row to the users table. Selecting all rows from the table: SELECT * FROM users; Monitoring MySQL/MariaDB status To check the server's global status and statistics: SHOW GLOBAL STATUS; Exporting Databases Exporting data from MySQL or MariaDB can be efficiently done using the mysqldump CLI utility or third-party tools like phpMyAdmin. The mysqldump utility allows you to save your database as an SQL dump, which contains the necessary commands for creating columns and populating them with data. This dump file can be easily managed, imported, or transferred. You will need: A database you want to export. User credentials with at least read access to the database. In the terminal, run the following command: mysqldump -u <username> -p<password> <database_name> > db_dump.SQL Where: -p<password>: Password for the database user (you can omit the password and simply use -p to prompt for it manually). db_dump.SQL: The name of the output dump file. <username>: The privileged user with read access. <database_name>: The name of the database you are exporting. To create dumps from a remote server, add the -h flag: mysqldump -h <ip-address> -u <username> -p<password> <database_name> > db_dump.SQL If the MySQL server uses a non-standard port, specify it with the -P flag: mysqldump -h <ip-address> -P <port> -u <username> -p<password> <database_name> > db_dump.SQL While the default export format is SQL, mysqldump also supports exporting data as CSV, XML, and other formats by configuring additional parameters. The SQL dump typically includes: Information about the RDBMS (MySQL or MariaDB) Commands for creating the required tables and their columns Data to populate those columns By default, it provides a comprehensive snapshot of the database structure and contents, making it an essential tool for database backups and migrations. Importing Data into MySQL or MariaDB To import a database dump, you don’t need mysqldump; a direct call to MySQL will suffice. Run the following command in your terminal: mysql -u <username> -p<password> <new_database_name> < db_dump.SQL Where: -p<password>: The user's password (use -p without the password to be prompted manually). db_dump.SQL: The dump file containing your database data. <username>: A privileged user with write access. <new_database_name>: The name of the target database to which you are importing the dump. If the process completes successfully, there will be no output. If any errors or warnings occur, MySQL or MariaDB will display them. You can check if the import was successful with these commands: SHOW DATABASES;  -- Lists all databasesUSE <database_name>;  -- Selects the target databaseSHOW TABLES;  -- Lists all tables within the selected database By executing these commands, you can confirm that the database structure and data have been imported correctly. Creating a systemd Service for Backup Suppose you want to automate the database backup (export) process. In this guide, we will create a service-timer that will trigger a script for backing up data. A Timer is a mechanism used to schedule the execution of a specific service at a given time or through certain intervals. Follow these steps to set it up: First, connect to the server and create the directory for backup scripts: mkdir -p /usr/bin/backup_scripts  # Create directory for backup scripts Create and open the file /usr/bin/backup_scripts/mysql_backup.sh in any text editor (e.g., nano): nano /usr/bin/backup_scripts/mysql_backup.sh Inside the file, add the following script: TIMESTAMP=$(date +'%F') # Get the current date BACKUP_DIR='<path_to_backup_directory>' MYSQL_USER='<username>' MYSQL_PASSWORD='<password>' DATABASE_NAME='<database_name>' mkdir -p "$BACKUP_DIR/$TIMESTAMP" # Create directory for this date mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $DATABASE_NAME > "$BACKUP_DIR/$TIMESTAMP/$DATABASE_NAME-$TIMESTAMP.sql" # Create dump find "$BACKUP_DIR" -type d -mtime +28 -exec rm -rf {} \; # Delete backups older than 28 days Replace the placeholder variables with the actual backup directory path, MySQL user credentials, and the database name. Grant execution permissions to the script: chmod +x /usr/bin/backup_scripts/mysql_backup.sh Create the service file /etc/systemd/system/mysql-backup.service: sudo nano /etc/systemd/system/mysql-backup.service Add the following content: [Unit] Description=MySQL Database Backup Service [Service] Type=oneshot ExecStart=/usr/bin/backup_scripts/mysql_backup.sh [Install] WantedBy=multi-user.target Create the timer file: sudo nano /etc/systemd/system/mysql-backup.timer Add this content to schedule the backup: [Unit] Description=Run MySQL Backup Service Weekly [Timer] OnCalendar=weekly Persistent=true [Install] WantedBy=timers.target Reload the systemd configuration, enable the timer for autostart, and start it: systemctl daemon-reload  # Reload systemd configurationsystemctl enable mysql-backup.timer  # Enable timer to start automaticallysystemctl start mysql-backup.timer  # Start the timer Check the status of the timer and ensure it is working: systemctl status mysql-backup.timersystemctl list-timers  # Lists active timers Now, your system will automatically create a backup of the specified database every week. Export and Import via phpMyAdmin You can perform database imports and exports not only through command-line utilities but also through the phpMyAdmin web interface. This method is typically more convenient when the dump size is small (less than 1GB). This section will cover the basic process of importing and exporting databases. Export To export a database: Go to the phpMyAdmin interface and select the desired database from the left-hand panel. Click on the Export tab. Choose export method: Quick Export: Select this if you want a basic export with default settings. Custom Export: Choose this for more specific export options, such as selecting certain tables, formats, or compression methods. Click Export. To export specific tables: Click on the database name in the left sidebar to view its tables. Select the tables you want to export by checking the boxes next to their names. At the bottom of the page, choose Export from the list of actions. On the next page, verify the export format and options, then click Go to save the dump to your local machine. Import The process of importing a database is very similar to exporting. Follow these steps: Open phpMyAdmin and navigate to the database you want to import into. If the database doesn't exist, create it by clicking Create Database from the left sidebar. Inside the database, click on the Import tab. Click the Choose File button to browse for and select the SQL dump file from your device. Choose the necessary options like file encoding, format (typically default settings are fine), and other options as needed. Click Go to start the import process. Once the process is complete, you will see the imported files and their contents listed in the left sidebar. You can also modify them if needed. Conclusion The choice of method depends on your needs: phpMyAdmin is ideal for manually creating backups or for quick access to a database. It’s user-friendly and simple for small-scale tasks. Using command-line utilities would be more efficient and flexible for automation or if you’re transferring infrastructure.
10 February 2025 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support