Sign In
Sign In

How to Find and Delete Duplicate Rows in MySQL with GROUP BY and HAVING Clauses

How to Find and Delete Duplicate Rows in MySQL with GROUP BY and HAVING Clauses
Shahid Ali
Technical writer
MySQL
19.11.2024
Reading time: 8 min

Duplicate entries may inadvertently accumulate in databases, which are crucial for storing vast amounts of structured data. These duplicates could show up for a number of reasons, including system errors, data migration mistakes, or repeated user submissions. A database with duplicate entries may experience irregularities, sluggish performance, and erroneous reporting. Using the GROUP BY and HAVING clauses, as well as a different strategy that makes use of temporary tables, we will discuss two efficient methods for locating and removing duplicate rows in MySQL. With these techniques, you can be sure that your data will always be accurate, clean, and well-organized.

Database duplication in MySQL tables can clog your data, resulting in inaccurate analytics and needless storage. Locating and eliminating them is a crucial database upkeep task. This is a detailed guide on how to identify and remove duplicate rows.

If two or more columns in a row have identical values, it is called a duplicate row. For instance, rows that have the same values in both the userName and userEmail columns of a userDetails table may be considered duplicates.

Benefits of Removing Duplicate Data

The advantage of eliminating duplicate data is that duplicate entries can slow down query performance, take up extra storage space, and produce misleading results in reports and analytics. The accuracy and speed of data processing are improved by keeping databases clean, which is particularly crucial for databases that are used for critical applications or are expanding.

Requirements

Prior to starting, make sure you have access to a MySQL database or have MySQL installed on your computer. The fundamentals of general database concepts and SQL queries. One can execute SQL commands by having access to a MySQL client or command-line interface.

To gain practical experience, you can create a sample database and table that contains duplicate records so that you can test and comprehend the techniques for eliminating them.

Creating a Test Database

Launch the MySQL command-line tool to create a Test Database.

mysql -u your_username -p

Create a new database called test_dev_db after entering your MySQL credentials.

CREATE DATABASE test_dev_db;

Then, switch to this newly created database:.

USE test_dev_db;

Add several rows, including duplicates, to the userDetails table after creating it with the CREATE TABLE query and INSERT query below.

CREATE TABLE userDetails (
userId INT AUTO_INCREMENT PRIMARY KEY,
userName VARCHAR(100),
userEmail VARCHAR(100)
);
INSERT INTO userDetails (userName, userEmail) VALUES
(‘Alisha’, ‘[email protected]’),
(‘Bobita, ‘[email protected]’),
(‘Alisha’, ‘[email protected]’),
(‘Alisha’, ‘[email protected]’);

Using GROUP BY and HAVING to Locate Duplicates

Grouping rows according to duplicate-defining columns and using HAVING to filter groups with more than one record is the simplest method for finding duplicates.

Now that you have duplicate data, you can use SQL to determine which rows contain duplicate entries. MySQL's GROUP BY and HAVING clauses make this process easier by enabling you to count instances of each distinct value. An example of a table structure is the userDetails table, which contains the columns userId, userName, and userEmail. The GROUP BY clause is useful for counting occurrences and identifying duplicates because it groups records according to specified column values. The HAVING clause  allows duplicate entries in groups formed by GROUP BY to be found by combining groups based on specific criteria.

Table userDetails Structure

userId

userName

userEmail

1

Alisha 

[email protected]

2

Bobita 

[email protected]

3

Alisha 

[email protected]

4

Alisha 

[email protected]

In the above table userDetails, records with identical userName and userEmail values are considered duplicates.

Finding Duplicates

Query for find the duplicate entries:

SELECT userName, userEmail, COUNT(*) as count
FROM userDetails
GROUP BY userName, userEmail
HAVING count > 1;

Rows are grouped by userName and userEmail in the aforementioned query, which also counts entries within the group and eliminates groups with a single entry (no duplicates).

Explanation:

  • SELECT userName, userEmail, COUNT(*) as count: Retrieves the count of each combination of username and userEmail, as well as their unique values.
  • GROUP BY userName, userEmail: Records are grouped by username and user email using the GROUP BY userName, userEmail function
  • COUNT (*): Tallies the rows in each set.
  • HAVING occurrences > 1: Recurring entries are identified by displaying only groups with more than one record.

