
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
How to ensure that MySQL rows are unique?
To ensure that MySQL rows are unique, you need to use UNIQUE constraint. Let us first create a table −
mysql> create table DemoTable1580 -> ( -> id int, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.73 sec)
Here is the query to create unique constraints to ensure MySQL rows are unique −
mysql> alter table DemoTable1580 add unique index(id,Name,Age); Query OK, 0 rows affected (0.45 sec) Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable1580 values(101,'Chris',21); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable1580 values(102,'Chris',21); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1580 values(102,'David',21); Query OK, 1 row affected (0.49 sec) mysql> insert into DemoTable1580 values(101,'Chris',21); ERROR 1062 (23000): Duplicate entry '101-Chris-21' for key 'id'
Display all records from the table using select statement −
mysql> select * from DemoTable1580;
This will produce the following output −
+------+-------+------+ | id | Name | Age | +------+-------+------+ | 101 | Chris | 21 | | 102 | Chris | 21 | | 102 | David | 21 | +------+-------+------+ 3 rows in set (0.00 sec)
- Related Articles
- How add unique key to existing table (with non-unique rows)?
- How to select rows in MySQL that are >= 1 DAY from the current date?
- How can we get all the unique rows in MySQL result set?
- Selecting rows that are older than current date in MySQL?
- Get the count of only unique rows in a MySQL column?
- How to return rows that have the same column values in MySQL?
- How to find the unique rows in an R data frame?
- How to ensure that child class overrides a super class method in java?
- How to select unique value in MySQL?
- MySQL select query to select rows from a table that are not in another table?
- How to skip rows in MySQL?
- How to merge rows in MySQL?
- How to find the unique rows based on some columns in R?
- How to extract unique combination of rows in an R data frame?
- Check how many rows are in a MySQL database table?

Advertisements