Sub topic 1
Anatomy of a SELECT statement
A SELECT statement reads data and returns it as a result set, which has the same shape as a table: named columns and zero or more rows. This chapter covers the parts of a query, the rules for writing them, and the errors you will see most often. Later chapters cover each part in detail.
Prerequisites
This chapter assumes you have the following:
- You know what a relational table, a row and a column are.
- You can run SQL in an Oracle session through SQL*Plus, SQLcl, SQL Developer or SQL Worksheet.
- You know the basic data types: numbers, strings (
VARCHAR2) and dates. - You can log in to a schema that has the HR sample tables, such as
employeesanddepartments. The examples use them.
The shape of a query
The smallest useful query has two parts, a select list and a source:
SELECT employee_id, first_name, last_name
FROM employees;- The select list follows
SELECT. It says which columns or expressions to return. - The FROM clause names the row source, which is usually a table or view.
- The semicolon ends the statement in SQL*Plus, SQLcl and SQL Developer. It is a signal to the client tool. It is not part of the SQL sent to the database.
A fuller query adds optional clauses in a fixed order:
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;The order in which you write the clauses is fixed: SELECT, FROM, WHERE, ORDER BY, then FETCH FIRST. Oracle does not evaluate them in that order, a point the last chapters return to.
The select list
The select list is a comma-separated list. Each item is one of these:
- a column name, such as
last_name - an expression, such as
salary * 12 - a function call, such as
UPPER(last_name) - a literal, such as
'active'or42 *, which means all columns
Each item produces one column in the result, in the order you list them. The order in the table definition does not matter.
SELECT last_name, first_name, salary * 12 AS annual_salary
FROM employees;Expressions, aliases and functions have their own chapters. For now, notice that the select list is not limited to stored columns. It can compute new values for every row.
SELECT *
SELECT * returns every column in table-definition order:
SELECT * FROM departments;It is handy for exploring, but avoid it in application code:
- If someone adds or reorders columns, your program receives a different result.
- It fetches columns you may not need, including large
CLOBcolumns, which wastes network and memory. - It can hide which columns the code actually depends on.
You can combine * with other items only if you qualify it with a table name or alias:
SELECT e.*, e.salary * 12 AS annual_salary
FROM employees e;Here e is a table alias. It is a short name for the table within this statement. Writing employees e with no AS keyword is correct. Oracle does not accept AS before a table alias, though it allows AS before a column alias.
The FROM clause
FROM names where the rows come from. The source can be:
- a table or view
- a table in another schema, written
schema.table - an inline view, which is a subquery in parentheses
- a join of several sources
dual, a special one-row table covered in the next chapter
Without a schema prefix, Oracle looks for the name in your own schema and then through synonyms. To read the HR tables from another account, qualify them:
SELECT department_id, department_name
FROM hr.departments;This works only if your account has SELECT privilege on that table.
Writing rules
Case and whitespace
Keywords, table names and column names are not case sensitive when unquoted. Oracle converts unquoted identifiers to uppercase internally. These three queries are the same:
select last_name from employees;
SELECT LAST_NAME FROM EMPLOYEES;
Select Last_Name From Employees;Whitespace and line breaks are free. Put each clause on its own line, because it makes errors easier to find.
String literals are different. Text inside single quotes is case sensitive, so 'King' and 'KING' are different values. Likewise, a double-quoted identifier such as "Last_Name" keeps its exact case. It must then be written with the same case and the quotes every time. Avoid quoted identifiers in your own table design.
Quotes
Oracle uses two kinds of quotes, and they are not interchangeable:
| Syntax | Meaning | Example |
|---|---|---|
| `'text'` | String literal | `WHERE last_name = 'King'` |
| `"Name"` | Quoted identifier | `SELECT salary AS "Monthly Pay"` |
To put an apostrophe inside a string literal, double it:
SELECT 'O''Brien' AS surname FROM dual;Comments
Comments are ignored by the database. Use -- for the rest of a line and /* ... */ for a block:
SELECT employee_id, -- primary key
last_name /* family name */
FROM employees;Identifier limits
Names of tables and columns can be up to 128 bytes from Oracle Database 12.2 onward. Earlier releases allow 30 bytes. Unquoted names must start with a letter and may contain letters, digits, _, $ and #. Reserved words such as SELECT, ORDER or DATE cannot be used as unquoted names.
Row order and the result set
A result set has no guaranteed order unless the query has an ORDER BY. A query may return rows in insertion order today and a different order after a table reorganization, an index change or a parallel plan. Never rely on the order you happen to see.
A result set is also not stored anywhere. Oracle builds it as the client fetches rows. Tools such as SQL Developer fetch in batches (50 rows by default in the grid), which is why a large query appears quickly: the tool has only asked for the first batch.
Finding the column names
Before you write a select list, check what columns a table has. In SQL*Plus, SQLcl and SQL Developer, use DESCRIBE:
DESCRIBE employeesDESCRIBE is a client command, so it takes no semicolon and works only in those tools. To get the same information with plain SQL, query the data dictionary:
SELECT column_name, data_type, nullable
FROM user_tab_columns
WHERE table_name = 'EMPLOYEES'
ORDER BY column_id;user_tab_columns lists the columns of tables you own. Note the uppercase 'EMPLOYEES'. The dictionary stores unquoted names in uppercase, and a string literal comparison is case sensitive.
Common errors
Most beginner errors come from a small set of mistakes. Learn to read the error code first, then the message.
| Error | Typical cause | Example |
|---|---|---|
| ORA-00942: table or view does not exist | Misspelled name, wrong schema, or missing privilege | `SELECT * FROM employes;` |
| ORA-00904: invalid identifier | Column name does not exist or is misspelled | `SELECT lastname FROM employees;` |
| ORA-00923: FROM keyword not found where expected | `FROM` is missing, or an unquoted alias contains a space | `SELECT 1 + 1 AS two;` before 23ai |
| ORA-00936: missing expression | A stray comma in the select list | `SELECT last_name, FROM employees;` |
| ORA-00933: SQL command not properly ended | Extra text after the statement, or clauses in the wrong order | `SELECT last_name FROM employees ORDER BY last_name WHERE 1 = 1;` |
ORA-00942 deserves a note. Oracle gives the same message when a table does not exist and when it exists but you have no privilege on it. This hides the existence of objects from users who should not know about them.
The missing comma
A missing comma does not always raise an error. Consider this query:
SELECT first_name last_name
FROM employees;Oracle reads last_name as an alias for first_name. The query succeeds and returns one column, headed LAST_NAME, that contains first names. When a result has fewer columns than you listed, look for a missing comma.
The role of DUAL
In Oracle releases before 23ai, every SELECT needs a FROM clause, even when you want to evaluate something that involves no table. Oracle provides dual for this purpose. It is a table owned by SYS with one row and one column, and any user can read it:
SELECT 'Hello, Oracle' AS greeting FROM dual;The next chapter explains why dual exists and what it holds. Oracle Database 23ai relaxes the rule and accepts SELECT 1 + 1 AS two; with no FROM at all. Because most databases in production run earlier releases, you should still know how to write FROM dual.
Practical habits
- Write one clause per line and one select-list item per line in longer queries.
- List the columns you need instead of using
*in anything saved or shared. - Start with a small query, check it, and then add clauses one at a time.
- Use table aliases once a query has more than one table, and prefix columns with them.
- Read the error code and the position marker Oracle shows under the failing text. It usually points at, or just after, the actual mistake.
Exercise
A colleague runs SELECT employee_id last_name, salary FROM employees; and says the result has two columns, "LAST_NAME" and "SALARY", yet the first column contains numbers. What went wrong, and how do you fix the query?
Show answer
The comma after employeeid is missing, so Oracle treats lastname as an alias for employeeid. That is why the first column is headed LASTNAME but holds employee IDs. The fixed query is: SELECT employeeid, lastname, salary FROM employees;
Exercise
You run SELECT * FROM Employees WHERE last_name = 'king'; on the HR schema and get no rows, although an employee named King exists. Which part of the query is responsible, and why does the table name not cause a problem?
Show answer
The string literal 'king' is case sensitive and does not match 'King'. The table name Employees is an unquoted identifier, so Oracle converts it to uppercase and finds EMPLOYEES. Use 'King' to match, or compare UPPER(last_name) = 'KING'.
Exercise
On Oracle Database 19c you run SELECT 2 * 3 AS product;. Which error do you get, what is the smallest change that fixes it, and which release accepts the original statement?
Show answer
You get ORA-00923: FROM keyword not found where expected. Add FROM dual: SELECT 2 * 3 AS product FROM dual; Oracle Database 23ai accepts the original statement without a FROM clause.