百度智能云

All Product Document

          Log Service

          SQL Syntax

          Catalog

          1. Syntax Support
          2. Operator
          3. Built-in Function
            3.1 Type Conversion Function
            3.2 Aggregate Function
            3.3 String Function
            3.4 Mathematical Functions
            3.5 Date time Function
            3.6 Condition Function
          4. appendix
            4.1 Date Format
            4.2 Keywords

          Syntax Support

          BLS supports basic SELECT query, and the specific query syntax is

          SELECT 
              select_expr [, select_expr] ... 
              [FROM subquery [AS] table_id] 
              [WHERE where_condition] 
              [GROUP BY {col_name | expr}, ... ] 
              [HAVING where_condition] 
              [ORDER BY {col_name | expr} [ASC | DESC], ...] 
              [LIMIT [offset,] row_count] 

          Among them, where_condition is a conditional expression whose execution result is a Boolean value. Don't write the FROM clause when you don't need a subquery.

          Field names are case sensitive, and try to avoid using keyword. If keywords are used, add backquotes, for example: `action`.

          Operator

          Unary prefix operation

          Operator Example Description
          +/- -A Change the sign of the parameter

          Binary operation

          Operator Example Description
          + A + B Addition operation
          - A-B Subtraction operation
          * A * B Multiplication operation
          / A / B Division operation
          % A% B Modulus operation, the result is the remainder of A divided by B

          Relational operations

          Operator Example Description
          = A = B If A is equal to B, return TRUE, otherwise return FALSE. If the types of A and B are not comparable, return NULL
          != A != B If A is not equal to B, return TRUE, otherwise return FALSE. If the types of A and B are not comparable, return NULL
          > A> B If A is greater than B, return TRUE, otherwise return FALSE. If the types of A and B are not comparable, return NULL
          >= A >= B If A is greater than or equal to B, it returns TRUE, otherwise it returns FALSE. If the types of A and B are not comparable, return NULL
          < A <B If A is less than B, return TRUE, otherwise return FALSE. If the types of A and B are not comparable, return NULL
          <= A <= B If A is less than or equal to B, it returns TRUE, otherwise it returns FALSE. If the types of A and B are not comparable, return NULL
          [NOT] LIKE A LIKE pattern If A [not] matches the pattern, return TRUE, otherwise return FALSE
          IS [NOT] NULL A IS NULL If A [NO] is NULL, return TRUE, otherwise return FALSE
          IS [NOT] TRUE/FALSE A IS TRUE If A [NO] is TRUE/FALSE, return TRUE, otherwise return FALSE

          Logic operation

          Operator Example Description
          [NOT] IN A IN (val1, val2, ...) If A [not] is equal to any parameter value, return TRUE, otherwise return FALSE
          AND A AND B If both A and B are TRUE, return TRUE, otherwise return FALSE. If A or B is not boolean, return NULL
          OR A OR B If A or B is TRUE, return TRUE, otherwise return FALSE. If A or B is not boolean, return NULL
          NOT NOT A If A is FALSE, return TRUE, otherwise return FALSE. If A is not boolean, return NULL

          Built-in Function

          Type Conversion Function

          Function signature Return value Description Example
          cast(expr as <type>) <type> Convert the value of expr into <type> type, <type> supports BIGINT, DECIMAL, VARCHAR, TIMESTAMP >select cast("123" as BIGINT)
          123

          Aggregate Function

          Function signature Return value Description Example
          count(*), count(expr), count(DISTINCT expr) Int Calculate the number of qualified result rows >select count(*)
          10
          sum(col) T Calculate the sum of the elements >select sum(num)
          983
          avg(col) Double Calculate the average of the elements >select avg(num)
          73.14
          max(col) T Calculate the maximum value of the element >select max(num)
          99
          min(col) T Calculate the minimum value of the element >select min(num)
          62
          first(col) T Calculate the first value of the element >select first(num)
          87
          last(col) T Calculate the last value of the element >select min(num)
          95

          String Function

          Function signature Return value Description Example
          reverse(String str) String Return the string in reverse order >select reverse("hello")
          olleh
          lower(String str) String Return lowercase format string >select lower("fOoBaR")
          foobar
          upper(String str) String Return uppercase format string >select upper("fOoBaR")
          FOOBAR
          capitalize(String str) String Return all words with the first letter capitalized format string >select upper("fOoBaR")
          FOoBaR
          substring(String str, Int start [, Int len]) String Return the substring of the original string starting from the start position and length len. start starts from 1 and supports negative numbers. Then, the position is calculated backward from the end. If the len parameter is not passed, it means intercepting to the end of the string >select substr("fOoBaR", 2, 4)
          OoBa
          >select substr("fOoBaR", -3, 2)
          Ba
          substr(String str, Int start [, Int len]) String alias of substring()
          replace(String str, String OLD, String NEW) String Returns the string str in which the OLD substring is replaced with the NEW substring >select replace("abcdef", "abc", "cba")
          cbadef
          length(String str) Int Length of the string returned >replace("abcdef", "abc", "cba")
          cbadef
          locate(String substr, String str) Int Return the first occurrence of substr in the string str, or 0 if there is none >select locate(".", "3.14")
          2
          position(String substr, String str) Int Alias of locate()
          concat(String A, String B...) String Return the string of all parameters concatenated according to the incoming order >select concat("foo", "bar")
          foobar

          Mathematical Function

          Function signature Return value Description Example
          abs(Double a), abs(Int a) Double/Int Calculate absolute value >select abs(-2)
          2
          sqrt(Double a) Double Calculate the square root >select sqrt(100)
          10
          greatest(T v1, T v2, ...) T Calculate the maximum value of the parameters, if any parameter is Null, return Null >select greatest(1, 3.14, -5)
          3.14
          least(T v1, T v2, ...) T Calculate the minimum value of the parameters, if any parameter is Null, then return Null >select least(1, 3.14, -5)
          -5
          rand() Double Return a random number between 0 and 1, the random number obtained for each row of the data set is different >select rand()
          0.3
          ceil(Double a) Int Return the integer greater than or equal to a and closest to a >select ceil(3.14)
          4
          floor(Double a) Int Return the integer less than or equal to a and closest to a >select floor(3.14)
          3
          log(Double a) Double Calculate the logarithm to base 2 >select log(32)
          5
          ln(Double a) Double Calculate the natural logarithm >select ln(100)
          4.61512051684126
          pow(Double a, Double p) Double Calculate the pth power of a >select pow(2, 5)
          32

          Date and Time Functions

          Function signature Return value Description Example
          now() DateTime Return the current local time >select now()
          2020-01-16T08:30:50Z
          current_timestamp() DateTime Alias of now()
          unix_timestamp([String/DateTime date[, String format]]) Int Convert date time string or DateTime type value into Unix timestamp according to format. The ISO8601 format is supported by default, and it is parsed according to the time zone in the string. If parsed according to the format, the local time zone will be used. >select unix_timestamp("2019-11-11T11:11:11Z")
          1573470671
          >select unix_timestamp("2019-11-11 11:11:11", "%Y-%m-%d %H:%i:%s")
          1573441871
          from_unixtime(Int unixtime[, String format]) String Convert unixtime (from 1970-01-01 00:00:00 UTC to now to the number of seconds) into a string representing local time, the default format is "1970-01-01 00:00:00", and the string forma can be specified by format. Please refer to Appendix for supported date_format >select from_unixtime(0)
          1970-01-01 08:00:00
          >select from_unixtime(unix_timestamp("2019-11-11T11:11:11+08:00"))
          2019-11-11 11:11:11
          str_to_date(String str, String format) DateTime Parse date and time string str according to format >select str_to_date("2019-11-11 11:11:11", "%Y-%m-%d %H:%i:%s")
          2019-11-11T03:11:11Z
          year(String/DateTime date) Int Return the year of the date date >select year("2019-11-07T09:09:16+ 08:00")
          2019
          month(String/DateTime date) Int Return the month of the date >select year("2019-11-07T09:09:16+08:00")
          11
          day(String/DateTime date) Int Alias of dayofmonth()
          weekday(String/DateTime date) Int Return the position of the date in a week (0 = Monday, 1 = Tuesday, ... 6 = Sunday) >select weekday("2019-11-07T09:09:16+08:00")
          3
          dayofyear(String/DateTime date) Int Return the position of the date in the year, and the optional value is from 1 to 366 >select dayofyear("2019-11-07T09:09:16+08:00")
          311
          dayofmonth(String/DateTime date) Int Return the position of date in a month >select dayofmonth("2019-11-07T09:09:16+08:00")
          7
          dayofweek(String/DateTime date) Int Return the position of date in a week (1 = Sunday, 2 = Monday, ... 7 = Saturday) >select dayofweek("2019-11-07T09:09:16+08:00")
          5

          Condition Function

          Function signature Return value Description Example
          if(Boolean testCondition, T valueTrue, T valueFalseOrNull) T If the test condition is true, return ValueTrue, otherwise return ValueFalseOrNull >select if(2>1, 1, 0)
          1
          nullif(T a, T b) T If a = b, return Null, otherwise return a >select nullif(1, 1)
          null
          coalesce(T v1, T v2, ...) T Return the first value that is not Null, if the parameters are all Null, return Null >select coalesce(null, 0, false, 1)
          0
          CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END T If a = b, return c; if a = d, return e; otherwise, return f >select case substring("abc", 1, 1) when "a" then "a" when "b" then "b" else "c" end
          a
          CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END T If a = true, return b; if c = true, return d; otherwise return e >select case when substring("abc", 1, 1) = "a" then "a" when 2> 1 then "b" else "c" end
          a

          Appendix

          Date Format

          Date_format supported by time function

          Placeholder Description
          %a Abbreviated weekday name (Sun..Sat)
          %b Abbreviated month name (Jan..Dec)
          %c Month, numeric (0..12)
          %D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
          %d Day of the month, numeric (00..31)
          %e Day of the month, numeric (0..31)
          %f Microseconds (000000..999999)
          %H Hour (00..23)
          %h Hour (01..12)
          %I Hour (01..12)
          %i Minutes, numeric (00..59)
          %j Day of year (001..366)
          %k Hour (0..23)
          %l Hour (1..12)
          %M Month name (January..December)
          %m Month, numeric (00..12)
          %p AM or PM
          %r Time, 12-hour (hh:mm:ss followed by AM or PM)
          %S Seconds (00..59)
          %s Seconds (00..59)
          %T Time, 24-hour (hh:mm:ss)
          %W Weekday name (Sunday..Saturday)
          %w Day of the week (0=Sunday..6=Saturday)
          %Y Year, numeric, four digits
          %y Year, numeric (two digits)
          %% A literal % character

          Keyword

          #

          _binary
          _utf8mb4

          A - F

          accessible action add against all alter analyze and as asc asensitive auto_increment before begin between bigint binary bit blob bool boolean both by call cascade case cast change char character charset check collate collation column columns comment commit committed condition constraint continue convert create cross current_date current_time current_timestamp current_user cursor database databases date datetime day_hour day_microsecond day_minute day_second dec decimal declare default delayed delete desc describe descriptor deterministic distinct distinctrow div double drop duplicate each else elseif enclosed end engines enum escape escaped exists exit expansion explain false fetch fields float float4 float8 flush for force foreign from full fulltext

          G - N

          generated geometry geometrycollection get global grant group group_concat having high_priority hour_microsecond hour_minute hour_second if ignore in index infile inner inout insensitive insert int int1 int2 int3 int4 int8 integer interval into io_after_gtids is isolation iterate join json key key_block_size keys kill language last_insert_id leading leave left less level like limit linear lines linestring load localtime localtimestamp lock long longblob longtext loop low_priority master_bind match maxvalue mediumblob mediumint mediumtext middleint minute_microsecond minute_second mod mode modifies multilinestring multipoint multipolygon names natural nchar next no no_write_to_binlog not null numeric

          O - S

          off offset on only optimize optimizer_costs option optionally or order out outer outfile partition plugins point polygon precision primary procedure processlist query read read_write reads real references regexp release rename reorganize repair repeat repeatable replace require resignal restrict return revoke right rlike rollback schema schemas second_microsecond select sensitive separator serializable session set share show signal signed smallint spatial specific sql sql_big_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting status stored straight_join stream string substr substring

          T - Z

          table tables terminated text than then time timestamp timestampadd timestampdiff tinyblob tinyint tinytext to trailing transaction trigger true truncate uncommitted undo union unique unlock unsigned update usage use using utc_date utc_time utc_timestamp values varbinary varchar varcharacter variables varying view vindex vindexes virtual vitess_keyspaces vitess_shards vitess_tablets vitess_target vschema vschema_tables warnings when where while with write xor year year_month zerofill

          Previous
          Log Query
          Next
          Search Syntax