Read this article in: Portuguese (Português) · Spanish (Español)
Creating users in MySQL and managing their permissions is a fundamental and indispensable step to ensure the integrity and security of any database management system (DBMS) in a corporate environment. The process goes far beyond simply providing a login; it establishes the level of access that each individual or application will have to the stored data, dictating whether the user can only view information or has the authority to alter or delete records. In a scenario where organizations, no matter how small, deal with ever-increasing amounts of data, granular access control offered by user management becomes the primary line of defense against leaks and unauthorized access.
The complexity of data management is an established fact in the technology market. While relational systems, such as MySQL and PostgreSQL, require predefined schemas with tables, columns, and rows, the universe of DBMSs is vast and diverse, including document-oriented models (like MongoDB) and columnar databases. It is precisely because of this diversity and the inherent responsibility of the DBMS—which is the software system responsible for managing data access, persistence, and manipulation—that security is crucial. An error in user management can compromise the reliability of the information a company needs.
In this complete guide, you will learn to master the process of creating users in MySQL, from the basic step-by-step to the most advanced scenarios. We will cover how to define permissions with the GRANT and REVOKE commands, how to configure host restrictions for remote users, and finally, how to apply security hardening best practices. By the end of this article, you will be able to solve common problems and build a robust and highly protected database architecture.
Key Points
- The Principle of Least Privilege requires that users have only the access strictly necessary for their role.
- Data Control Language (DCL) uses commands like GRANT and REVOKE to manage permissions.
- The CREATE USER command defines the user’s identity, name, and password, as well as the connection host.
- The @’host’ component restricts the attack vector, defining whether the access is local (localhost) or global (%).
- FLUSH PRIVILEGES must be executed after GRANT or REVOKE so that the changes are applied immediately.
Why managing users is crucial for your database’s security

A Database Management System (DBMS) is much more than just a digital repository; it acts as the critical interface between application programs and physical data files. Essentially, the DBMS is a complex set of programs whose primary function is to allow the secure storage, modification, and extraction of information. For any organization to ensure effective control over its data assets, it is imperative that the DBMS not only stores but also manages who can access and what can be altered. This is where user management assumes its central role in security.
Database security is not a passive feature, but rather an active control mechanism mediated by specific languages. Among the languages that make up the DBMS, Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL) stand out. It is DCL that provides the essential commands, such as GRANT and REVOKE, allowing the administrator to precisely define which users can interact with which data elements. Without this granular control, the database would be vulnerable to indiscriminate access.
📘 DCL
DCL (Data Control Language) is the language that provides essential commands, such as GRANT and REVOKE, for the administrator to define data access permissions.
The Principle of Least Privilege
The main reason why creating restricted users is crucial lies in applying the Principle of Least Privilege. This principle establishes that a user, whether human or an application service, should only have the privileges strictly necessary to perform their function, and nothing more. In a scenario where a single user, typically the superuser (such as root), performs all operations, the possibility of error or malice results in catastrophic risk. If the superuser is compromised, or if a code error in an application uses the superuser, the entire database is exposed.
Instead of relying on a single point of failure, creating multiple users with limited scopes—for example, one user for read-only reports, another for order entry, and a third for structure administration—isolates the risk. If the reports user is breached, the intruder will not have permission to modify critical data or delete tables. The DBMS, equipped with a good access control system, thus acts as a defense barrier, protecting sensitive data against improper access, whether resulting from an external attack or an internal application failure.
The basic step-by-step process for creating a new user in MySQL
After understanding the importance of the Principle of Least Privilege—which dictates that every user should only have the strictly necessary access for their role—the next step is to implement this security policy. Creating a user in MySQL is not just an administrative act, but the first step in establishing a robust layer of access control. If you don’t know how to start, check out our guide on how to create a MySQL database. While a database is a set of programs that allows information to be stored, modified, and extracted, it is user management that ensures these processes are executed by authorized entities and according to established business rules.
The mechanism for this management is Data Control Language (DCL), which, besides commands like GRANT and REVOKE, uses the CREATE USER command. This command is the basis for authentication because it defines the username and, crucially, where and how that user can connect to the server.
The Fundamental Command: Syntax and Components
The basic and universal syntax for creating a new user in MySQL is as follows: CREATE USER 'username'@'host' IDENTIFIED BY 'strong_password';. For this command to work correctly, it is vital to understand the meaning of each element:
username: This is the unique identifier that the system will use to recognize the account.strong_password: This is the authentication credential. The use of complex passwords is recommended to mitigate brute-force attacks.@'host': This is the most important component in terms of security and scope. It defines which machine or location the user can connect from. The choice ofhostdetermines whether the user is restricted to a specific environment or is allowed global access.
To illustrate the concept of host, there are two common use cases:
localhost: The user can only connect to the server from the machine where MySQL is installed. This is ideal for development applications or internal systems that will never be accessed remotely.'%'(wildcard): Using the percentage symbol indicates that the user can connect from any IP address. Although this offers greater flexibility, this option must be used with extreme caution, as it exposes the user to any machine on the network.
To execute user creation, the process is carried out through the command line, with administrative privileges. The sequence of steps ensures that the account is created and, subsequently, that the necessary permissions are assigned:
- Connect to the MySQL server as an administrator user (usually
root). - Execute the
CREATE USERcommand, defining the desired name, host, and password. - Verify that the user was created successfully.
- Use the
GRANTcommand to grant specific privileges (such asSELECTorINSERT) on the necessary databases. - Execute the
FLUSH PRIVILEGEScommand to ensure that permission changes are immediately applied to the system.
A practical example of how to create a user named analista, who can only access the database from the local machine (localhost), with a strong password, is as follows: See also: Discover the Magic Codes to Create Perfect Haze Pieces!.
CREATE USER 'analista'@'localhost' IDENTIFIED BY 'SenhaSegura123';
This syntax establishes the user’s identity, and the next step, which will be detailed in the permissions section, is to ensure that they only have access to the data required by their role, fully complying with the principle of layered security.
📊 Connection Restriction Comparison (Host)
| Restriction | Meaning | Ideal Use | Security |
|---|---|---|---|
| localhost | Only the local machine | Internal development | High |
| % | Any IP address | Broad remote access | Low (Caution) |
Defining Permissions: The GRANT and REVOKE Commands

