Assign a serial number to result set – MySQL

Concerned parties may occasionally request that a serial number be displayed alongside the result set when a report is being generated. If the table lacks an auto-increment column or the result-set is lacking a unique identifier, you can assign one dynamically using the method outlined below.

— Sample dataset
CREATE TABLE tbCustomer (  

  CustName VARCHAR(45) NOT NULL,  
  CustPhone VARCHAR(45) DEFAULT NULL,  
  CustEmail VARCHAR(25) DEFAULT NULL
); 

INSERT INTO tbCustomer(CustName, CustPhone, CustEmail) VALUES 
(‘Jack’, ‘+011 543 4312′,’Jack@someco.com’),
(‘Jill’, ‘+011 543 4313′,’Jill@someco.com’),
(‘Jim’, ‘+011 543 4314′,’Jim@someco.com’),
(‘John’, ‘+011 543 4315′,’John@someco.com’),
(‘Joan’, ‘+011 543 4316′,’Joan@someco.com’),
(‘Josh’, ‘+011 543 4317′,’Josh@someco.com’);

Method-1:
SELECT @n := @n + 1 Id,
       CustName, 
       CustPhone,
CustEmail
  FROM tbCustomer, (SELECT @n := 0) m
ORDER BY CustEmail;

Method-2:
SET @n = 0;
SELECT @n := @n + 1 Id,
       CustName, 
       CustPhone,
       CustEmail
  FROM tbCustomer
ORDER BY CustEmail;

Method-3:
SELECT ROW_NUMBER() OVER (ORDER BY CustEmail) Id,
       CustName, 
       CustPhone,
       CustEmail
FROM tbCustomer;

Methods 1 and 2 behave in the same way. Declaring the variable outside of the SELECT query is the only distinction.

Happy learning!!!

Leave a Reply