Oracle 中是否需要“AS”关键字来为 SELECT 语句中的列定义别名?
我注意到
SELECT column_name AS "alias"
是相同的
SELECT column_name "alias"
我想知道以后一种方式定义列别名的后果是什么。
根据 select_list Oracle 选择文档,AS 是可选的。
作为个人笔记,我认为使用 AS 更容易阅读
(测试于Oracle 11g
)
关于AS
:
AS
是可选的。AS
不应添加,否则会出错。关于double quote
:
例如
-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;
-- 'AS' shouldn't be used for table name
select 'hi' from dual d;
-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;
select 'hi' from dual "d";
SELECT employee_id,department_id AS department
FROM employees
order by department
SELECT employee_id,department_id AS "department"
FROM employees
order by department
--oracle错误--
如果您使用 ORDER BY 子句,那么最好使用不带双引号的 AS
两者都是正确的。Oracle 允许同时使用两者。
我的结论是(在12c上测试):
因此 :
SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect
SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias
所以,使用 AS AND "" 导致问题的原因不是 AS
注意:如果别名包含空格或如果它包含小写字符并且必须在结果集中显示为小写字符,则需要 "" 双引号。在所有其他情况下,它是可选的,可以忽略。
当我们在别名中有空格时需要引号,例如
SELECT employee_id,department_id AS "Department ID"
FROM employees
order by department
两者之间没有区别,AS
只是一种更明确的提及别名的方式,这很好,因为一些依赖库依赖于这个小关键字。例如JDBC 4.0。根据使用情况,可以观察到不同的行为。
看到这个。我总是建议使用完整的语义形式来避免此类问题。