Difference between revisions of "SQL Syntax"

From LongJump Support Wiki
imported>Aeric
imported>Aeric
 
(157 intermediate revisions by the same user not shown)
Line 1: Line 1:
Here is the syntax for the SQL SELECT statements that the SQL parser recognizes.
Here is the syntax for the SQL SELECT statement that the SQL parser recognizes.


;Considerations:
==About SQL Syntax==
:* SQL syntax is case insensitive.
:* SQL syntax is case insensitive.
:* Field and table names are case sensitive
:* Field and table names are case sensitive
{{:Common:SQL Legend}}
{{:Common:SQL Safety Note}}
{{:SQL Syntax Considerations}}
:''Learn more:''
:* Java [[execSQL|execSQL API]]
:* REST [[REST_API:execSQL_Resource|execSQL Resource]]
:* [[HowTo:Use a SQL Query to List Records in a Custom Page]]


''Learn more:'' [[SQL Functions]]
==SELECT Statement==
__TOC__
In a ''select'' statement, you designate one or more columns separated by commas (or "*" for all columns), plus a table or join to get the data from, and additional options:  
==SELECT STATEMENT==
;Examples:
:<syntaxhighlight lang="sql" enclose="div">
SELECT * FROM Customers
SELECT * FROM Customers LIMIT 80
SELECT * FROM Customers ORDER BY zip_code, customer_name
</syntaxhighlight>
 
