apendix b sql
DESCRIPTION
Oracle Academy - Basic SQL StatementsTRANSCRIPT
-
Appendix BSQL PrimerSQL Primer
1 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Overview
This lesson covers the following topics: Describe the syntax of basic SQL-92/1999 commands,
including:including: SELECT INSERT UPDATE DELETE
CREATE TABLE CREATE TABLE DROP TABLE
Define basic SQL-92/1999 data types.
2 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
yp
-
SQL Primer
Accessing Relational Databases
In a relational database, you do not specify the access route to the tables, and you do not need to know how the data is arranged physically.data is arranged physically.
To access the database, you execute a structured query y q ylanguage (SQL) statement, which is the American National Standards Institute (ANSI) standard language for operating relational databasesoperating relational databases.
3 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
What is SQL?
SQL is a set of statements with which all programs and users access data in an Oracle Database.
Application programs and Oracle tools often allow users access to the database without using SQL directly, but g ythese applications, in turn, must use SQL when executing the users request.
4 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
SQL Statements Used to Execute Tasks
SQL provides statements for a variety of tasks, including: Querying data.
I ti d ti d d l ti i t bl Inserting, updating, and deleting rows in a table. Creating, replacing, altering, and dropping objects. Controlling access to the database and its objects Controlling access to the database and its objects. Guaranteeing database consistency and integrity.
SQL unifies all of the preceding tasks in one consistent language and enables you to work with data at a logical
5 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
level.
-
SQL Primer
SQL Complies with Industry Standards
SQL statements supported by Oracle comply with industry standards. Oracle Corporation ensures future compliance with Oracle Corporation ensures future compliance with
evolving standards by actively involving key personnel in SQL standards committees. The industry-accepted committees are ANSI and
International Standards Organization (ISO). Both ANSI and ISO have accepted SQL as the standard p Q
language for relational databases.
6 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Using SQL to Query Your Database
Structured query language (SQL) is: The ANSI standard language for operating relational
databasesdatabases. Efficient, easy to learn, and use. Functionally complete (with SQL you can defineFunctionally complete (with SQL, you can define,
retrieve, and manipulate data in the tables).
SELECT department name
Database
S C depa t e t a eFROM departments;
7 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
SQL Statements: DML
Data Manipulation Language (DML):Statement DescriptionSELECT R t i d t f th d t bSELECT Retrieves data from the database.
INSERT Enters new rows.
UPDATE Changes existing rows.
DELETE MERGE Removes unwanted rows from tables in the databaseDELETE MERGE Removes unwanted rows from tables in the database.
8 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
SQL Statements: DDL
Data Definition Language (DDL):Statement DescriptionCREATECREATE
ALTER
Sets up, changes, and removes data structures from tables.DROP
RENAME
TRUNCATE
COMMENT
9 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
SQL Statements: DCL
Data Control Language (DCL):Statement Description
P id i ht t b th th O l D t bGRANT Provides access rights to both the Oracle Database and the structures within it.
REVOKE Removes access rights to both the Oracle Database and the structures within it.
10 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
SQL Statements: Transaction Control
Transaction control: Statement DescriptionCOMMITCOMMITROLLBACKSAVEPOINT
Manages the changes made by DML statements. Changes to the data can be grouped together into logical transactions.
11 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Basic SELECT Statement
A SELECT statement must include the following: A SELECT clause, which specifies the columns to be
displayeddisplayed. A FROM clause, which identifies the table containing the
columns that are listed in the SELECT clause.
SELECT *|{[DISTINCT] column|expression [alias],...}FROM table;
12 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Basic SELECT Statement Syntax
Syntax Description
SELECT A list of one or more columns.
* Selects all col mns* Selects all columns.
DISTINCT Suppresses duplicates.
column | expression Selects the named column or the expression.
alias Gives the selected columns different headingsalias Gives the selected columns different headings.
FROM table Specifies the table containing the columns.
13 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Basic SELECT Statement Vocabulary Terms
Vocabulary Term Description
Keyword Refers to an individual SQL element. For example, SELECT and FROM are keywords.
A part of a SQL statement For e ample SELECTClause A part of a SQL statement. For example, SELECT employee_id, last_name, and so on.
Statement A combination of two or more clauses. For example, SELECT * FROM employees.
14 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Limiting the Rows That Are Selected
You can restrict the rows that are returned from the query by using the WHERE clause.
A WHERE clause contains a condition that must be met and it directly follows the FROM clause. If the condition is true, the row meeting the condition is returned.
WHERE clause: SELECT *|{[DISTINCT] column|expression [alias],...}|{[ ] | p [ ], }FROM table[WHERE condition(s)];
15 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
WHERE Clause Syntax
Syntax Description Restricts the query to rows that meet a condition.
WHERE Follows the FROM clause.
Can compare values in columns, literal, arithmetic expressions, or functions.
Consists of three elements: column name, comparison condition, and column name, constant, or list of values.column name, constant, or list of values.
condition
Iscomposedofcolumnnames,expressions,constants,andacomparisonoperator.
Specifiesacombinationofoneormoreexpressionsandlogical(boolean)operatorsoperators.
ReturnsavalueofTRUE,FALSE,orUNKNOWN.
16 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
ORDER BY Clause
The order of rows that are returned in a query result is undefined. The ORDER BY clause can be used to sort the rows. If you use the ORDER BY clause:rows. If you use the ORDER BY clause: It must be the last clause of the SQL statement. You can specify an expression, an alias, or a column p y p
position as the sort condition.SELECT last_name, job_id, department_id, hire_dateFROM employeesp yORDER BY hire_date ;
17 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
ORDER BY Clause Syntax
Title Title
S ifi th d i hi h th t i dORDER BY Specifies the order in which the retrieved rows are displayed.
Orders the rows in ascending order (this is the defaultASC Orders the rows in ascending order (this is the default order).
DESC Orders the rows in descending order.
18 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Using the ORDER BY Clause
Use the ORDER BY clause to display the rows in a specific order. If the ORDER BY clause is not used: The sort order is undefined The sort order is undefined. The Oracle server may not fetch rows in the same
order for the same query twiceorder for the same query twice.
Use the keywords NULLS FIRST or NULLS LAST to yspecify whether returned rows containing null values should appears first or last in the ordering sequence.
19 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Using the ORDER BY Clause Syntax
The ORDER BY clause syntax is as follows:
SELECT exprFROM tableFROM table[WHERE condition(s)][ORDER BY {column, expr, numeric_position} [ASC|DESC] ];
20 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
INSERT Statement
You can add new rows to a table by issuing the INSERT statement. The statement with the VALUES clause adds only one row at a time to a table.only one row at a time to a table.
INSERT INTO table [(column [, column...])]VALUES (value [, value...]);
21 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
INSERT Statement Syntax
Syntax Description
table Name of the table.
column Name of the column in the table to populate.p p
value Corresponding value for the column.
22 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
UPDATE Statement
You can modify the existing values in a table by using the UPDATE statement. You can update more than one row at a time (if required).a time (if required).UPDATE tableSET column = value [, column = value, ...][WHERE condition];
23 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
UPDATE Statement Syntax
Syntax Description
table Name of the table.
column Name of the column in the table to populate.p p
value Corresponding value or subquery for the column.
conditionIdentifies the rows to be updated and is comprised of column names, expressions, constants, subqueries, and comparison operators.
24 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Using the UPDATE Statement
To confirm the update operation, query the table to display the updated rows.
In general, use the primary key column in the WHERE clause to identify a single row for update. Using other y g p gcolumns can unexpectedly cause several rows to be updated.
For example identifying a single row in the For example, identifying a single row in the EMPLOYEES table by name is dangerous, because more than one employee may have the same name.
25 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
DELETE Statement
You can remove existing rows from a table by using the DELETE statement.
DELETE [FROM] table [WHERE condition];
26 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
DELETE Statement Syntax
Syntax Description
table Name of the table.
conditionIdentifies the row to be deleted and is composed of column names, expressions, constants, subqueries, and , p , , q ,comparison operators.
value Corresponding value or subquery for the column.
27 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
CREATE TABLE Statement
When executed, the SQL CREATE TABLE statement creates tables to store data. Is a DDL statement that is a subset of the SQL Is a DDL statement that is a subset of the SQL
statements used to create, modify, or remove Oracle database structures.
Has an immediate effect on the database. Records information in the data dictionary.
CREATE TABLE [schema.]table(column datatype [DEFAULT expr][, ...]);
28 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Creating a Table
To create a table, a user must have: The CREATE TABLE privilege.
A t i hi h t t bj t A storage area in which to create objects.The database administrator (DBA) uses data control language (DCL) statements to grant privileges to users Tolanguage (DCL) statements to grant privileges to users. To create a table, you specify: Table name Column name, column data type, and column size
CREATE TABLE [schema.]table
29 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
(column datatype [DEFAULT expr][, ...]);
-
SQL Primer
CREATE TABLE Statement Syntax
Syntax Description
schema Same as the owner's nameschema Same as the owner s name.
table Name of the table.
Specifies a default value if a value is omitted in theDEFAULT expr Specifies a default value if a value is omitted in the INSERT statement.
column Name of the column.
datatype Column's data type and length.
30 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Defining Constraints
Constraints are created at the column or table level. Column-level constraints are included when column is
defineddefined. Table level constraints are defined at the end of the table
definition and must refer to the column or columns on which the constraint pertains in a set of parentheses.
NOT NULL constraints must be defined at the column levellevel.
31 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Defining Constraints
Constraints that apply to more than one column must be defined at the table level.
The difference between the two is mostly syntax The difference between the two is mostly syntax (functionally, they are the same).
32 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Defining Constraints Syntax
Syntax: CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
Column level constraint syntax:
( yp [ p ][column_constraint],...
[table_constraint][,...]);
Column-level constraint syntax:
column [CONSTRAINT constraint_name] constraint_type,
Table-level constraint syntax: column,...
33 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
,
[CONSTRAINT constraint_name] constraint_type(column, ...),
-
SQL Primer
Defining Constraints Syntax
Syntax Description
schema Same as the owner's name.schema Same as the owner s name.
table Name of the table.
DEFAULT expr Specifies a default value if a value is omitted in the DEFAULT expr INSERT statement.
column Name of the column.
datatype Column's data type and lengthdatatype Column's data type and length.
column_constraint An integrity constraint as part of the column definition.
t bl t i t A i t it t i t t f th t bl d fi iti
34 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
table_constraint An integrity constraint as part of the table definition.
-
SQL Primer
Constraints
Constraints: Are usually created at the same time as the table.
C b dd d t t bl ft it ti Can be added to a table after its creation. Can also be temporarily disabled.
35 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Column-Level Constraint Example
The following examples create a primary key constraint on the EMPLOYEE_ID column of the EMPLOYEES table.
Column-level constraint example:
CREATE TABLE employees( employee_id NUMBER(6)CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),...);...);
36 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Table-Level Constraint Example
The following examples create a primary key constraint on the EMPLOYEE_ID column of the EMPLOYEES table.
Table-level constraint example:
CREATE TABLE employees( employee_id NUMBER(6),first_name VARCHAR2(20),...
job id VARCHAR2(10) NOT NULL,job d C ( 0) O U ,CONSTRAINT emp_emp_id_pkPRIMARY KEY (EMPLOYEE_ID));
37 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Including Constraints
The Oracle server uses constraints to prevent invalid data entry into tables.
Use constraints to do the following: Enforce rules on the data in a table whenever a row isEnforce rules on the data in a table whenever a row is
inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to proceed.
Prevent the deletion of a table if there are dependencies from other tables.
Provide rules for Oracle tools such as Oracle
38 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
Provide rules for Oracle tools, such as Oracle Developer.
-
SQL Primer
Valid Constraint Types
The following constraint types are valid: NOT NULL
UNIQUE UNIQUE PRIMARY KEY FOREIGN KEY FOREIGN KEY CHECK
39 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Data Integrity Constraints
Constraint Description
NOT NULL Specifies that the column cannot contain a null valueNOT NULL Specifies that the column cannot contain a null value.
UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table.
PRIMARY KEY Uniquely identifies each row of the table.
FOREIGN KEYEstablishes and enforces a referential integrity between the column and a column of the referenced table such that valuesFOREIGN KEY column and a column of the referenced table such that values in one table match values in another table.
CHECK Specifies a condition that must be true.
40 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Data Types
When you identify a column for a table, you need to provide a data type for the column. There are several data types available:types available:
Data Type Description
VARCHAR2(size) Variable-length character data (A maximum size must be VARCHAR2(size) specified: minimum size is 1; maximum size is 4,000.)
CHAR(size) Fixed-length character data of length size bytes (Default and minimum size is 1; maximum size is 2,000.)
V i bl l th i d t N b h i i i d
NUMBER(p,s)
Variable-length numeric data - Number having precision p and scale s (Precision is the total number of decimal digits and scale is the number of digits to the right of the decimal point; precision can range from 1 to 38, and scale can range from 84 to 127 )
41 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
84 to 127.)
-
SQL Primer
More Data Types
Data Type Description
DATE Date and time values to the nearest second between January 1, 4712 B.C., and December 31, 9999 A.D.
O GLONGVariable-length character data (up to 2 GB).
CLOB Character data (up to 4 GB).
RAW (size) Raw binary data of length size (A maximum size must be specified: maximum size is 2,000).
LONG RAW Raw binary data of variable length (up to 2 GB).
BLOB Binary data (up to 4 GB).
BFILE Binary data stored in an external file (up to 4 GB).
42 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
ROWID A base-64 number system representing the unique address of a row in its table.
-
SQL Primer
Data Type Guidelines
Guidelines: A LONG column is not copied when a table is created
using a subqueryusing a subquery. A LONG column cannot be included in a GROUP BY or
an ORDER BY clause. Only one LONG column can be used per table. No constraints can be defined on a LONG column. You might want to use a CLOB column rather than a
LONG column.
43 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Dropping a Table
To drop a table, use the DROP TABLE statement. This statement:
Moves a table to the recycle bin or removes the table and Moves a table to the recycle bin or removes the table and all its data from the database entirely.
Invalidates the dependent objects and removes object privileges on the table.
DROP TABLE dept80;
DROP TABLE dept80 succeededDROP TABLE dept80 succeeded.
44 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Guidelines for Dropping a Table
Guidelines: All data is deleted from the table.
A i d i b t i lid Any views and synonyms remain, but are invalid. Any pending transactions are committed. Only the creator of a table or a user with the DROP ANY Only the creator of a table or a user with the DROP ANY
TABLE privilege can remove a table.
45 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Using the DROP TABLE Statement
Notes for use: Unless you specify the PURGE clause, the DROP
TABLE statement does not result in space beingTABLE statement does not result in space being released back to the tablespace for use by other objects, and the space continues to count toward the users space quota.
When you drop a table, the database loses all the data in the table and all the indexes associated with itin the table and all the indexes associated with it.
46 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Terminology
Key terms used in this lesson included: Clause
C t i t Constraints Create Table Statement Data Control Language (DCL) Data Control Language (DCL) Data Definition Language (DML) Data Manipulation Language (DML)Data Manipulation Language (DML) Data Types Delete Statement
47 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Terminology
Key terms used in this lesson included: Drop Table Statement
I t St t t Insert Statement Keyword Order By Clause Order By Clause Statement Select StatementSelect Statement Structured query language (SQL) Transaction Control
48 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Terminology
Key terms used in this lesson included: Update Statement
Wh Cl Where Clause
49 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
-
SQL Primer
Summary
In this lesson, you should have learned how to: Describe the syntax of basic SQL-92/1999 commands,
including:including: SELECT INSERT UPDATE DELETE
CREATE TABLE CREATE TABLE DROP TABLE
Define basic SQL-92/1999 data types.
50 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
yp