Oracle 2 SQL
Oracle 2 SQL
Lecture 2
SQL language
Types of SQL statements
• DDL (Data Definition Language) : create,
drop, alter, for example: CREATE TABLE
• DML (Data Modification Language):
select, update, delete, insert
• Transaction control statements: commit,
rollback, savepoint
• Session control statements: alter session
• System control statements: alter system
DML Statements: SELECT
• SELECT
– query data,
– does not modify tables
– does not lock (unless FOR UPDATE)
SELECT * FROM users
WHERE id = 1 FOR UPDATE
– does not wait for any locks (unless FOR
UPDATE)
DML Statements: UPDATE
• UPDATE
– update data in one table (any number of rows)
– locks updated data (until transaction end)
– waits for locks if data is locked (can cause
deadlock)
– syntax:
UPDATE table
SET col1 = value1, col2 = value2
[ WHERE ...]
DML Statements: DELETE
• DELETE
– deletes rows from one table (any number of
rows)
– locks deleted data (update will wait)
– waits for locks if data is locked (can cause
deadlock)
– syntax:
DELETE FROM table [ WHERE ... ]
DML Statements: INSERT
• INSERT
– inserts one row or multiple rows
– can sometimes wait for a lock
Syntax:
INSERT INTO table (col1, col2)
VALUES (val1, val2)
or
INSERT INTO table VALUES (val1, val2)
or
INSERT INTO table (col1, col2)
SELECT val1, val2
FROM ... (regular select statement)
SELECT – basic syntax
• Simple version:
SELECT column_list FROM table
[WHERE condition]
• Example with table alias:
SELECT u.last_name, u.first_name
FROM users u
– u is an alias for table users
• Column alias:
SELECT count(*) AS cnt
FROM users
cnt is column alias for function count(*)
SELECT – all columns
• Select all columns from a table using “*”
• The following statements are identical:
– SELECT * FROM users
– SELECT users.* FROM users
– SELECT u.* FROM users u
To select all columns and more, use the following
syntax:
SELECT u.*, UPPER(last_name) FROM
users
SELECT – other user tables
• To select data from some other user:
SELECT users.first_name, users.last_name
FROM user_name.users
• Note: user_name cannot be used in column list, the
following is illegal:
SELECT user_name.table1.col1,
user_name.table1.col2
FROM user_name.table1
• To select data from other user’s table current must have
one of the following:
• SELECT privilege on the table
• SELECT ANY TABLE system privilige
WHERE condition
• WHERE clause specifies what records to include
• There can be any number of conditions combined with
AND, OR, NOT
• There also can be conditions:
– EXISTS (subquery), NOT EXISTS (subquery)
– value IN (subquery),
value NOT IN (subquery)
• SQL functions can be used:
SELECT * FROM users WHERE
hire_date > SYSDATE – 10
SELECT * FROM users WHERE
LENGTH(last_name) > 20
WHERE condition examples
SELECT * FROM departments WHERE
EXISTS(SELECT * FROM employees
WHERE employees.dept_id = departments.id)