;Syntax:
<div style="font-family:monospace; font-size:larger">
:SELECT
:SELECT
::[DISTINCT]
::[DISTINCT]
::
::[(] [[#column_expr|column_expr]] [, [[#column_expr|column_expr]] ...] [)]
::FROM [(] ''[[#table|table]]'' [, ''[[#table|table]]'' ...] [)]
:::[WHERE [[#where_clause|where_clause]]]
:::[GROUP BY ''col_name'' [ASC|DESC] &nbsp;[, ''col_name'' [ASC|DESC] ...]
::::[WITH ROLLUP]
::::[HAVING [[#where_clause|where_clause]]]
:::]
:::[ORDER BY ''col_name'' [ASC|DESC] &nbsp;[, ''col_name'' [ASC|DESC] ...]
:::[LIMIT {''maximum_rows'' | ''offset, maximum_rows''} ]
</div>


===Keywords===
where:
:;DISTINCT:Eliminates duplicate rows from the result set.
:;DISTINCT:Eliminates duplicate rows from the result set.
:: For example: <tt>DISTINCT(customer_name, address)</tt>
::(Parentheses are optional, but must be matched if present.)
:;WITH ROLLUP:Adds summary rows that aggregate values for each group.
:;HAVING:Is only allowed as part of GROUP BY, for performance reasons. (WHERE does the same thing outside of a GROUP BY clause, only more efficiently.)
:;''ASC'': Ascending (the default).
:;''DESC'': Descending.
:;''maximum_rows'': Maximum number of rows to return.
:;''offset'': The row to start from. Offset for the first row is zero (0).
;''Learn more:'':
:* [http://dev.mysql.com/doc/refman/5.5/en/select.html MySQL Select Statement syntax]
===column_expr===
<div style="font-family:monospace; font-size:larger">
: * &nbsp;|&nbsp; ''table_alias''.* &nbsp;|&nbsp; ''col_name'' [ [AS] ''col_alias'' ] &nbsp;|&nbsp; [[#expr|expr]] [AS] ''col_alias''
</div>
where:
:;''col_alias'':
:: Used for the column name in the result set in the [[SQL Browser]], or for the tag name in the REST [[REST API:execSQL Resource|execSQL]] resource.
:: Required when an expression is specified.
:: Can be used as a field name in a [[#group_by_clause|group_by_clause]] or [[#order_by_clause|order_by_clause]].
:: For example:
:::<tt>SELECT CONCAT(last_name,', ',first_name) AS full_name</tt>
:::: <tt>FROM Customer_Contacts ORDER BY full_name;</tt>
===table===
;Example:
:{| border="0" cellpadding="5" cellspacing="1"
| valign="top" |
:<syntaxhighlight lang="sql" enclose="div">
SELECT cust.customer_name, orders.order_amount
  FROM `Order` as orders, Customer AS cust
  GROUP BY cust.customer_name WITH ROLLUP
</syntaxhighlight>
|
[[File:customer_order_query.png]]
|}
:'''Note:''' The "Order" table must be enclosed in backticks, because that name is a reserved word in SQL. (If used to qualify a field name, the syntax would be: <tt>`Order.fieldName`</tt>.)
;Syntax:
<div style="font-family:monospace; font-size:larger">
:&nbsp;  ''table_name'' [ [AS] ''table_alias'' ]
: | ''[[#join_table|join_table]]''</div>
<blockquote>
====join_table====
<div style="font-family:monospace; font-size:larger">
:[[#table|table]] [INNER | LEFT | RIGHT] JOIN [(] ''[[#table|table]]'' [, ''[[#table|table]]'' ...] [)]
::[ON ''[[#on_clause|on_clause]]'']
</div>
:''Learn more:'' [[About Table Joins]]
====on_clause====
<div style="font-family:monospace; font-size:larger">
:''[[#on_condition|on_condition]]'' [ {AND|OR} ''[[#on_condition|on_condition]]'' ...]
</div>
   
====on_condition====
<div style="font-family:monospace; font-size:larger">
:&nbsp;  ''table_alias.col_name'' IS [NOT] NULL
: | ''table_alias.col_name'' = ''table_alias.col_name''
: | ''table_alias.col_name'' != ''table_alias.col_name''
: | ( ''[[#on_clause|on_clause]]'' )
</div>
;Considerations:
:* If multiple tables are specified, a JOIN is implied
:* An INNER join (aka a STRAIGHT join) is the default.
:* ''table_alias'' is required when specifying columns in a JOIN.
</blockquote>
===where_clause===
An [[#expr|expression]] that evaluates to true or false for a row. When true, the row is selected.
;Example:
:{| border="0" cellpadding="5" cellspacing="1"
| valign="top" |
:<syntaxhighlight lang="sql" enclose="div">
SELECT orders.order_number, Item.amount
  FROM `Order` as orders, OrderItems AS Item
  WHERE Item.related_to_Orders = orders.id
  ORDER BY orders.order_number
</syntaxhighlight>
|
[[File:order_items_query.png]]
|}
;Syntax:
<div style="font-family:monospace; font-size:larger">
:''[[#condition|condition]]'' [ {AND|OR} ''[[#condition|condition]]'' ...]
</div>
<blockquote>
====condition====
<div style="font-family:monospace; font-size:larger">
:&nbsp; expr IS [NOT] NULL
: | ''[[#expr|expr]]'' [NOT] LIKE ''[[#wildcard_string|wildcard_string]]''
: | ''[[#expr|expr]]'' [NOT] REGEXP ''[[#pattern_string|pattern_string]]'' 
: | ''[[#expr|expr]]'' [NOT] IN (''[[#expr|expr]]'' [, ''[[#expr|expr]]'' ...])
: | ''[[#expr|expr]]'' = ''[[#expr|expr]]''
: | ''[[#expr|expr]]'' < ''[[#expr|expr]]''
: | ''[[#expr|expr]]'' > ''[[#expr|expr]]''
: | ''[[#expr|expr]]'' != ''[[#expr|expr]]''
: | ''[[#expr|expr]]'' <= ''[[#expr|expr]]''
: | ''[[#expr|expr]]'' >= ''[[#expr|expr]]''
</div>
====expr====
<div style="font-family:monospace; font-size:larger">
:&nbsp; ''[[#string|string]]''
: | ''[[#number|number]]''
: | ''[[#boolean|boolean]]''
: | ''[[#date/time|date/time]]''
: | ''column_name
: | [[SQL Functions|SQL Function]]
: | + ''[[#expr|expr]]''
: | - ''[[#expr|expr]]''
: | (''[[#expr|expr]]'' [, ''[[#expr|expr]]'' ...] )
</div>
====string====
A sequence of alphanumeric characters and/or symbols, enclosed in single quotes:
<div style="font-family:monospace; font-size:larger">
:'a string'
</div>
Strings can also "escape sequences" for characters that do not appear on the keyboard:
:{| border="1" cellpadding="5" cellspacing="1"
!Escape<br>Sequence !! Character
|-
| \0 || ASCII NUL (0x00).
|-
| \' || Single quote (“'”).
|-
| \" || Double quote (“"”).
|-
| \b || Backspace character.
|-
| \n || Newline (linefeed).
|-
| \r || Carriage return.
|-
| \t || Tab character.
|-
| \\ || Backslash (“\”).
|-
| \%
| The “%” character. Used in a [NOT] LIKE expression, so the character isn't interpreted as a wildcard.
|-
| \_
| The “_” character. Used in a [NOT] LIKE expression, so the character isn't interpreted as a wildcard.
|-
| \Z || ASCII 26 (Control+Z). To prevent the character from being interpreted as End-of-File in Windows.
|}
====wildcard_string====
A [[#string|string]] containing one or more wildcards, used in a [NOT] LIKE expression:
:{| border="1" cellpadding="5" cellspacing="1"
!xx !! yy
|-
| <tt>%</tt> || Matches any number of characters, or zero characters.
|-
| <tt>_</tt>  || Matches exactly one character.
|}
====pattern_string====
A string containing a regular expression, used in a [NOT] REGEXP expression:
:{| border="1" cellpadding="5" cellspacing="1"
!Character(s) !! Meaning
|-
| align="center"|<tt>.</tt>
| Any character, including newlines.
|-
| align="center"|<tt>*</tt>
| Zero or more of previous character. As in: <tt>'.*'</tt>
|-
| align="center"|<tt>+</tt>
| One or more of previous character. As in: <tt>'t+'</tt>
|-
| align="center"|<tt>?</tt>
| Zero or one of previous character. As in: <tt>'T?'</tt>
|-
| align="center"|<tt>|</tt>
| Or. As in: <tt>'ABC|XYZ'</tt>
|-
| align="center"|<tt>(...)</tt>
| Grouping. As in: <tt>'(ABC|XYZ) Company'</tt>, <tt>'(ABC|XYZ)( Company)?'</tt><br>(The latter pattern matches "ABC", "XYC", "ABC Company", and "XYZ Company".)
|-
| align="center"|<tt>[...]</tt>
| Character set:
:<tt>[abcdef]</tt> - match any of the characters in the set
:<tt>[a-f]</tt> - match any of the characters in the range
:<tt>[a-fA-FzZ]</tt> - Combination, Match any of the specified characters,or any of the characters in either range.
:<tt>[^...]</tt> - Negation. Match anything other than the characters specified in the set.
|-
| align="center"|<tt>^</tt>
| Beginning of a string when it is in a pattern.<br/>
"Not", when it is the first character in a character set.
|-
| align="center"|<tt>$</tt>
| End of string.
|}
<blockquote>
'''Note:'''<br>
Since strings use backslash escape syntax (for example, “\n” to represent the newline character), you must double any backslash characters you use in your REGEXP strings. For example, to include a question mark (<tt>?</tt>) in a string, the pattern matcher needs to see <tt>\?</tt>. (So it looks for a question mark character, instead of interpreting the question mark as "zero or one".) To get that string to the pattern matcher, you specify <tt>\\?</tt>. String processing reduces the <tt>\\</tt> to <tt>\</tt>, so the regular expression processor sees <tt>\?</tt>, as intended.
For example, this expression evaluates as true:
:<tt>SELECT 'Question?' REGEXP 'Q.*\\?'</tt>
</blockquote>
====number====
Numbers can be specified as integers:
:1221
:0
:-32
Or as floating point/decimal numbers:
:294.42
:-32032.6809e+10
:148.00
====boolean====
Boolean true/false values can be specified as integers:
:1 (true)
:0 (false)
====date/time====
:''Learn more:'' [[SQL Functions#Date and Time Functions|SQL Date and Time Functions]]
:{| border="1" cellpadding="5" cellspacing="1"
! !! Date !! "As Entered" Date/Time !! "Convert to Local" Date/Time
|-
| SQL Browser
| <tt>'YYYY-MM-DD'</tt><br/>([[UTC Format]])
| <tt>'YYYY-MM-DD&nbsp;hh:mm:ss'</tt>
| <tt>'YYYY-MM-DD<b>T</b>hh:mm:ss<b>Z</b>'</tt><br>([[UTC Format]])
|-
|REST
| <tt>'YYYY-MM-DD'</tt><br/> ([[UTC Format]])
| <tt>'YYYY-MM-DD&nbsp;hh:mm:ss'</tt>
| <tt>'YYYY-MM-DD<b>T</b>hh:mm:ss<b>Z</b>'</tt><br>([[UTC Format]])
|-
|Java
| User format, specified<br>in [[Company Information#Date & Currency Format|Company Information]]
| User format, in user timezone
| User format, in user timezone
|}
</blockquote>

Latest revision as of 19:27, 2 October 2012

Here is the syntax for the SQL SELECT statement that the SQL parser recognizes.

About SQL Syntax

  • SQL syntax is case insensitive.
  • Field and table names are case sensitive
Legend
  • [ x ] - Optional (one or none)
  • [, x ... ] - Optional additional values, in a comma-separated list
  • x | y - Choose one. Curly braces are added when needed: { x | y } ...
  • CAPITALIZED - SQL Keyword (case insensitive)
  • italicized - Value you supply. (Table names and column names are case-sensitive)


Notepad.png

Note:
When you make a SQL query, you are not querying the platform database directly. Rather, you are querying a view of the database that is restricted by your role permissions, so the records and fields you can see using SQL are the same as those you see when using the GUI. In addition, the platform implements various safeguards to prevent SQL Injection attacks.

Considerations
  • SQL syntax is not case-sensitive, except for table names and field names.
  • Backticks are (`) are needed around any table or field name that is one of the SQL Reserved Words.
For example: SELECT * FROM `Order`
Without the backticks, you get an error like this:
Encountered "Order" at line column 15. Was expecting one of (...
That error means the parser found a word it recognized, but didn't find other things it expected before it got to that word.
  • When either a table name or a field name is reserved word, and both are used together, then backticks are needed around the combination.
For example: `Order.order_number`
  • If you do a query on different tables that have fields with the same name, you should provide column aliases for those fields. (Otherwise, a query for A.phone and B.phone identifies both sets of values as "phone". A column alias like A.phone AS A-phone makes it possible to tell which table a set of values came from.)
Learn more: column_expr
Learn more:

SELECT Statement

In a select statement, you designate one or more columns separated by commas (or "*" for all columns), plus a table or join to get the data from, and additional options:

Examples
SELECT * FROM Customers
SELECT * FROM Customers LIMIT 80
SELECT * FROM Customers ORDER BY zip_code, customer_name
Syntax
SELECT
[DISTINCT]
[(] column_expr [, column_expr ...] [)]
FROM [(] table [, table ...] [)]
[WHERE where_clause]
[GROUP BY col_name [ASC|DESC]  [, col_name [ASC|DESC] ...]
[WITH ROLLUP]
[HAVING where_clause]
]
[ORDER BY col_name [ASC|DESC]  [, col_name [ASC|DESC] ...]
[LIMIT {maximum_rows | offset, maximum_rows} ]

where:

DISTINCT
Eliminates duplicate rows from the result set.
For example: DISTINCT(customer_name, address)
(Parentheses are optional, but must be matched if present.)
WITH ROLLUP
Adds summary rows that aggregate values for each group.
HAVING
Is only allowed as part of GROUP BY, for performance reasons. (WHERE does the same thing outside of a GROUP BY clause, only more efficiently.)
ASC
Ascending (the default).
DESC
Descending.
maximum_rows
Maximum number of rows to return.
offset
The row to start from. Offset for the first row is zero (0).
Learn more:

column_expr

*  |  table_alias.*  |  col_name [ [AS] col_alias ]  |  expr [AS] col_alias

where:

col_alias
Used for the column name in the result set in the SQL Browser, or for the tag name in the REST execSQL resource.
Required when an expression is specified.
Can be used as a field name in a group_by_clause or order_by_clause.
For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name
FROM Customer_Contacts ORDER BY full_name;

table

Example
SELECT cust.customer_name, orders.order_amount 
   FROM `Order` as orders, Customer AS cust
   GROUP BY cust.customer_name WITH ROLLUP

Customer order query.png

Note: The "Order" table must be enclosed in backticks, because that name is a reserved word in SQL. (If used to qualify a field name, the syntax would be: `Order.fieldName`.)
Syntax
  table_name [ [AS] table_alias ]
| join_table

join_table

table [INNER | LEFT | RIGHT] JOIN [(] table [, table ...] [)]
[ON on_clause]
Learn more: About Table Joins

on_clause

on_condition [ {AND|OR} on_condition ...]

on_condition

  table_alias.col_name IS [NOT] NULL
| table_alias.col_name = table_alias.col_name
| table_alias.col_name != table_alias.col_name
| ( on_clause )
Considerations
  • If multiple tables are specified, a JOIN is implied
  • An INNER join (aka a STRAIGHT join) is the default.
  • table_alias is required when specifying columns in a JOIN.

where_clause

An expression that evaluates to true or false for a row. When true, the row is selected.

Example
SELECT orders.order_number, Item.amount 
   FROM `Order` as orders, OrderItems AS Item
   WHERE Item.related_to_Orders = orders.id
   ORDER BY orders.order_number

Order items query.png

Syntax
condition [ {AND|OR} condition ...]

condition

  expr IS [NOT] NULL
| expr [NOT] LIKE wildcard_string
| expr [NOT] REGEXP pattern_string
| expr [NOT] IN (expr [, expr ...])
| expr = expr
| expr < expr
| expr > expr
| expr != expr
| expr <= expr
| expr >= expr

expr

  string
| number
| boolean
| date/time
| column_name
| SQL Function
| + expr
| - expr
| (expr [, expr ...] )

string

A sequence of alphanumeric characters and/or symbols, enclosed in single quotes:

'a string'

Strings can also "escape sequences" for characters that do not appear on the keyboard:

Escape
Sequence
Character
\0 ASCII NUL (0x00).
\' Single quote (“'”).
\" Double quote (“"”).
\b Backspace character.
\n Newline (linefeed).
\r Carriage return.
\t Tab character.
\\ Backslash (“\”).
\% The “%” character. Used in a [NOT] LIKE expression, so the character isn't interpreted as a wildcard.
\_ The “_” character. Used in a [NOT] LIKE expression, so the character isn't interpreted as a wildcard.
\Z ASCII 26 (Control+Z). To prevent the character from being interpreted as End-of-File in Windows.

wildcard_string

A string containing one or more wildcards, used in a [NOT] LIKE expression:

xx yy
% Matches any number of characters, or zero characters.
_ Matches exactly one character.

pattern_string

A string containing a regular expression, used in a [NOT] REGEXP expression:

Character(s) Meaning
. Any character, including newlines.
* Zero or more of previous character. As in: '.*'
+ One or more of previous character. As in: 't+'
? Zero or one of previous character. As in: 'T?'
| XYZ'
(...) XYZ) Company', '(ABC|XYZ)( Company)?'
(The latter pattern matches "ABC", "XYC", "ABC Company", and "XYZ Company".)
[...] Character set:
[abcdef] - match any of the characters in the set
[a-f] - match any of the characters in the range
[a-fA-FzZ] - Combination, Match any of the specified characters,or any of the characters in either range.
[^...] - Negation. Match anything other than the characters specified in the set.
^ Beginning of a string when it is in a pattern.

"Not", when it is the first character in a character set.

$ End of string.

Note:
Since strings use backslash escape syntax (for example, “\n” to represent the newline character), you must double any backslash characters you use in your REGEXP strings. For example, to include a question mark (?) in a string, the pattern matcher needs to see \?. (So it looks for a question mark character, instead of interpreting the question mark as "zero or one".) To get that string to the pattern matcher, you specify \\?. String processing reduces the \\ to \, so the regular expression processor sees \?, as intended.

For example, this expression evaluates as true:

SELECT 'Question?' REGEXP 'Q.*\\?'

number

Numbers can be specified as integers:

1221
0
-32

Or as floating point/decimal numbers:

294.42
-32032.6809e+10
148.00

boolean

Boolean true/false values can be specified as integers:

1 (true)
0 (false)

date/time

Learn more: SQL Date and Time Functions
Date "As Entered" Date/Time "Convert to Local" Date/Time
SQL Browser 'YYYY-MM-DD'
(UTC Format)
'YYYY-MM-DD hh:mm:ss' 'YYYY-MM-DDThh:mm:ssZ'
(UTC Format)
REST 'YYYY-MM-DD'
(UTC Format)
'YYYY-MM-DD hh:mm:ss' 'YYYY-MM-DDThh:mm:ssZ'
(UTC Format)
Java User format, specified
in Company Information
User format, in user timezone User format, in user timezone