Is there a way to reference an alias that has a space in it in an Oracle SQL Query? I haven't found it anywhere yet. Normally I don't use spaces for naming database elements, so this is new ground for me.
Here's an example query:
SELECT t.id AS "Ticket ID",
(SELECT w.workgroup_title FROM workgroups w
WHERE w.operator_id = t.operator_id AND ROWNUM < 2) AS "Workgroup Title"
FROM tickets t
How would I use "Ticket ID" or "Workgroup Title" in a future comparison operation? For example:
"Ticket ID" == 9 or "Workgroup Title" == 'Workgroup #1'
I'm guessing there's an easy way to do this, just haven't found it yet.
Thanks!
PS This is for a legacy piece that was handed to me. The aliases in the SQL tie dynamically into other various code, and all have spaces. As a result, removing the spaces isn't a simple matter and I currently haven't been budgeted the time for it. Otherwise, that's what I'd do.
Edit for Clarification
Using the example above, how would I do something like this where "Workgroup Title" always refers to the alias:
SELECT t.id AS "Ticket ID",
(SELECT w.workgroup_title FROM workgroups w
WHERE w.operator_id = t.operator_id AND ROWNUM < 2) AS "Workgroup Title",
(SELECT s.support_tier_id FROM support_tiers s
WHERE s.workgroup_title == "Workgroup Title") AS "Support Tier ID"
FROM tickets t
When using a self-join, it is important to use a logical SQL alias for each table. (Aliases are also useful for subqueries.
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.
If the alias_name contains spaces, you must enclose the alias_name in quotes. It is acceptable to use spaces when you are aliasing a column name. However, it is not generally good practice to use spaces when you are aliasing a table name.
The WHERE clause can contain non-correlated aliases and correlated aliases.
Yes, you can do this, but you have to enclose those names in double quotes:
-- SQL Example
SELECT "Just one" FROM (
SELECT 1 AS "Just one" FROM dual
);
Output:
Just one ---------- 1
-- PL/SQL Example
BEGIN
FOR v_rec IN (SELECT 1 AS "Just one" FROM dual)
LOOP
dbms_output.put_line(v_rec."Just one");
END LOOP;
END;
/
Output:
1
And a little curiosity:
BEGIN
FOR v_rec IN (SELECT COUNT(1) * 10 FROM dual)
LOOP
dbms_output.put_line(v_rec."COUNT(1)*10");
END LOOP;
END;
This works.. and prints:
10
Edit
You can reference the aliased column elsewhere in your query, for example:
SELECT 'It is just one' FROM (
SELECT "Just one" FROM (
SELECT 1 AS "Just one" FROM dual
) t
WHERE t."Just one" = 1 -- prefixing with t. is not necessary in this particular example
);
Output:
It is just one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With