In this article, we are going to cover the LOG2() function that means it will calculate the logarithm of a specific number with base 2.
Pre-requisite :LOG function
LOG2() function in MySQL is used to calculate the natural logarithm of a specific number with base 2. The number must be >0 Otherwise it will return NULL.
Syntax :
Example-2 :
Logarithm of 0 using LOG2() function.
Example-3 :
The LOG2 function can also be used to find the logarithmic value with base 2 of a column data. To demonstrate create a table named Product.
Now, we are going to find the logarithmic values with base 2 for all the records present in the Service_grade column.
LOG2( X )Parameter : LOG2() function accepts one parameter which is described below as following.
- X -A number whose logarithm value with base 2 we want to calculate . It should be positive number.
SELECT LOG2(16) AS Log2_Val;Output :
| Log2_Val |
|---|
| 4 |
SELECT LOG2(0) AS Log2_Val;Output :
| Log2_Val |
|---|
| NULL |
CREATE TABLE Product
(
Product_id INT AUTO_INCREMENT,
Product_name VARCHAR(100) NOT NULL,
Buying_price DECIMAL(13,2) NOT NULL,
Selling_price DECIMAL(13,2) NOT NULL,
Service_grade Decimal(6,2) NOT NULL,
PRIMARY KEY(Product_id)
);
Now inserting some data to the Product table :
INSERT INTO Product
(Product_name, Buying_price, Selling_price, Service_grade)
VALUES
('Touring Bike' ,2019.00 ,3009.6 ,0.89 ) ,
('Mountain Bike' ,3019.50 ,4000.56 ,1.00 ) ,
('Road Bike' ,1019.20 ,2000.56 ,-0.89 ) ,
('Road Bicycle',1019.50 ,1500.56 ,-1.50 ) ,
('Racing Bicycle',3019.50 ,4000.56 ,2.00) ;
Showing all data in Product table :
Select * from Product;
| Product_id | Product_name | Buying_price | Selling_price | Service_grade |
|---|---|---|---|---|
| 1 | Touring Bike | 2019.00 | 3009.60 | 0.89 |
| 2 | Mountain Bike | 3019.50 | 4000.56 | 1.00 |
| 3 | Road Bike | 1019.20 | 2000.56 | -0.89 |
| 4 | Road Bicycle | 1019.50 | 1500.56 | -1.50 |
| 5 | Racing Bicycle | 3019.50 | 4000.56 | 2.00 |
Select
Product_id,
Product_name,
Buying_price,
Selling_price,
Service_grade,
LOG2(Service_grade) AS GRADELOG2
FROM Product;
Output :
| Product_id | Product_name | Buying_price | Selling_price | Service_grade | GRADELOG2 |
|---|---|---|---|---|---|
| 1 | Touring Bike | 2019.00 | 3009.60 | 0.89 | -0.16812275880832692 |
| 2 | Mountain Bike | 3019.50 | 4000.56 | 1.00 | 0 |
| 3 | Road Bike | 1019.20 | 2000.56 | -0.89 | NULL |
| 4 | Road Bicycle | 1019.50 | 1500.56 | -1.50 | NULL |
| 5 | Racing Bicycle | 3019.50 | 4000.56 | 2.00 | 1 |