In this tutorial, you will learn how to find the duplicate records in a table.
In this tutorial, you will learn how to find the duplicate records in a table.In this tutorial, you will learn how to find the duplicate records in a table.
Duplicate records in a table :
You can check for duplicate records of table. You can group record by any of fields of table. GROUP BY clause groups record over the field and Having clause refine records in SELECT statement. Having clause is used with the GROUP BY clause.
You can check this by writing following SQL query -
sql = "SELECT name as name_count from employee GROUP BY name HAVING ( COUNT(name)
>1 )"
Example :
In this tutorial we are checking of duplicate record and listing name of such employees. Count function returns the count of the number of rows.
JDBCDuplicateRecords.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JDBCDuplicateRecords { public static void main(String[] args) { System.out.println("Finding the duplicate records in a table.."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "employees"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; Statement statement = null; ResultSet rs; try { Class.forName(driverName); conn = DriverManager .getConnection(url + dbName, userName, password); statement = conn.createStatement(); String sql = "SELECT name as name_count from employee GROUP BY name HAVING ( COUNT(name) > 1 )"; rs = statement.executeQuery(sql); System.out.println("Employee Name having duplicate names : "); while (rs.next()) { String name = rs.getString("name_count"); System.out.println(name); } conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output :
Finding the duplicate records in a table.. Employee Name having duplicate names : Linda Roxi