Operator precedence for IBM DB2 - sql

What are the operator precedence rules for the DB2 RDBMS engine?
I am looking for explicit rules which mention actual operators instead of precedence relations between groups of operators.
I found this document http://www-01.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/com.ibm.db2z10.doc.sqlref/src/tpc/db2z_precedenceofoperations.dita via googling, but I am looking for something that goes into more detail, e.g. precedence relations between AND, OR and NOT

If you're looking for search-condition operators, then see the Information Center section on Search conditions. Additional details are in the topic, but the basic rules are:
Search conditions within parentheses are evaluated first. If the order
of evaluation is not specified by parentheses, NOT is applied before
AND, and AND is applied before OR. The order in which operators at the
same precedence level are evaluated is undefined to allow for
optimization of search conditions.

From DB2 for z/OS 10.0.0>DB2 reference information>DB2 SQL>Language elements>Expressions>Precedence of operations
Expressions within parentheses are evaluated first. When the order of
evaluation is not specified by parentheses, prefix operators are
applied before multiplication and division, and multiplication,
division, and concatenation are applied before addition and
subtraction. Operators at the same precedence level are applied from
left to right.

I used a case in my order by and it seemed to work
SELECT * FROM TABLE WHERE KEY IN (KEY1 , KEY2) ORDER BY
CASE
WHEN KEY = KEY1 THEN 1
ELSE 2
END
I haven't check with more than 2 keys.

It's over here. Simple google could help you.

Related

XPath: multiple predicates vs logical And operator

