SlideShare a Scribd company logo
1 of 14
Advanced Database
MySQL
Seminar proposed by: Marwa Mohammed Ali
M.Sc. Student
CONTENTS
Using Sequences
• A sequence is a set of integers 1, 2, 3, ... that are
generated in order on demand. Sequences are frequently
used in databases because many applications require
each row in a table to contain a unique value and
sequences provide an easy way to generate them.
• Using AUTO_INCREMENT column:
The simplest way in MySQL to use Sequences is to define
a column as AUTO_INCREMENT and leave rest of the
things to MySQL to take care.
Example: Try out the following example. This will create table and
after that it will insert few rows in this table where it is not required
to give record ID because it's auto incremented by MySQL.
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO insect (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM insect ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
Renumbering an Existing
Sequence
• There may be a case when you have deleted many records from a
table and you want to resequence all the records. This can be done
by using a simple trick but you should be very careful to do so if
your table is having joins with other table.
• If you determine that resequencing an AUTO_INCREMENT column
is unavoidable, the way to do it is to drop the column from the table,
then add it again. The following example shows how to renumber
the id values in the insect table using this technique:
mysql> ALTER TABLE insect DROP id;
mysql> ALTER TABLE insect
-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
-> ADD PRIMARY KEY (id);
Starting a Sequence at a Particular
Value
• By default, MySQL will start sequence from 1 but you can specify
any other number as well at the time of table creation. Following is
the example where MySQL will start sequence from 100.
Alternatively, you can create the table and then set the initial sequence
value with ALTER TABLE.
mysql> ALTER TABLE insect AUTO_INCREMENT = 100;
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Handling Duplicates
• Tables or result sets sometimes contain duplicate
records. Sometimes, it is allowed but sometimes it is
required to stop duplicate records.
• Preventing Duplicates from Occurring in a Table:
You can use a PRIMARY KEY or UNIQUE Index on a table with
appropriate fields to stop duplicate records.
 The following table contains no such index or primary key, so it
would allow duplicate records for first_name and last_name
CREATE TABLE person_tbl
(
first_name CHAR(20),
last_name CHAR(20),
Gender CHAR(10)
);
• To prevent multiple records with the same first and last name
values from being created in this table, add a PRIMARY KEY to its
definition. When you do this, it's also necessary to declare the
indexed columns to be NOT NULL, because a PRIMARY KEY does
not allow NULL values
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
Gender CHAR(10)
PRIMARY KEY (last_name, first_name)
);
• Use INSERT IGNORE rather than INSERT. If a record
doesn't duplicate an existing record, MySQL inserts it as
usual. If the record is a duplicate, the IGNORE keyword
tells MySQL to discard it silently without generating an
error. Following example does not error out and same
time it will not insert duplicate records
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( ‘ali', ‘mohammed');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( ‘ali', ‘mohammed');
Query OK, 0 rows affected (0.00 sec)
• Use REPLACE rather than INSERT. If the record is new, it's inserted
just as with INSERT. If it's a duplicate, the new record replaces the
old one:
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( ‘ali', ‘ahmed');
Query OK, 1 row affected (0.00 sec)
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( ‘ali', ‘ahmed');
Query OK, 2 rows affected (0.00 sec)
INSERT IGNORE and REPLACE should be chosen according to the
duplicate-handling behavior you want to effect.
• INSERT IGNORE keeps the first of a set of duplicated records and
discards the rest.
• REPLACE keeps the last of a set of duplicates and erase out any earlier
ones
• Another way to enforce uniqueness is to add a UNIQUE
index rather than a PRIMARY KEY to a table.
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
Gender CHAR(10)
UNIQUE (last_name, first_name)
);
Counting and Identifying
Duplicates
• Following is the query to count duplicate records with
first_name and last_name in a table.
mysql> SELECT COUNT(*) as repetitions, last_name, first_name
-> FROM person_tbl
-> GROUP BY last_name, first_name
-> HAVING repetitions > 1;
This query will return a list of all the duplicate records in
person_tbl table.
Eliminating Duplicates from a Query
Result
• You can use DISTINCT along with SELECT statement
to find out unique records available in a table.
mysql> SELECT DISTINCT last_name, first_name
-> FROM person_tbl
-> ORDER BY last_name;
An alternative to DISTINCT is to add a GROUP BY clause that
names the columns you're selecting. This has the effect of removing
duplicates and selecting only the unique combinations of values in
the specified columns:
mysql> SELECT last_name, first_name
-> FROM person_tbl
-> GROUP BY (last_name, first_name);
Database

More Related Content

What's hot

Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Ajay Khatri
 
Vtiger picklist 创建实例
Vtiger picklist 创建实例Vtiger picklist 创建实例
Vtiger picklist 创建实例YUCHENG HU
 
Procedure To Store Database Object Size And Number Of Rows In Custom Table
Procedure To Store Database Object Size And Number Of Rows In Custom TableProcedure To Store Database Object Size And Number Of Rows In Custom Table
Procedure To Store Database Object Size And Number Of Rows In Custom TableAhmed Elshayeb
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 

What's hot (10)

10053 - null is not nothing
10053 - null is not nothing10053 - null is not nothing
10053 - null is not nothing
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 
Sql tables
Sql tablesSql tables
Sql tables
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1
 
Lab4 join - all types listed
Lab4   join - all types listedLab4   join - all types listed
Lab4 join - all types listed
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
R part iii
R part iiiR part iii
R part iii
 
Vtiger picklist 创建实例
Vtiger picklist 创建实例Vtiger picklist 创建实例
Vtiger picklist 创建实例
 
