The way to query duplicate data in SQL is to use the GROUP BY clause to group the required columns. Use the HAVING clause to specify filter conditions for duplicate data.
SQL command to query duplicate data
How to query duplicate data
In SQL, querying duplicate data can be achieved by using the GROUP BY
and HAVING
clauses.
Steps
GROUP BY
clause. HAVING
clause to specify filter conditions for duplicate data. Syntax
<code class="sql">SELECT column_name(s) FROM table_name GROUP BY column_name(s) HAVING COUNT(*) > 1;</code>
Example
Suppose there is a table named students
, containing the following data:
student_id | name |
---|---|
1 | John Doe |
2 | Jane Smith |
3 | John Doe |
4 | Mary Johnson |
To query the duplicate name in the
students table
fields, you can use the following query:
<code class="sql">SELECT name FROM students GROUP BY name HAVING COUNT(*) > 1;</code>
Output
<code>John Doe</code>
Other examples
orders
Duplicate product_id
fields in the table: <code class="sql">SELECT product_id FROM orders GROUP BY product_id HAVING COUNT(*) > 1;</code>
employees
Duplicate email## in the table # field and display the number of repetitions:
<code class="sql">SELECT email, COUNT(*) AS count FROM employees GROUP BY email HAVING COUNT(*) > 1;</code>
Note
COUNT
, SUM
, and AVG
.
The above is the detailed content of Command to query duplicate data in sql. For more information, please follow other related articles on the PHP Chinese website!