When we have multiple terms to locate an element we can use a single predicate with logical and operator inside it or to use multiple predicates with single term inside each predicate.
For example on this page we can locate links to questions containing selenium in their links with this XPath:
"//a[#class='s-link'][contains(#href,'selenium')]"
and with this
"//a[#class='s-link' and contains(#href,'selenium')]"
I'm wondering if there are any differences between these 2 approaches?
The expressions are equivalent provided that neither of the predicates is positional. A predicate is positional if (a) its value is numeric, or (b) its value depends on the current position in the dynamic context (for practical purposes, that means if it's an expression that calls the position() function).
Assuming this condition is met, there is no good reason for preferring one expression over the other. It's possible of course that some XPath processor might evaluate one of them faster than the other, but it's very unlikely to be a signficant difference, and it could equally well favour either of the two.
There are minor differences in the degree of freedom offered to processors in how far they can go in optimising the constructs in ways that affect error handling, and these rules vary slightly between XPath versions, but again this is very unlikely to be significant in practice.
The equivalence doesn't apply to positional predicates because (a) when you write A[X][Y], the value of position() within Y is different from its value within X, and (b) if X or Y is numeric then it is interpreted as position()=X (or position()=Y), and this doesn't apply to the operands of and: you can't rewrite A[#code][1] as A[#code and 1].
There may be differences in the algorithm that evaluates these expressions, but the result is the same. Things would be different if the second condition contained position() or last():
//a[#class='s-link'][position() > 1] gives all s-link anchors except the first (because position() is the position in the nodeset //a[#class='s-link']) whereas
//a[#class='s-link' and position() > 1] gives all s-link anchors that come after the first anchor overall (because position() is the position in the nodeset //a).
Also, you can select the first s-link anchor with //a[#class='s-link'][1], but not with //a[#class='s-link' and 1].

Arity of BETWEEN expression

What is the arity of the sql BETWEEN expression? I thought it was three (ternary) since the expression usually looks like:
WHERE...
1 BETWEEN 2 AND 3
But it's listed as binary on BigQuery's documentation, and I assume other places as well.
Source: Operators.
What is the arity of the BETWEEN expression and why? I think the answer is 3 from the following example:
select
~ (SELECT -1 AS expr_1) AS 'bitwise_arity_1',
(SELECT 1 AS expr_1) * (SELECT 2 AS expr_2) AS 'times_arity_2',
(SELECT 1 AS expr_1) BETWEEN
(SELECT 2 AS expr_2) AND (SELECT 3 AS expr_3) AS 'bitwise_arity_3?'
I suppose one way to interpret it might just be that the grammar is:
expr 'BETWEEN' logicalAndExpr
And so the two expressions in the logicalAnd are just grouped into one. Is that a correct understanding?
SQLFiddle: http://www.sqlfiddle.com/#!9/b28da2/2156
It's binary, in syntactic terms. See below for a discussion of syntax vs. semantics, where I note that a better syntactic term is "infix".
Similarly, function calls and array subscripting are postfix unary operators and the C family's conditional operator (often misnamed "the ternary operator" as though it were the only such thing) is also infix. The reason is that the interior operands (the operands between BETWEEN...AND, (...), [...], and ?...:, respectively) are fenced off from the rest of the syntax by the pair of surrounding terminal tokens which function as a syntactic barrier, like parentheses. Precedence does not penetrate to the enclosed operands; only the outer operand(s) remain floating in the syntax.
The semantic view is quite different, of course. BETWEEN...AND and ?...: are certainly three-argument functions, although since the latter is short-circuiting, only two of the three arguments are ever evaluated, which makes it hard to discuss in strict mathematical terms [Note 1]. Moreover, the semantic view is complicated by the fact that there is not just a single way to look at what an argument is. As noted in a comment, you can always curry functions into a series of unary applications of higher-order functions. Although you might be tempted to try to redefine "arity" as the length of that sequence, you will soon find higher-order functions which have different sequence lengths depending on the values of their arguments. Also, in most programming languages (unlike SQL) the function being called is a full expression which does not need to be evaluated at compile-time, and since different functions have different argument counts, there is no good way to describe the arity of a function call unless you respecify the call to be the application of a list-of-arguments object to a callable object. That's often done, but it's a bit unsatisfying because (in most languages), the list object does not really exist and cannot be observed as an object.
I'd suggest taking the Wikipedia article on arity with a good-sized saline dosage, because it completely misses the distinction between semantics and syntactic structure, giving rise to the confusing ambiguity between the semantic and syntactic view of SQL's range operator or C's conditional operator. Personally, I prefer to reserve "arity" for the semantic meaning, using "fixity" or "valence" for the syntactic feature. (The advantage of "fixity" is that it encourages the distinction between prefix and postfix, which is a real distinction hidden by calling both cases "unary operators".)
Notes
BETWEEN...AND could short-circuit, too, but standard SQL doesn't guarantee short-circuiting, as far as I know (although some SQL implementations do.)

Syntax for comparison expression in Simple case expression in Oracle DB SQL

I am trying to make a parser for Oracle SQL select statement which include CASE statement
http://docs.oracle.com/cd/B19306_01/server.102/b14200/img/case_expression.gif
And the oracle reference listed that the simple case expression can be expressed in
http://docs.oracle.com/cd/B19306_01/server.102/b14200/img/simple_case_expression.gif
But i cannot find the comparison expression everywhere in the reference, does anyone have a clue where is it and how it looks like?
I believe it's the same as the condition defined here:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/conditions001.htm#SQLRF52101
which means it can be several kinds of things, requiring all of chapter 7 of the manual to explain them. And most of them in turn can include arbitrary expressions (that's all of chapter 6, plus chapter 5 for function calls) and even subqueries (so all of chapter 9 too). For eaxmple this is a "simple case statement" in action:
SELECT
CASE
WHEN (SELECT /* anything that can go in a select statement might be here */) > 0
THEN 'Y'
ELSE 'N'
END
FROM DUAL
And in the nested query you can have all kinds of hard-to-parse things. Basically if you want to parse a CASE expression the way Oracle would parse it, you're in trouble. There's no way to avoid the need to parse the rest of Oracle SQL.
If you limit yourself to standard SQL (and maybe ban subqueries) you have a better chance of finishing the project.
OK, first answer was exactly the opposite of the truth. comparison_expr is an expr that will be compared to the expr that comes right after the CASE.

Logical operators priority with NAND, NOR, XNOR

I've searched the web but I've found no solution to this problem.
What is the logical priority for operators NAND, NOR and XNOR?
I mean, considering as example the expression
A AND B NAND C
which operator should be evaluated first?
Obviously NAND can be translated as NOT-AND (as NOR is NOT-OR and XNOR is NOT-XOR), but
(A AND B) NAND C != A AND (B NAND C) = A AND NOT(B AND C)
According to my researches there's no a defined priority for such an expression, so I think the simplest solution is to evaluate the operators according to the order they appear in the expression, but I may be wrong.
Any suggestions?
This actually depends on your precedence rules. If there is no order (no precedence rules or everything of the same importance), it should be solved left to right. Here is an example with C++.
operator precedence have to be defined by a language, and what you have here doesn't seem to be a formal language, in such cases it's often assumed to be evaluated as you read from left to right.
Though, you could use the same operator precedence as verilog , or look at wikipedia which has a small table precedence commonly used for logic operators
If the expression is written like the way it is mentioned in the question(without brackets in between), it should be solved in the order they are written. Thats the only correct way to do this.
eg. If its written line A NOR B XOR C, It simply means (A NOR B) XOR C
Boolean operators have analogues in conventional arithmetic, so one way of deciding what the precedence rules should be is to follow the rules for conventional arithmetic, e.g. AND is analogous to multiplication, while OR is analogous to addition, hence AND should have higher precedence than OR. If you look at the operator precedence table for a language such as C or C++ you will see that this is indeed the case in these and other related languages.
I suppose this could be language specific, ALL operators must have an order of precedence defined or implied by a specific implmentation.
Here is what another site has to say about that.

SQL Parentheses use in an OR clause

Was wondering whether anyone would know why do we use the parentheses in this SQL:
So, the format goes as follows:
Name,location and department of the service of the employees whose name starts with A or B. (A rough translation from French).
I answered the following way:
SELECT service.nom_serv, localite.ville, localite.departemen
FROM service, localite, employe
WHERE service.code_loc=localite.code_loc
AND employe.service=service.code_serv
AND ((employe.nom LIKE 'A%') OR (employe.nom LIKE 'B%'))
Basically, where the last AND is concerned for the WHERE, couldn't I simply do without the parenthesis in order to have the SQL select for me employees with their name starting either with an A or a B? What difference does positioning a parenthesis in that way make? And ahy is there a double use of parentheses? Or is it to prioritize the OR in the last clause, since an AND is preceding it?
Take a look at the Operator Precedence in SQL Server (You've not specified that, but I'd imagine it's the same for all RDBMS). What this means is that ANDs (without parenthesis) are evaluated before1 bind more tightly than ORs.
So in your specific case, without the parenthesis, the conditions are:
employe.service=service.code_serv AND employe.nom LIKE 'A%'
OR
employe.nom LIKE 'B%'
1Evaluation order is deliberately not specified in SQL, allowing many more possible re-orderings that languages that guarantee left-to-right or precedence ordered evaluation.
You use it to specify grouping of the clause, not priority. SQL does not allow you to specify priority as the optimizer will create the best priority for you.
AND ()
Will take both of the OR conditions in one statement. So if either is true then the AND is true as well. The inner parentheses are not necessary, but help in visualizing the separation.
Without the outer parentheses it would allow anything with the final clause as true as well.
There are extra parenthesis. The rule in math is to add the parenthesis to clarify the logic. In this case if you remove all of the parenthesis you'll get the wrong answer. What you have is a AND ((b) OR (c)). Removing all of the parenthesis would take it from (a OR b) AND (a OR c) to (a AND b) OR c which is incorrect.