This query will return groups of duplicate records based on the selected columns.

userName

userEmail

count

Alisha

[email protected]

3

Eliminating Duplicate Rows

After finding duplicates, you may need to eliminate some records while keeping the unique ones. Joining the table to itself and removing rows with higher userId values is one effective method that preserves the lowest userId for every duplicate.

Use the SQL query to remove duplicate rows while keeping the lowest userId entry.

DELETE u1
FROM userDetails u1
JOIN userDetails u2
ON u1. userName = u2. userName
AND u1. userEmail = u2. userEmail
AND u1. userId > u2. userId ;

Explanation:

  • u1 & u2: Aliases for the userDetails table to ease a self-join.
  • ON u1. userName = u2. userName AND u1. userEmail = u2. userEmail: Matches rows with identical userName, userEmail.
  • AND u1. userId > u2. userId: Removes rows with higher userId values, keeping only the row with the smallest userId.

Because this action cannot be undone, it is advised that you backup your data before beginning the deletion procedure.

Confirming Duplicate Removal

To confirm that all duplicates have been removed, repeat the Step 1 identification query.

SELECT userName, userEmail, COUNT(*) as count
FROM userDetails
GROUP BY userName, userEmail
HAVING count > 1;

All duplicates have been successfully eliminated if this query yields no rows.

Benefits of Employing GROUP BY and HAVING

The GROUP BY and HAVING clauses serve as vital instruments for the aggregation of data and the filtration of grouped outcomes. These functionalities are especially useful for detecting and handling duplicate entries or for condensing extensive datasets. Below are the primary benefits of employing these clauses.

  • Efficient Identification of Duplicates
  • Data Aggregation and Summarization
  • Filtering Aggregated Results with Precision
  • Versatility Across Multiple Scenarios
  • Compatibility and Simplicity
  • Enhanced Query Readability
  • Support for Complex Aggregations

The GROUP BY and HAVING clauses serve as essential instruments for data aggregation, identifying duplicates, and filtering results. Their effectiveness, ease of use, and adaptability render them crucial for database management and data analysis activities, allowing users to derive insights and handle data proficiently across a variety of applications.

Identifying Duplicates Using a Temporary Table

When dealing with large datasets, it can be easier and more efficient to separate duplicates using a temporary table before deleting them.

Creating the Table

