I have a MySQL table with two columns, row1 and row2, and theese columns together increased.
+------+------+
| row1 | row2 |
+------+------+
| 10 | 100 |
| 11 | 110 |
| 20 | 200 |
| 21 | 210 |
+------+------+
But sometimes an error occured, wrong values inserted:
+------+------+
| row1 | row2 |
+------+------+
| 10 | 100 |
| 11 | 110 |
| 20 | 105 |
| 21 | 210 |
+------+------+
The row1 = 20, row2 = 105 is "wrong", because the previous row1 is 11, and the corresponding row2 is 110, which is larger than 105.
How can I list theese "wrong" rows?
2
Answers
On MySQL 8+, we can use the
LAG()
window function to detect breaks in therow2
sequence as ordered byrow1
:The computed
flag
column generated by the above query would containERROR
for any record which is breaking sequence.Use a self-join query to compare each row with its previous row and check if the value in the rrow2 would be less than the value of the row2 from the previous row,
on the above query, the table gets joined with itself by using column row1 as a join condition, and the t1 table would represent the current row, whereas the t2 represents the previous row. By using
WHERE
we filter the results and we get only the rows where the value of rrow2 of the current row is less than row2 of the previous row values,I hope it helps!