The DML component of SQL is the part that is used to query and update the tables (once they are built via DDL commands or other means). By far, the most commonly used DML statement is the SELECT. It combines a range of functionality into one complex command.
Used primarily to retrieve data from the database. Also used to create copies of tables, create views, and to specify rows for updating.
General Format: Generic overview applicable to most commercial SQL implementations – lots of potential combinations. There are several variations available in Oracle.
SELECT {field-list | * | ALL | DISTINCT | expression}
FROM table-list
WHERE expression
GROUP BY group-fields
HAVING group-expression
ORDER BY field-list;
Only the SELECT and the FROM clauses are required. The others are optional.
FROM
A required clause that lists the tables that the select works on. You can define “alias” names with this clause to speed up query input and to allow recursive “self-joins”.
WHERE
An optional clause that selects rows that meet the stated condition. A “sub-select” can appear as the expression of a where clause. This is called a “nested select”.
GROUP BY
An optional clause that groups rows according to the values in one or more columns and sorts the results in ascending order (unless otherwise specified). The duplicate rows are not eliminated, rather they are consolidated into one row. This is similar to a control break in traditional programming.
HAVING
An optional clause that is used with GROUP BY. It selects from the rows that result from applying the GROUP BY clause. This works the same as the WHERE clause, except that it only applies to the output of GROUP BY.
ORDER BY
An optional clause that sorts the final result of the SELECT into either ascending or descending order on one or more named columns.
There can be complex interaction between the WHERE, GROUP BY, and HAVING clauses. When all three are present the WHERE is done first, the GROUP BY is done second, and the HAVING is done last.
Example 1: Select all employees from the ‘ACCT’ department.
SELECT * FROM EMPLOYEES WHERE EMP-DEPT = ‘ACCT’;
Example 2: Show what salary would be if each employee recieved a 10% raise.
SELECT LNAME, SALARY AS CURRENT, SALARY * 1.1 AS PROPOSED FROM EMPLOYEES;