After creating a user in the system, it is crucial to understand that the mere existence of the account does not guarantee the necessary access to the database resources. The database management system (DBMS) has advanced mechanisms, governed by Data Control Language (DCL), that allow granular control over what each user can do. This management is the core of security because it enforces the Principle of Least Privilege, ensuring that each account has only the strictly necessary access for its function. It is through DCL that we define the “data dictionary”—that is, who accesses which elements and under what conditions.
Granting Permissions with GRANT
The GRANT command is the tool used to assign specific rights to a user. It doesn’t just tell the system that the user exists, but rather what actions they are authorized to perform on a particular database or table. The basic syntax is structured to be precise, requiring the specification of the privilege, the resource (database), the user, and the connection host.
🧪 Common Permission Types
Granular control is achieved through commands like GRANT. Basic permissions include SELECT (read-only), INSERT (data addition), UPDATE (modification), and DELETE (removal). A reporting user, for example, only needs SELECT.
The general structure of the command is:
GRANT permissao ON nome_do_banco TO 'usuario'@'host';
When granting permissions, it is crucial to be surgical. Permissions such as SELECT (read-only), INSERT (adding new records), UPDATE (modifying existing data), and DELETE (removing records) are the most common. For example, a reporting user will only need SELECT, while a maintenance user will need INSERT, UPDATE, and DELETE. The host specification (such as localhost or %) complements the scope of the permission, defining where the access can occur.
Revoking Access with REVOKE
In scenarios involving role changes or in response to security issues, it is as important to know how to remove permissions as it is to grant them. The REVOKE command serves this function, allowing an administrator to withdraw previously granted rights. The revocation syntax follows a pattern similar to GRANT, specifying the permission to be removed from the user.
The structure is:
REVOKE permissao ON nome_do_banco FROM 'usuario'@'host';
To ensure that permission changes are applied immediately to the system, it is imperative to execute the FLUSH PRIVILEGES command after any use of GRANT or REVOKE. This step guarantees that the database management system recognizes the new set of access rules instantly, maintaining data integrity and security.
Advanced Scenarios: Remote Users and Host Restrictions
Creating a user in a Database Management System (DBMS) goes far beyond just defining a name and a strong password. In a high-security corporate setting, a user’s identity must be complete, and this includes knowing where they are accessing the system from. The @'host' component is the mechanism that establishes the user’s geographical and network scope, acting as a crucial layer of defense. Instead of just ensuring the credentials are valid, the host restricts the attack vector, ensuring that a user can only interact with the database from authorized machines.
Types of Host Restrictions and Their Impact on Security
The way the host is defined determines the level of remote access permission. It is imperative that the administrator chooses the level of restriction appropriate to the account’s usage profile:
@localhost: This is the highest level of restriction. The user is exclusively tied to the server where MySQL is installed. This means that access is only permitted if the connection is made internally, without going through the network. This is ideal for service accounts or applications that run on the same machine as the database.@ip_especifico: This is the most secure scenario for remote access. The administrator restricts the user to an exact IP address (or a set of addresses, such as a network block) that represents the location where the user or application is based. If an attacker tries to access the database from a location other than that IP, the authentication attempt will fail, even if the password is correct.@%(Wildcard): The use of the percentage symbol indicates that the user can connect from any IP address. While this setting is extremely practical in testing or initial development environments, it is considered a high security risk because it makes access global, exposing the user to any connection attempt from the internet.
The difference between these scenarios is not merely technical; it is a security decision. By restricting the host, the administrator is implementing a defense-in-depth policy. If a password is compromised (which can happen through leaks or brute-force attacks), the attacker is still limited to the defined scope. A user configured with @localhost or @ip_especifico is significantly more secure than a user with @%, because the host restriction acts as a second authentication barrier.
In a professional environment, the philosophy is always the principle of least privilege. If a user only needs to be accessed by a specific application server (and not by a home user, for example), using @ip_especifico is best practice. This minimizes the attack surface, ensuring that the database remains accessible only to trusted entities. In short, host restriction is an advanced hardening mechanism that elevates the security of your system beyond simple password management.
✅ Advantages
- @localhost: Maximum restriction, ideal for local services.
- @ip_especifico: More secure for remote access, restricts to an exact location.
- @% (Wildcard): Practical for testing and initial development.
❌ Disadvantages
- @localhost: Does not allow network access.
- @ip_especifico: Requires exact knowledge of the access IP.
- @% (Wildcard): High security risk, exposed global access.
Best practices and security hardening

