TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

A bug in MySQL, or working as intended? You decide

5 pointsby julesnpover 1 year ago

1 comment

dossyover 1 year ago
&gt; What? b is 2? It should be 4. Or produce an error, or something. But not 2. There&#x27;s no universe in which that result could be considered correct, it&#x27;s just wrong.<p>It is correct, and what I would expect based on the behavior in MySQL documentation.<p><a href="https:&#x2F;&#x2F;dev.mysql.com&#x2F;doc&#x2F;refman&#x2F;8.0&#x2F;en&#x2F;insert.html" rel="nofollow noreferrer">https:&#x2F;&#x2F;dev.mysql.com&#x2F;doc&#x2F;refman&#x2F;8.0&#x2F;en&#x2F;insert.html</a><p>&quot;An expression expr can refer to any column that was set earlier in a value list.&quot;<p>As the columns are evaluated in left-to-right order, &quot;earlier&quot; in this context means &quot;to the left of&quot;.<p>Therefore:<p><pre><code> INSERT INTO t1 (b,a) values (DEFAULT, 3); </code></pre> At the time `b` is being evaluated, `a` is to the right of it, so the current value of `a` is its own default value, which is `1`. So, `a+1` will evaluate to `1+1` or `2`.<p>This is not a bug, this is the documented and expected behavior.<p>To try and illustrate more clearly, try this:<p><pre><code> CREATE TABLE t1 (a int default 11, b int default 22, c int default (a+b+33)); </code></pre> To start simply:<p><pre><code> INSERT INTO t1 (a, b, c) VALUES (DEFAULT, DEFAULT, DEFAULT); </code></pre> This gives us:<p><pre><code> SELECT * FROM t1; +------+------+------+ | a | b | c | +------+------+------+ | 11 | 22 | 66 | +------+------+------+ </code></pre> No surprises.<p>Next:<p><pre><code> DELETE FROM t1; INSERT INTO t1 (a, b, c) VALUES (44, 55, DEFAULT); SELECT * FROM t1; +------+------+------+ | a | b | c | +------+------+------+ | 44 | 55 | 132 | +------+------+------+ </code></pre> Again, no surprises. Now, let&#x27;s reorder things a bit:<p><pre><code> DELETE FROM t1; INSERT INTO t1 (b, c, a) VALUES (87, DEFAULT, 65); </code></pre> Knowing that we&#x27;re evaluating this left-to-right, and `a`, `b` and `c` start out set to their default values as defined in the table schema, what do we expect? &lt;a=65, b=87, c=??&gt;<p>At the time `c` is being computed though, what is the value of `a`? Is it `65`, or `11`? We would expect it to be equal to `11`, as we haven&#x27;t evaluated the value of `a` in the INSERT statement, yet.<p>Therefore, we expect `c = 11 + 87 + 33 = 131` and NOT `c = 65 + 87 + 33 = 185`.<p><pre><code> SELECT * FROM t1; +------+------+------+ | a | b | c | +------+------+------+ | 65 | 87 | 131 | +------+------+------+ </code></pre> And, sure enough, there it is.<p>This is well-defined and expected behavior. Sorry, not a bug.
评论 #37888890 未加载