正文
postgres=# explain select name from product;
Seq Scan on product (cost=0.00..24.08 rows=1408 width=24)
postgres=# explain select /*+ indexonlyscan(product my_index) */ name from product;
Index Only Scan using my_index on product (cost=0.00..65.37 rows=1408 width=24)
执行计划是SQL优化的重要手段,在openGauss中不支持autotrace方式查看执行计划,实时的执行计划可以通过explain命令直接查看。与Oracle类似的是,openGauss支持通过explain plan命令将执行计划存入系统表中,不过与Oracle稍有区别,openGauss中会将执行计划存入PLAN_TABLE表。
postgres=# explain plan for select * from test;
EXPLAIN SUCCESS
postgres=# SELECT * FROM PLAN_TABLE;
statement_id | plan_id | id | operation | options | object_name | object_type | object_owner | projection
--------------+-----------------+----+--------------+----------+-------------+-------------+--------------+------------
| 281474976710867 | 1 | TABLE ACCESS | SEQ SCAN | test | TABLE | public | id
(1 row)
postgres=# explain select * from test;
Seq Scan on test (cost=0.00..34.02 rows=2402 width=4)
应用开发中,函数是必不可少的功能,经常会用到系统自带函数,常见的SQL函数主要有DECODE、时间函数、空函数、自定义函数等。
DECODE是Oracle公司独家提供的功能,它是一个功能很强的函数。它虽然不是SQL的标准,但对于性能非常有用。openGauss中也提供了DECODE的功能。
postg
res=# select DECODE(3, 1,'One', 2,'Two', 3,'Three', 'Not found');
decode
--------
Three
(1 row)
Oracle中提供了一系列时间函数,最常用的是SYSDATE及SYSTIMESTAMP,openGauss中支持SYSDATE,但SYSTIMESTAMP需要替代为LOCALTIMESTAMP。
postgres=# select sysdate;
sysdate
---------------------
2020-10-21 17:04:14
(1 row)
postgres=# select systimestamp from dual;
ERROR: column "systimestamp" does not exist
LINE 1: select systimestamp from dual;
CONTEXT: referenced column: systimestamp
postgres=# select localtimestamp from dual;
2020-11-02 09:39:22.382455
空值处理是实际中会经常遇到的情况,通常是通过NVL函数处理,NVL(E1, E2)的功能为:如果E1为NULL,则函数返回E2,否则返回E1本身。但此函数有一定局限,所以Oracle在NVL函数的功能上扩展,提供了NVL2函数。NVL2(E1, E2, E3)的功能为:如果E1为NULL,则函数返回E3,若E1不为NULL,则返回E2。openGauss当前版本只支持NVL函数,NVL2的功能可用DECODE进行替代。
postgres=# select NVL(9, 0) from dual;
nvl
-----
9
(1 row)
postgres=# select nvl2(100,1,2) from dual;
ERROR: function nvl2(integer, integer, integer) does not exist
LINE 1: select nvl2(100,1,2) from dual;
HINT: No function matches the given name and argument types. You might need to add explicit type casts.