User management in a Database Management System (DBMS) is not limited to merely creating a login and assigning a password. For any organization, effective control over data is a primary necessity, and security is the most critical line of defense. Security, in this context, is an operational philosophy that transcends technique; it is the principle of ensuring that access is limited to what is strictly necessary to perform the function. If the DBMS, through its Data Dictionary, describes who accesses the data, hardening is the process of ensuring that this access is as restricted as possible, protecting the integrity and confidentiality of the stored information.
The Principle of Least Privilege: The Golden Rule
One of the most common and dangerous mistakes in production environments is the unrestricted granting of permissions. The most advanced security philosophy requires the strict application of the Principle of Least Privilege. This means that when creating a user for an application or an analyst, the administrator must grant only the minimum essential rights for that account to fulfill its function. It is imperative, under no circumstances, to grant full-level permissions (such as the generic concept of ‘ALL PRIVILEGES’) to an application account. Furthermore, storage integrity is also crucial, and to understand how to optimize data resilience, check out our guide on how to create a RAID. For example, an application user who only inserts data (INSERT) should not have permission to drop tables (DROP) or modify the database structure (ALTER TABLE).
This granularity is what differentiates a well-managed database from a vulnerable system. Restricting privileges acts as a layer of defense. If an attacker manages to compromise the password of a low-privilege user, the damage they can cause will be limited to the scope of that user, not the entire system.
The Importance of Robustness and Immediate Application
Security robustness begins with authentication. Password complexity and strength are crucial security elements because the password is the first and most direct point of contact between the user and the system. Weak, predictable, or shared passwords are an invitation to compromise. Furthermore, security is not a static state; it requires continuous maintenance.
After any permission alteration—whether a GRANT to add a right or a REVOKE to remove one—it is absolutely necessary to execute the FLUSH PRIVILEGES command. This step is not a mere technical detail; it is an operational integrity requirement. Without executing this command, access modifications are not immediately recognized by the database server. The server will continue to operate under the old permission view, creating a latent security flaw where the user might, for example, still have access to a resource that was just revoked.
In summary, security hardening is a continuous cycle of identity definition, access restriction, monitoring, and updating. It is the discipline that transforms a mere data repository into a secure and reliable corporate asset.
How to Resolve Common Issues When Creating or Using Users
Despite all the rigor employed in defining a user and assigning their rights, it is common for obstacles to arise during the implementation or usage phase that prevent the expected access. These problems are rarely random; they almost always stem from a communication failure between the client, the server, or in the syntax of the access control command itself. The ability to diagnose these errors is as vital as the ability to create them.
How to Diagnose the “Access Denied” Error
When a user receives the “Access denied” message, the cause can be threefold: the user does not exist, the source host is restricted, or the specific permission for the desired resource was not granted. The diagnosis must follow a logical order to isolate the point of failure.
- Existence Check: The first step is always to confirm that the user was created correctly in the system. The most direct method is to try connecting with the provided username and password in an administrative environment (such as the MySQL client).
- Host Analysis: If the user exists, the problem may be an access restriction. If the user was created with a restriction to @localhost, they will not be able to connect from a remote server, for example. If the access is remote, check if the host was configured as @specific_ip or @%.
- Rights Review: If the identity and host are correct, the issue is permissions. Even if the user has access to the database, they may not have permission to perform a specific operation (such as a DROP TABLE or ALTER DATABASE ). In this case, the GRANT commands applied to the user must be reviewed.
Syntax Errors and Connection Failures
Syntax errors occur when Data Control Language (DCL) commands, such as CREATE USER or GRANT, are written incorrectly. A syntax error prevents the server from even attempting to process the request, resulting in immediate failure. The solution here is always a thorough review of the DBMS documentation to ensure the SQL grammar is perfect.
In connection failure scenarios, even if the syntax is correct, the problem may lie in network or firewall settings. If the user cannot connect, it is necessary to verify that the MySQL server is accessible from the client machine. The system, being a set of programs that manages data storage and manipulation, depends on stable communication between layers.
To resolve persistent permission issues after creating or modifying a user, and to ensure that the operating system and the database read the new access rules immediately, it is essential to execute system update commands. This ensures that user management is a continuous cycle of definition, restriction, and application.
Glossary
- DBMS: Database Management System. It is the set of programs that allows for the secure storage and extraction of information.
- DCL: Data Control Language. It is the set of commands (GRANT and REVOKE) used to manage and control access to data.
- Principle of Least Privilege: A security rule that requires a user to have only the privileges strictly necessary to perform their job.
- localhost: A connection host that restricts a user to accessing the server only from the machine where MySQL is installed.
Frequently Asked Questions
What is the difference between creating a user and granting permissions in MySQL?
Creation (via CREATE USER) establishes the identity, name, and credentials of the user. Granting permissions (via GRANT) is the subsequent act that defines which actions, such as SELECT or INSERT, that user is authorized to perform on a specific database or table.
Is it safe to use ‘%’ as the host when creating a user in MySQL?
It is not considered safe in professional environments. Using ‘%’ allows the user to connect from any IP address, exposing the account to connection attempts from any machine on the network. This option should be used with extreme caution.
How do I create a user who can only access a specific database and not all of them?
You must use the GRANT command, specifying the desired permission (e.g., SELECT) and the exact database name in the syntax. This ensures granular control, limiting access only to the defined resources and complying with the Principle of Least Privilege.
What should I do if I forget the password for the user I created?
Password recovery usually requires an administrator with elevated privileges, such as the superuser, to reset the credential. This is an administrative procedure that must be performed through the server’s command line.
Is the FLUSH PRIVILEGES command really necessary after creating a user?
Yes, it is imperative. After executing GRANT or REVOKE commands, FLUSH PRIVILEGES must be used. This command ensures that the database management system recognizes the new set of access rules and applies them instantly.
Conclusion
User management in a Database Management System (DBMS) transcends a mere administrative task; it is the materialization of a robust security policy. By implementing commands such as CREATE USER and GRANT, the administrator is not just creating accounts, but establishing layers of defense that protect sensitive data assets against unauthorized access, whether resulting from external attacks or internal application failures. The success of this security lies in strict adherence to the Principle of Least Privilege, ensuring that every entity, whether a human or an application service, possesses only the privileges strictly necessary for its scope. This granular approach isolates risks and prevents a user’s failure from compromising the integrity of the entire system.
Access control, mediated by the Data Control Language (DCL), demands precision. Defining the connection host (whether it is localhost or a broader domain) and assigning specific permissions are inseparable steps that transform the existence of an account into a functional defense barrier. It is the combination of identity, permitted location, and limited rights that ensures the database operates under established business rules. Well-executed user management is, therefore, the pillar of digital resilience.
By mastering the syntax and concept behind user creation and restriction, the database administrator elevates the maturity level of their infrastructure. Remember that security is an ongoing process, not a final state; therefore, the next step is always the constant review and monitoring of these privileges to ensure that the Principle of Least Privilege is maintained in all operations.




