Oracle兼容-语法-Oracle ORDER BY兼容


在GreatSQL中,切换到ORACLE模式后,即可支持Oracle风格的排序规则。

1. 语法

  1. ORDER BY order_expr [, order_expr...]
  2. order_expr :
  3. expr [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]

2. Oracle兼容说明

GreatSQL 和 Oracle 在 ORDER BY 排序时,对于 NULL 值的排序处理方式存在差异。

GreatSQL的做法:

  • ASC 排序时,NULL 排序在前;
  • DESC 排序时,NULL 排序在后。

Oracle的做法与GreatSQL相反,即:

  • ASC 排序时,NULL 排序在后;
  • DESC 排序时,NULL 排序在前。

可以设置 SET sql_mode = ORACLE 切换到ORACLE模式,选择使用Oracle的排序模式。

在ORACLE模式下,还可以在排序时加上 NULLS FIRST 显式设置在最终结果中将 NULL 排序在最前面。 也可以加上 NULLS LAST 显式设置在最终结果中将 NULL 排序在最后面。

3. 示例

  1. greatsql> SET sql_mode = DEFAULT;
  2. greatsql> CREATE TABLE t1 (id INT, desc1 VARCHAR(2), desc2 VARCHAR(2));
  3. greatsql> INSERT INTO t1 VALUES (1, NULL, 'A'), (2, 'B', 'B'), (3, 'C', 'C'), (4, 'D', 'D');
  4. greatsql> SELECT * FROM t1;
  5. +------+-------+-------+
  6. | id | desc1 | desc2 |
  7. +------+-------+-------+
  8. | 1 | NULL | A |
  9. | 2 | B | B |
  10. | 3 | C | C |
  11. | 4 | D | D |
  12. +------+-------+-------+
  13. greatsql> SELECT * FROM t1 ORDER BY desc1;
  14. +------+-------+-------+
  15. | id | desc1 | desc2 |
  16. +------+-------+-------+
  17. | 1 | NULL | A |
  18. | 2 | B | B |
  19. | 3 | C | C |
  20. | 4 | D | D |
  21. +------+-------+-------+
  22. greatsql> SELECT * FROM t1 ORDER BY desc1 DESC;
  23. +------+-------+-------+
  24. | id | desc1 | desc2 |
  25. +------+-------+-------+
  26. | 4 | D | D |
  27. | 3 | C | C |
  28. | 2 | B | B |
  29. | 1 | NULL | A |
  30. +------+-------+-------+
  31. greatsql> SELECT * FROM t1 ORDER BY desc1 NULLS FIRST;
  32. +------+-------+-------+
  33. | id | desc1 | desc2 |
  34. +------+-------+-------+
  35. | 1 | NULL | A |
  36. | 2 | B | B |
  37. | 3 | C | C |
  38. | 4 | D | D |
  39. +------+-------+-------+
  40. greatsql> SELECT * FROM t1 ORDER BY desc1 NULLS LAST;
  41. +--------+-------+-------+
  42. | id | desc1 | desc2 |
  43. +--------+-------+-------+
  44. | 2 | B | B |
  45. | 3 | C | C |
  46. | 4 | D | D |
  47. | 1 | NULL | A |
  48. +--------+-------+-------+
  49. greatsql> SELECT * FROM t1 ORDER BY desc1 DESC NULLS FIRST;
  50. +------+-------+-------+
  51. | id | desc1 | desc2 |
  52. +------+-------+-------+
  53. | 1 | NULL | A |
  54. | 4 | D | D |
  55. | 3 | C | C |
  56. | 2 | B | B |
  57. +------+-------+-------+
  58. greatsql> SELECT * FROM t1 ORDER BY desc1 DESC NULLS LAST;
  59. +------+-------+-------+
  60. | id | desc1 | desc2 |
  61. +------+-------+-------+
  62. | 4 | D | D |
  63. | 3 | C | C |
  64. | 2 | B | B |
  65. | 1 | NULL | A |
  66. +------+-------+-------+

问题反馈

联系我们

扫码关注微信公众号

greatsql-wx