Open In App

LOG2() Function in MySQL

Last Updated : 01 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
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_idProduct_nameBuying_priceSelling_priceService_grade
1Touring Bike2019.003009.600.89
2Mountain Bike3019.504000.561.00
3Road Bike1019.202000.56-0.89
4Road Bicycle1019.501500.56-1.50
5Racing Bicycle3019.504000.562.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_idProduct_nameBuying_priceSelling_priceService_gradeGRADELOG2
1Touring Bike2019.003009.600.89-0.16812275880832692
2Mountain Bike3019.504000.56 1.000
3Road Bike1019.202000.56-0.89NULL
4Road Bicycle1019.501500.56-1.50NULL
5Racing Bicycle3019.504000.562.001

Next Article
Article Tags :
Practice Tags :

Similar Reads