Procedure To Store Database Object Size And Number Of Rows In Custom Table
Procedure To Store Database Object Size And Number Of Rows In Custom TableProcedure To Store Database Object Size And Number Of Rows In Custom Table
Procedure To Store Database Object Size And Number Of Rows In Custom Table
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Similar to Database (20)

Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 
1 introduction to my sql
1 introduction to my sql1 introduction to my sql
1 introduction to my sql
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
 
Using Mysql.pptx
Using Mysql.pptxUsing Mysql.pptx
Using Mysql.pptx
 
Sql
SqlSql
Sql
 
MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
MYSql manage db
MYSql manage dbMYSql manage db
MYSql manage db
 
Sql modifying data - MYSQL part I
Sql modifying data - MYSQL part ISql modifying data - MYSQL part I
Sql modifying data - MYSQL part I
 
Autonumber
AutonumberAutonumber
Autonumber
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
 
mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
 
sql.pptx
sql.pptxsql.pptx
sql.pptx
 
Database index
Database indexDatabase index
Database index
 
My s qlbalidfnl
My s qlbalidfnlMy s qlbalidfnl
My s qlbalidfnl
 
ADV PPT 2 LAB.pptx
ADV PPT 2 LAB.pptxADV PPT 2 LAB.pptx
ADV PPT 2 LAB.pptx
 
Sql commands
Sql commandsSql commands
Sql commands
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 

Recently uploaded

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Database

  • 1. Advanced Database MySQL Seminar proposed by: Marwa Mohammed Ali M.Sc. Student
  • 3. Using Sequences • A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them. • Using AUTO_INCREMENT column: The simplest way in MySQL to use Sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care.
  • 4. Example: Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it's auto incremented by MySQL. mysql> CREATE TABLE insect -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected ); Query OK, 0 rows affected (0.02 sec) mysql> INSERT INTO insect (id,name,date,origin) VALUES -> (NULL,'housefly','2001-09-10','kitchen'), -> (NULL,'millipede','2001-09-10','driveway'), -> (NULL,'grasshopper','2001-09-10','front yard'); Query OK, 3 rows affected (0.02 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM insect ORDER BY id; +----+-------------+------------+------------+ | id | name | date | origin | +----+-------------+------------+------------+ | 1 | housefly | 2001-09-10 | kitchen | | 2 | millipede | 2001-09-10 | driveway | | 3 | grasshopper | 2001-09-10 | front yard | +----+-------------+------------+------------+ 3 rows in set (0.00 sec)
  • 5. Renumbering an Existing Sequence • There may be a case when you have deleted many records from a table and you want to resequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having joins with other table. • If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique: mysql> ALTER TABLE insect DROP id; mysql> ALTER TABLE insect -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, -> ADD PRIMARY KEY (id);
  • 6. Starting a Sequence at a Particular Value • By default, MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100. Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE. mysql> ALTER TABLE insect AUTO_INCREMENT = 100; mysql> CREATE TABLE insect -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected );
  • 7. Handling Duplicates • Tables or result sets sometimes contain duplicate records. Sometimes, it is allowed but sometimes it is required to stop duplicate records. • Preventing Duplicates from Occurring in a Table: You can use a PRIMARY KEY or UNIQUE Index on a table with appropriate fields to stop duplicate records.  The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name CREATE TABLE person_tbl ( first_name CHAR(20), last_name CHAR(20), Gender CHAR(10) );
  • 8. • To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it's also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values CREATE TABLE person_tbl ( first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, Gender CHAR(10) PRIMARY KEY (last_name, first_name) );
  • 9. • Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error. Following example does not error out and same time it will not insert duplicate records mysql> INSERT IGNORE INTO person_tbl (last_name, first_name) -> VALUES( ‘ali', ‘mohammed'); Query OK, 1 row affected (0.00 sec) mysql> INSERT IGNORE INTO person_tbl (last_name, first_name) -> VALUES( ‘ali', ‘mohammed'); Query OK, 0 rows affected (0.00 sec)
  • 10. • Use REPLACE rather than INSERT. If the record is new, it's inserted just as with INSERT. If it's a duplicate, the new record replaces the old one: mysql> REPLACE INTO person_tbl (last_name, first_name) -> VALUES( ‘ali', ‘ahmed'); Query OK, 1 row affected (0.00 sec) mysql> REPLACE INTO person_tbl (last_name, first_name) -> VALUES( ‘ali', ‘ahmed'); Query OK, 2 rows affected (0.00 sec) INSERT IGNORE and REPLACE should be chosen according to the duplicate-handling behavior you want to effect. • INSERT IGNORE keeps the first of a set of duplicated records and discards the rest. • REPLACE keeps the last of a set of duplicates and erase out any earlier ones
  • 11. • Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table. CREATE TABLE person_tbl ( first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, Gender CHAR(10) UNIQUE (last_name, first_name) );
  • 12. Counting and Identifying Duplicates • Following is the query to count duplicate records with first_name and last_name in a table. mysql> SELECT COUNT(*) as repetitions, last_name, first_name -> FROM person_tbl -> GROUP BY last_name, first_name -> HAVING repetitions > 1; This query will return a list of all the duplicate records in person_tbl table.
  • 13. Eliminating Duplicates from a Query Result • You can use DISTINCT along with SELECT statement to find out unique records available in a table. mysql> SELECT DISTINCT last_name, first_name -> FROM person_tbl -> ORDER BY last_name; An alternative to DISTINCT is to add a GROUP BY clause that names the columns you're selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns: mysql> SELECT last_name, first_name -> FROM person_tbl -> GROUP BY (last_name, first_name);