Open In App

LOG2() Function in MySQL

Last Updated : 01 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

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.

Returns :
It returns the natural logarithm of given number x with base 2.

Example-1 :
Logarithm of given number with base 2 using LOG2() function.

SELECT LOG2(16) AS Log2_Val;

Output :

Log2_Val
4

Example-2 :
Logarithm of 0 using LOG2() function.

SELECT LOG2(0) AS Log2_Val;

Output :

Log2_Val
NULL

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.

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

Now, we are going to find the logarithmic values with base 2 for all the records present in the Service_grade column.

        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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads