// math reference

SQL LOG function

Returns a logarithm, but the argument order and the one-argument default base differ per engine: the single most error-prone swap in SQL math.

カテゴリ
Math
Returns
float / double
In this category
21 of 82

構文

LOG(base, number)  -- MySQL, Oracle, SQLite
LOG(number, base)  -- SQL Server
LOG(number)  -- base 10 on PostgreSQL, SQLite

Each block is a separate form. The support table and the examples show which engine takes which.

エンジンサポート

エンジンSupportメモ
SQL Server Different name or syntax LOG(number [, base]): value first, base second, the reverse of MySQL and Oracle
PostgreSQL はい log(x) with one argument is base 10; log(base, x) with two takes the base first
MySQL はい LOG(x) with one argument is the natural log, LOG(base, x) takes the base first (the opposite default from PostgreSQL)
SQLite Different name or syntax Requires 3.35+; log(x) is base 10, log(base, x) takes the base first, ln(x) is natural
Oracle はい Supported under this name.

例

MySQL

SELECT LOG(2, 8) AS three;  -- 3

SQL Server

SELECT LOG(8, 2) AS three;  -- 3: value first, base second

PostgreSQL

SELECT LOG(100) AS base_ten, LOG(2, 8) AS base_two;  -- 2, 3

知っておくと便利なこと

  • MySQL LOG(10, 100) is 2 (base 10); SQL Server LOG(10, 100) is the log of 10 in base 100. Swapping the order silently returns a wrong number instead of an error.
  • PostgreSQL log(100) with one argument is base 10, but MySQL LOG(100) is the natural log: the same call means different things.
  • Oracle's LOG needs two arguments and a positive base other than 1: LOG(0.5, 4) is -2, LOG(1, 4) raises ORA-01428. Use LN for base e.

Questions about LOG

Why does my LOG return the wrong number?

Almost always the base is in the wrong position. MySQL, Oracle and SQLite take LOG(base, number); SQL Server takes LOG(number, base). A one-argument LOG is base e on MySQL but base 10 on PostgreSQL and SQLite.

How do I write a log in an arbitrary base?

Use the change-of-base formula, valid everywhere: LN(x) / LN(b). It avoids the argument-order trap entirely.

What is the base of a one-argument LOG?

Depends on the engine: natural (e) on SQL Server and MySQL, base 10 on PostgreSQL and SQLite. Prefer LN or LOG10 when you mean something specific.

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.