Make a temporary table to store duplicate groups according to predetermined standards (e.g. A. username, along with userEmail.

CREATE TEMPORARY TABLE temp_view_duplicates AS
SELECT username, userEmail, MIN (userId) AS minuid
FROM userDetails
GROUP BY username, userEmail,
HAVING COUNT(*) > 1;

Explanation:

  • CREATE TEMPORARY TABLE temp_view_duplicates AS: Creates a temporary table named temp_view_duplicates.
  • SELECT userName, userEmail, MIN(userId) AS minuid: Groups duplicates by userName and userEmail, keeping only the row with the smallest userId.
  • GROUP BY userName, userEmail: Groups rows by userName, userEmail.
  • HAVING COUNT(*) > 1: Filters only groups with more than one row, identifying duplicates.

This temporary table will now contain one representative row per duplicate group (the row with the smallest id).

Deleting Duplicates from the Main Table

Now that we have a list of unique rows with duplicates in the temp_view_duplicates table, we can use the temporary table to remove duplicates while keeping only the rows with the smallest userId.

Use the following DELETE command:

DELETE FROM userDetails
WHERE (username, userEmail) IN (
SELECT username, userEmail FROM temp_view_duplicates
) AND userId NOT IN (
SELECT minuid FROM temp_view_duplicates
);

Explanation:

  • WHERE (username, userEmail,) IN: Targets only duplicate groups identified in temp_view_duplicates.
  • AND userId NOT IN (SELECT minuid FROM temp_view_duplicates): Ensures that only duplicate rows (those with higher userId values) are deleted.

Verifying Results

To confirm that duplicates have been removed, query the userDetails table:

SELECT * FROM userDetails;

Only unique rows should remain.

Temporary tables (CREATE TEMPORARY TABLE) are automatically dropped when the session ends, so they don’t persist beyond the current session.

When making extensive deletions, think about utilizing a transaction to safely commit or undo changes as necessary.

Key Advantages of Using a Temporary Table

  • Lower Complexity: By isolating duplicates, the removal process is simpler and clearer.
  • Enhanced Efficiency: It's faster for large datasets, as it avoids repeated joins.
  • Improved Readability: Using a temporary table makes the process more modular and easier to understand.

Conclusion

Eliminating duplicate records is essential for maintaining a well-organized database, improving performance, and ensuring accurate reporting. This guide presented two approaches:

  • Direct Method with GROUP BY and HAVING Clauses: Ideal for small datasets, using self-joins to delete duplicates.
  • Temporary Table Approach: More efficient for larger datasets, leveraging temporary storage to streamline deletion.

Choose the method that best fits your data size and complexity to keep your database clean and efficient.

MySQL
19.11.2024
Reading time: 8 min

Similar

MySQL

How to Secure MySQL Server

MySQL is the best choice for relational database management, but its widespread use also makes it an appealing target for potential attackers. This tutorial outlines essential steps to fortify your MySQL server, protecting your data from unauthorized access and activities that are malicious. Prerequisites Prior to diving into security configurations, ensure the prerequisites mentioned below: MySQL is Installed and Running: Consider reading the official MySQL documentation if needed.  Access to Administrator Privileges: sudo or root access is required for many steps. Familiarity with MySQL Commands: Basic command-line knowledge will be helpful. Understanding Threat Landscape MySQL databases face various threats, including:   Unauthorized Logins: Weak credentials or misconfigurations can allow attackers to access your data.   SQL Injection Attacks: Unvalidated inputs in applications can expose your database to manipulation.   Insufficient Network Security: Open ports and weak firewalls leave the server vulnerable.   Proactively securing the database reduces the likelihood of such incidents. Step 1: Update the Server and MySQL As new updates provide new security features and also fixes bugs, it is highly important that your system stays updated because if will fix known vulnerabilities and leverage latest security enhancements.  Utilize the commands mentioned below to update both the operating system and MySQL. sudo apt updatesudo apt upgrade -y Verify the current MySQL version: mysql --version Keep an eye on official release notes to understand updates and security patches. Step 2: Secure Initial Configuration   The mysql_secure_installation script is an essential tool for strengthening the security of your MySQL server's. It streamlines sensitive tasks such as: Setting a root password Removing anonymous user accounts Disabling remote root logins Deleting the test database To run the script: sudo mysql_secure_installation Follow the prompts to implement the recommended security measures. Step 3: Configure User Authentication   Effective user management is essential for database security.   Use Unique Users for Applications Create separate users for each application, and assign only the permissions they need. For example:   CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';GRANT SELECT, INSERT ON app_database.* TO 'app_user'@'localhost';FLUSH PRIVILEGES; This ensures that a breach in one application doesn’t compromise the entire database.   Enable Authentication Plugins MySQL provides plugins like caching_sha2_password for secure authentication. To enable it:   ALTER USER 'root'@'localhost' IDENTIFIED WITH 'caching_sha2_password' BY 'SecurePassword!'; Step 4: Enforce Password Policies   If passwords are strong then the possibility of brute force attacks may not be of any help for the hackers. Install the password validation plugin if it isn’t already enabled: INSTALL PLUGIN validate_password SONAME 'validate_password.so'; Configure password strength rules in the MySQL configuration file: validate_password_policy=STRONGvalidate_password_length=12 These settings enforce strong, hard-to-guess passwords. Step 5: Restrict Remote Access   Unnecessary remote access exposes the database to risks. Disable Remote Root Access By default, MySQL allows root logins from remote systems. Disable this feature by editing the MySQL configuration file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Set the bind address to localhost: bind-address = 127.0.0.1 Restart the MySQL service:   sudo systemctl restart mysql Use Firewalls for Remote Connections If remote access is necessary then configure firewalls. This will only allow traffic from trusted IPs. sudo ufw allow from <trusted_ip> to any port 3306sudo ufw enable Step 6: Secure Data Transmission   Encryption will make sure that data transferred between the client and server is safe from eavesdropping. Enable SSL/TLS Certificates for MySQL are generated automatically at the time of installation.  Add the following lines to /etc/mysql/mysql.conf.d/mysqld.cnf:   [mysqld]ssl-ca=/var/lib/mysql/ca.pemssl-cert=/var/lib/mysql/server-cert.pemssl-key=/var/lib/mysql/server-key.pemrequire_secure_transport = ON Restart MySQL to apply changes. Use tools like OpenSSL to verify encrypted connections. Step 7: Audit and Monitor Database Activity   Monitoring user activity can help detect unauthorized actions. Enable Logs Activate general logs and error logs in the configuration file:   general_log=1log_error=/var/log/mysql/error.log Analyze Access Patterns Periodically review logs to identify anomalies or suspicious activity. Use automated tools like Percona Monitoring and Management for advanced analytics. Step 8: Protect Against SQL Injection   SQL injection is a common attack vector for web-based MySQL applications. Mitigate this risk by: Using Parameterized Queries: This prevents attackers from injecting malicious SQL commands Validating User Inputs: Sanitize and validate inputs at the application level. Implementing a Web Application Firewall (WAF): Tools like ModSecurity can block malicious queries. Step 9: Regular Backups and Disaster Recovery   Prepare for the unexpected by setting up automated backups. Full Database Backups Use mysqldump to create complete backups:   mysqldump -u root -p --all-databases > backup.sql Incremental Backups For large databases, consider incremental backups using tools like Percona XtraBackup. Step 10: Disable Unused Features   Reducing the database’s attack surface is crucial.   Disable Unused Plugins Run the following command to list active plugins:   SHOW PLUGINS; Unload any unnecessary plugins UNINSTALL PLUGIN plugin_name; Remove Sample Databases Delete test databases that come pre-installed with MySQL:   DROP DATABASE test; Step 11: Use Security Updates and Best Practices   Regularly update MySQL to address vulnerabilities and ensure you’re using the most secure version. Stay connected with the MySQL Community for updates, news, and security alerts. Advance Practices: Segmentation Isolate your database server from other services using network segmentation to reduce the risk of unauthorized access. Intrusion Detection Systems (IDS). Use tools like Snort to monitor for unusual activity and detect potential intrusions in real-time. Two-Factor Authentication (2FA). Enable 2FA for administrative accounts to add an extra layer of protection against unauthorized access. Conclusion Securing a MySQL server requires a comprehensive approach, combining careful configuration, continuous monitoring, and proactive management. If you utilize these practices then your database can be safeguarded very effectively, protecting sensitive data as well as mitigating the chance of unauthorized access. You must evaluate and update the security measures regularly so that you can stay prepared for emerging threats.
24 January 2025 · 6 min to read
Debian

How to Install MySQL on Debian

Installing MySQL on Debian effectively creates a robust and flexible database (DB) infrastructure that accommodates a wide range of applications as well as services. It is renowned for its scalability, dependability, and durability. By setting it, individuals experience the operations in an efficient manner and enhance the overall efficiency of DB infrastructure. This combination is especially beneficial for administrators, DB analysts, and industries that demand a dependable database solution for dealing with huge data. Additionally, MySQL's comprehensive guide and supporters help make it simpler to troubleshoot problems and enhance operations.  In this guide, we will demonstrate the thorough procedure for installing and configuring MySQL on Debian. How to Install MySQL on Debian The default repositories do not contain the MySQL database server package on Debian. To install it on a  Linux system follow the below instructions. We will download the recent version of the MySQL. Step 1: Download MySQL Package Let us obtain the MySQL repository information package, which is in the .deb format: wget https://dev.mysql.com/get/mysql-apt-config_0.8.30-1_all.deb Note: To authenticate the most updated release, go to the MySQL repository webpage. Step 2: MySQL Configuration Package Installation Then, employ the .deb file for initializing the installation via dpkg: sudo dpkg -i mysql-apt-config_0.8.30-1_all.deb Respond to the prompt. For instance, pick MySQL Server & Cluster and hit Enter for starting configurations: For picking a version such as (mysql-8.4-lts), scroll downward and hit OK for the next step: Step 3: Refresh the System Now, update the server's package indexes to implement the updated MySQL info: sudo apt update Step 4: MySQL Installation Debian's default manager makes sure to install MySQL in an easier manner. Installing the package with this command: sudo apt install mysql-server -y You will see the interface for setting the root account. Input a stronger password to secure the database. In the end, hit the Ok button: Check the version on the server via the --version utility: mysql --version Step 5: Managing the Services Now, you can enable the MySQL service to initialize automatically at boot time: sudo systemctl enable mysql Activate the service via the systemctl utility: sudo systemctl start mysql Check if the system service is operational by viewing its status: sudo systemctl status mysql Step 6: MySQL Secure Installation The key or password that the individual created at the initialising procedure is currently protecting the root DB user on the server. MySQL also includes other insecure defaults, such as remote access to test databases and the root database user on the server.  It is vital to secure the MySQL installation after it has been completed as well as disable all unsafe default settings. There is a security script that can assist us in this procedure. Run the script: sudo mysql_secure_installation To activate the VALIDATE PASSWORD component and guarantee stringent password procedures, type Y and hit Enter. Next, you will need to configure several security settings: Set the Root Password: Select a strong password and make sure that it is correct. Configure the password policy for the DB server. For instance, type 2 to permit only the strong passwords on the server and hit Enter. When required to modify the root password, input N; alternatively, input Y to modify the password. Eliminate Anonymous Users: It is advised to eliminate the accessibility of anonymous users. For this, input Y and Enter when prompted. Prevent Accessibility of Remote Root: It is a better practice to avoid remote root login for multiple security concerns. To prevent the root user from having a remote access, input Y and hit Enter. Delete the Test DB: For enhancing security, the test database, which is utilized for testing, can be deleted. To do so, input Y and hit Enter. Refreshing Privilege Tables: It guarantees that all modifications are implemented instantly. To implement the configuration and edit the privileges table, hit Enter. Step 7: Access MySQL Utilizing the mysql client utility, MySQL establishes the connection and provides access to the database server console.  Now, access the shell interface and run general statements on the DB server. Let’s input the root and the password created at the time of the safe installation procedure: sudo mysql -u root -p Step 8: Basic MySQL Operations The creation of a DB and a new user for your applications rather than utilizing the root is a better practice. To accomplish the task, employ the given instructions: Create a Database: First, create a database. For instance, hostmandb is created via the below command: CREATE DATABASE hostmandb; Display All Databases: List all databases to make sure hostmandb is created: SHOW DATABASES; Create of a New User: Create a user and assign a strong password. In our example, we set Qwer@1234 as a password for the user  minhal. Replace these values with your data. CREATE USER 'minhal'@'localhost' IDENTIFIED BY 'Qwer@1234'; Give Permissions to the User: Give complete access to the hostmandb to the new user: GRANT ALL PRIVILEGES ON hostmandb.* TO 'minhal'@'localhost'; Flush Privileges: To implement the modifications, refresh the table: FLUSH PRIVILEGES; Exit the Shell: For closing the interface, utilize the EXIT statement: EXIT; Access MySQL Console as the Particular User For the purpose of testing hostmandb access, log in to MySQL as the new user, in our case minhal. sudo mysql -u minhal -p It accesses the console after entering the minhal user password when prompted: For verification, display all DBs and confirm that the hostmandb is available: SHOW DATABASES; Step 9: Configuration for Remote Access Setting up the server for supporting remote accessibility is necessary if an individual is required to access MySQL remotely. Follow these steps: Access the mysql.cnf file and modify the particular file for MySQL: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Look for the line with the bind-address and change it to: bind-address = 0.0.0.0 Reload the MySQL service: sudo systemctl restart mysql Permit the user to have remote access: sudo mysql -u root -p GRANT ALL PRIVILEGES ON hostmandb.* TO 'minhal'@'localhost';FLUSH PRIVILEGES;EXIT; Step 10: Firewall Configuration If you have a firewall activated, you need to open the MySQL port 3306 to traffic. Set up the firewall following the below steps: Allow traffic through MySQL: sudo ufw allow mysql Now, activate the UFW on the system: sudo ufw enable Reload the firewall: sudo ufw reload Step 11: Restore and Backup Maintaining regular backups is crucial to avoiding data loss. The mysqldump utility is provided by MySQL for backup creation. To achieve this, consider these instructions: Backup a Single Database: This command employs mysqldump to create the backup of the hostmandb as a hostmandb_backup.sql file: sudo mysqldump -u root -p hostmandb> hostmandb_backup.sql Backup All Databases: For creating a backup of all databases as a file named all_databases_backup.sql with root privileges, utilize mysqldump: sudo mysqldump -u root -p --all-databases > all_databases_backup.sql Restore a Particular Database: Now, restore the hostmandb from the backup file hostmandb_backup.sql: sudo mysql -u root -p hostmandb < hostmandb_backup.sql Step 12: Optimize MySQL Operations (Optional) Depending on the workload and server resources, you can adjust settings to guarantee peak performance. These instructions will help you maximize MySQL's speed: Adjust InnoDB Buffer Pool Size: Caches for data and indexes are kept in the InnoDB buffer pool. Expanding its size can enhance its functionality. Edit the MySQL configuration file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf The below line should be added or changed: innodb_buffer_pool_size = 1G Its size should be adjusted according to the amount of memory on the server. Enable Query Cache: The query cache stores the outcome of SELECT queries. Enabling it can enhance operations for repetitive queries. Modify the .cnf file: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf Add or edit the below lines: query_cache_type = 1query_cache_size = 64M Optimize Table Structure: Frequently optimize your customers table in hostmandb to recover wasted space and boost efficiency: USE hostmandb;OPTIMIZE TABLE customers; Analyze Operations: DB operations can be tracked and analyzed with tools like MySQL Workbench and mysqltuner. Using the command below, install mysqltuner: sudo apt install mysqltuner Run mysqltuner to get performance recommendations: sudo mysqltuner Conclusion Installing a MySQL environment is important in today's digital world. By following this instruction, you'll be able to safely install and connect to your MySQL database. This strategy not only increases security but also improves remote database maintenance efficiency. It helps to prevent breaches and ensures the confidentiality of your data. This article has given thorough instructions for the installation of MySQL's database environment on Debian. It is suggested that MySQL servers should be regularly monitored and optimized to guarantee optimum performance and dependability. In addition, Hostman offers pre-configured and ready-to-use cloud databases, including cloud MySQL. 
14 January 2025 · 8 min to read
MySQL

Creating an SSH Tunnel for MySQL Remote Access

Maintaining a secure database environment is vital in today's digital age. It helps prevent breaches and ensure the confidentiality of your information. A highly effective process for enhancing MySQL connection security is by implementing an SSH tunnel for remote access. This approach establishes an encrypted tunnel between your device and the server, ensuring data remains secure. SSH Tunneling SSH tunneling, also referred to as SSH port forwarding, enables the secure transmission of data between networks. By establishing an encrypted SSH tunnel, data can be safely transferred without the risk of exposure to potential threats. It possesses several benefits: Security: Encrypts data, keeping it safe from being seen or intercepted by others. Bypassing Restrictions: Allows access to services and resources blocked by firewalls. Flexibility: Can handle all network traffic types, fitting many uses. Types of SSH Tunneling SSH tunneling is of three types: Local Port Forwarding: It lets you redirect a port from your local machine to a destination machine using a tunnel. This is the method used in our guide. For example: ssh -L 3307:localhost:3306 your_username@your_server_ip Remote Port Forwarding: It lets you redirect a port from a remote machine to your local machine. This is useful for accessing local services from a remote machine. For example: ssh -R 9090:localhost:80 your_username@your_server_ip Dynamic Port Forwarding: It lets you create a SOCKS proxy to dynamically forward traffic through an SSH tunnel. This is useful for secure web browsing or bypassing firewalls. For example: ssh -R 9090:localhost:80 your_username@your_server_ip Prerequisites Before beginning, ensure you have: SSH client (OpenSSH, or PuTTY for Windows) MySQL server info SSH into the MySQL host machine securely. Setting Up Remote Access Go through these essential steps to securely set up remote access to your MySQL server through SSH tunnel: Step 1: Facilitate Connectivity For remote access, tune it to listen on an external IP. This allows SQL access from localhost to all IPs. Here’s how to do it: Access MySQL Config File Using a text editor, access the config file. On Ubuntu, it's typically located at: sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf If the file isn't in its expected place, search for it with: sudo find / -name mysqld.cnf Edit bind-address Inside the file, find bind-address line, which is set to 127.0.0.1 by default, limiting server to local connections: Change the address to allow connections from all IP addresses by setting it to 0.0.0.0. Save changes by pressing Ctrl+X, Y to confirm, and Enter to exit. Restart MySQL Restart service to apply the updated settings: sudo systemctl restart mysql Step 2: Adjust Firewall By default, 3306 is the standard port in MySQL. To permit remote access, ensure this port is opened in your firewall settings. Tailor these steps to your specific firewall service. Open Port via UFW On Ubuntu, UFW is a pre-installed firewall utility. To allow traffic on 3306: sudo ufw allow from remote_ip to any port 3306 Substitute remote_ip with actual IP. Open Port via Firewalld On Red Hat-based and Fedora systems, Firewalld is the primary firewall tool. To open port 3306 for traffic, run these commands: sudo firewall-cmd --zone=public --add-service=mysql --permanentsudo firewall-cmd --reload The first command permanently allows MySQL traffic, and the second reloads the firewall to make the changes. Step 3: Open Your SSH Client Fire up your go-to SSH client. Opt for PuTTY on Windows, or the terminal if using macOS or Linux. Using Terminal (Linux or macOS) Implement this command: ssh -L 3307:localhost:3306 your_username@your_server_ip 3307: It's the local port your computer will listen to. localhost: It's a MySQL server address used by the SSH. It's where the service runs on the machine you're connecting to. 3306: The remote port where the server listens for incoming connections. username@server_ip: Your SSH login details. When required, verify the server's fingerprint. Confirm it matches by typing "yes" and pressing Enter.  Once confirmed, enter your SSH password if asked and press Enter for tunneling. After the tunnel is up, all traffic destined to local port 3307 will be forwarded to the remote machine in a secure fashion. Using PuTTY (Windows) Windows users can use the below-given instructions to perform tunneling: Launch PuTTY. From the left menu, direct to Connection > SSH > Tunnels. Input 3307 for Source port and localhost:3306 for the Destination field. Then hit Add. Navigate back to Session menu, enter server’s IP address and start the session using the Open button. Step 4: Connect to MySQL After setting up the tunnel, seamlessly link to the server through: sudo mysql -h localhost -P 3307 -u your_mysql_user -p Step 5: Verify the Connection Log into server and check if you can run queries: Additional Safeguards for Enhanced Security To further enhance the MySQL remote access security, consider the following: Implement Robust Passwords and Authentication Ensure using strong, unique passwords for both servers accounts. Implement key-based SSH authentication for added security. Here's how to set up SSH key authentication: Generate an SSH key pair via: ssh-keygen -t rsa -b 4096 -C "[email protected]" Copy the public key to the server via: ssh-copy-id your_username@your_server_ip Regularly Update Your Software Ensure that your server, client, and all associated software are consistently updated with the latest security patches and enhancements. This practice safeguards your system against known vulnerabilities and potential threats. Supervise and Audit Access Consistently examine access logs on both your MySQL and SSH server. Watch for any unusual activities or unauthorized attempts to gain access. Set up logging for both services: Check the SSH logs via: sudo tail /var/log/auth.log Enable and check MySQL logs by adding the below-given lines in the configuration file: [mysqld]general_log = 1general_log_file = /var/log/mysql/mysql-general.log You can view the general query log via: sudo cat /var/log/mysql/mysql-general.log To continuously monitor the log file in real time, use: sudo tail -f /var/log/mysql/mysql-general.log Implement IP Whitelisting Limit access to your MySQL by applying IP whitelisting. It ensures that connections are permitted only from specified IP addresses, thereby enhancing security: sudo ufw allow from your_trusted_ip to any port 3306 Replace your_trusted_ip with the IP address you trust. Troubleshooting Issues Here are a few common problems and solutions: Unable to Connect: Check SSH configuration and firewall rules. Ensure the SSH tunnel is correctly established and the server is reachable. Port Already in Use: Change the local forwarding port from 3307 to another available port. Authentication Errors: Verify your server's credentials. Ensure that the correct user permissions are set. MySQL Server Not Listening on Correct IP: Double-check the MySQL bind-address configuration and ensure the server is listening on the correct IP. Conclusion By adhering to this guide, you'll securely connect to your MySQL database via an SSH tunnel. This method not only boosts security but also enhances remote database management efficiency.  Regularly check your SSH tunnel setup to ensure a stable, secure connection. This practice ensures your data stays protected, providing peace of mind for seamless database operations. Hostman provides pre-configured and ready-to-use cloud databases, including cloud MySQL.
27 December 2024 · 6 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