// math reference

SQL LOG2 function

Returns the base-2 logarithm: LOG2(8) is 3 and LOG2(1024) is 10.

카테고리
Math
Returns
float / double
In this category
23 of 82

구문

LOG2(number)

엔진 지원

엔진Support메모
SQL Server Different name or syntax No LOG2; LOG(x, 2) with the base as second argument
PostgreSQL Different name or syntax No LOG2; log(2, x) with the base as first argument, or ln(x)/ln(2)
MySQL 예 Supported under this name.
SQLite 예 log2(X) on 3.35+ with math functions
Oracle Different name or syntax No LOG2; LOG(2, x)

예시

MySQL

SELECT LOG2(1024) AS ten;  -- 10

PostgreSQL

SELECT LOG(2, 1024) AS ten;  -- 10

SQL Server

SELECT LOG(1024, 2) AS ten;  -- 10

알아 두면 좋은 정보

  • Same function, three spellings: LOG2(x) on MySQL and SQLite, LOG(x, 2) on SQL Server, LOG(2, x) on PostgreSQL and Oracle; note SQL Server reverses the arguments.
  • Domain is positive: LOG2(0) is NULL (MySQL, SQLite) or an error elsewhere.
  • For bit-length work, FLOOR(LOG2(n)) + 1 is the number of binary digits for n >= 1. Near large powers of two, float error can put LOG2 a hair under the integer, so check with a power of 2 when exactness matters.

Questions about LOG2

What is the PostgreSQL equivalent of LOG2?

log(2, x): PostgreSQL's two-argument log takes the base first. There is no log2 keyword; ln(x) / ln(2) also works.

How do I compute LOG2 on SQL Server?

LOG(x, 2). SQL Server's LOG puts the value first and the base second, the reverse of MySQL, Oracle and SQLite two-argument logs.

What is LOG2 used for?

Tree depth and bit-count math: LOG2(1024) is 10 because 2 to the 10th is 1024, and FLOOR(LOG2(n)) + 1 counts an integer's binary digits.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.