Sub topic 1
Anatomy of a SELECT Statement
Prerequisites
This chapter assumes that you understand tables, rows and columns, and that you can connect to an Oracle Database session through SQL*Plus, SQL Developer or a SQL Worksheet. You should also be comfortable with numbers, strings and dates. The examples use the HR sample schema, but the DUAL examples need no schema at all.
Anatomy of a SELECT statement
A SELECT statement asks the database to return data. Its basic form has two required clauses:
SELECT column_list
FROM table_name;The SELECT clause lists the columns or expressions to return. The FROM clause names the source table. Oracle evaluates each row of the source table and returns one output column for each item in the list.
What DUAL is and why Oracle has it
DUAL is a built-in table that every user can read. It has one column, DUMMY, of type VARCHAR2(1), and one row containing the value 'X'. Oracle provides it because most releases require a FROM clause in every SELECT, even when no table holds the data you want. Selecting from DUAL gives you exactly one row to work with.
SELECT * FROM dual;Choosing columns and naming them with aliases
You choose output columns by listing them. An alias gives an output column a different heading. Add AS followed by the name, or leave out AS and write the name after a space.
SELECT employee_id,
last_name AS surname,
salary * 12 AS annual_salary
FROM employees;Wrap an alias in double quotes when it contains spaces or must keep its case, for example AS "Annual Salary".
Literals, arithmetic and string concatenation
A literal is a fixed value written directly in the query. Text literals use single quotes. Numbers need no quotes. You can combine values with arithmetic operators such as +, -, * and /. The || operator joins strings.
SELECT 'Hello, Oracle' AS greeting,
2 + 3 AS total,
'Ora' || 'cle' AS joined_text
FROM dual;> Note: Double quotes name identifiers, and single quotes write text values. Mixing them up is a common error.
Exercise
What does this query return, and what is the column heading? SELECT 10 - 4 AS difference FROM dual;
Show answer
It returns one row with the value 6 in a column headed DIFFERENCE.