How to Select Distinct Data from Table in MySQL or MariaDB - MySQL Developer Tutorial

How to Select Distinct Data from Table in MySQL or MariaDB

When you use distinct keyword in Select, it returns you distinct (different) values.  Below is the syntax you will use to get distinct values from MySQL Table.


Select distinct column1,column2,... from YourTableName;


Example :
Let's create customer table and then insert some rows in customer table.

CREATE TABLE `customer` (
  `idcustomer` int,
  `firstname` varchar(50)  NULL,
  `lastname` varchar(30)  NULL,
  `age` int(11) DEFAULT NULL,
  `phonenumber` char(11) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `gender` char(1) NOT NULL
) ;



insert some values in table.

insert into customer(idcustomer,firstname,lastname,age,phonenumber,dob,gender)
values
(1,'Aamir','Ali',39,'505-4141969','1980-01-01','M'),
(2,'Aamir','Naz',39,'505-4141969','1980-01-01','M'),
(3,'Aamir','Shahzad',39,'505-4141900','1980-01-01','M');


Now let's say if you want to get the distinct or different values from first name column, you can run below  statement.


Select distinct firstname from customer;


The above query will return you only "Aamir".

Now let's say if you want to get distinct values for firstname and phonenumber, then you will get two values.


Select distinct firstname,phonenumber from customer;



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.