Search code examples
mysqlsqlselectgroup-byhaving

How to check duplicate value in MySQL


I have one table as below:

ID   USER1    USER2
1      Q        Y
2      W        Y 
3      R        Y
4      T        Y
5      XY       Y

How I can check when USER2 column is ALL duplicate ? I'm using this code but It not working

$res = mysqli_query($conn, "SELECT COMLUMN FROM TABLE");
$result = array_unique($res);
if($result == 1 )
{
echo "Unique";
}
else
{
echo "NOT Unique";
}

Solution

  • Just do a:

    SELECT COUNT(USER2) FROM tablename GROUP BY USER2
    

    And see if it returns 1 record, or the first record value is equal to the total record count.

    Here is an example:

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "SELECT (SELECT COUNT(USER2) FROM tablename GROUP BY USER2 LIMIT 1) = (SELECT COUNT(USER2) FROM tablename)";
    $result = $conn->query($sql);
    
    if ($result->fetch_row()[0] == 1)
    {
      // all same
    }
    else
    {
      //not same
    }