Professional Documents
Culture Documents
• Query statements Allow you to retrieve rows stored in database tables. You
write a query using the SQL SELECT statement.
• Data Manipulation Language (DML) statements Allow you to modify the
contents of tables. There are three DML statements:
o INSERT Allows you to add rows to a table.
o UPDATE Allows you to change a row.
o DELETE Allows you to remove rows.
• Data Definition Language (DDL) statements Allow you to define the data
structures, such as tables, that make up a database. There are five basic types
of DDL statements:
o CREATE Allows you to create a database structure. For example,
CREATE TABLE is used to create a table; another example is
CREATE USER, which is used to create a database user.
o ALTER Allows you to modify a database structure. For example,
ALTER TABLE is used to modify a table.
o DROP Allows you to remove a database structure. For example,
DROP TABLE is used to remove a table.
o RENAME Allows you to change the name of a table.
o TRUNCATE Allows you to delete the entire contents of a table.
• Transaction Control (TC) statements Allow you to permanently record the
changes made to the rows stored in a table or undo those changes. There are
three TC statements:
o COMMIT Allows you to permanently record changes made to rows.
o ROLLBACK Allows you to undo changes made to rows.
o SAVEPOINT Allows you to set a “savepoint” to which you can roll
back changes made to rows.
• Data Control Language (DCL) statements Allow you to change the
permissions on database structures. There are two DCL statements:
o GRANT Allows you to give another user access to your database
structures, such as tables.
o REVOKE Allows you to prevent another user from accessing to your
database structures, such as tables.
To create a user in the database, you use the CREATE USER statement. The
simplified syntax for the CREATE USER statement is as follows:
where
VARCHAR2(length)
DATE
To undo any changes you make to the database, you use ROLLBACK:
SQL> ROLLBACK;
Quitting SQL*Plus
SQL> EXIT
Performing Arithmetic
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
SELECT 2*6
FROM dual;
There are many other comparison operators that you can use in a WHERE clause
besides the equality operator. The following table lists the comparison operators.
Operator Description
= Equal
<> or != Not equal
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
ANY Compares one value with any value in a list
ALL Compares one value with all values in a list
SELECT *
FROM customers
WHERE customer_id > ANY (2, 3, 4);
SELECT *
FROM customers
WHERE customer_id > ALL (2, 3, 4);
Using the SQL Operators
The SQL operators allow you to limit rows based on pattern matching of strings, lists
of values, ranges of values, and null values. The SQL operators are listed in the
following table:
Operator Description
LIKE Matches patterns in strings
IN Matches lists of values
BETWEEN Matches a range of values
IS NULL Matches null values
IS NAN New for Oracle10g. Matches the NaN special value,
which means “not a number”
IS INFINITE New for Oracle10g. Matches infinite BINARY_FLOAT
and BINARY_DOUBLE values
You can also use the NOT operator to reverse the meaning of LIKE, IN, BETWEEN,
and IS NULL:
• NOT LIKE
• NOT IN
• NOT BETWEEN
• IS NOT NULL
• IS NOT NAN
• IS NOT INFINITE
SELECT *
FROM customers
WHERE first_name LIKE '_o%';
SELECT *
FROM customers
WHERE first_name NOT LIKE '_o%';
There are three logical operators that may be used in a WHERE clause. The logical
operators allow you to limit rows based on logical conditions. The logical operators
are listed in the following table:
Operator Description
x AND y Returns true when both x and y are true
x OR y Returns true when either x or y is true
NOT x Returns true if x is false, and returns false if x is true
alter table
cust_table
add constraint
fk_cust_name FOREIGN KEY (person_name)
references
person_table (person_name);
ALTER TABLE
cust_table
drop constraint
fk_cust_table_ref;
Performing SELECT Statements that Use More than
Two Tables
• Equijoins You use the equality operator (=) in the join. You’ve already seen
examples of equijoins.
• Non-equijoins You use an operator other than equals in the join, such as <, >,
BETWEEN, and so on. You’ll see examples of non-equijoins shortly.
• Single row functions These operate on one row at a time and return one row
of output for each input row. An example single row function is CONCAT(x,
y), which appends y to x and returns the resulting string.
•
• Aggregate functions These operate on multiple rows at the same time and
return one row of output. An example aggregate function is AVG(x), which
returns the average of x where x may be a column or, more generally, an
expression.
The next example displays the position where the second occurrence of e occurs,
starting from the beginning of the product name using INSTR():
LENGTH()
You use LENGTH(x) to get the number of characters in x. The following example
displays the length of the strings in the name column of the products table using
LENGTH():
You use LOWER(x) to convert the letters in x to lowercase. Similarly, you use
UPPER(x) to convert the letters in x to uppercase.
You use LPAD(x, width [, pad_string]) to pad x with spaces to left to bring the total
length of the string up to width characters. If a string is supplied in pad_string, this
string is repeated to the left to fill up the padded space. The resulting padded string is
then returned. Similarly, you use RPAD(x, width [, pad_string]) to pad x with strings
to the right.
RPAD(NAME,30,'.') LPAD(PRI
------------------------------ --------
Modern Science................ *+*19.95
Chemistry..................... *+*+*+30
Supernova..................... *+*25.99
LTRIM(), RTRIM(), and TRIM()
SELECT
LTRIM(' Hello Gail Seymour!'),
RTRIM('Hi Doreen Oakley!abcabc', 'abc'),
TRIM('0' FROM '000Hey Steve Button!00000')
FROM dual;
NVL()
You use NVL() to convert a null to a known value. NVL(x, value) returns value if x is
null; otherwise, x is returned.
NVL2()
NVL2(x, value1, value2) returns value1 if x is not null. If x is null, value2 is returned.
REPLACE()
REPLACE(NAME,'SCIENCE','PHYSICS')
-----------------------------------------------
Modern Physics
SUBSTR()
You use SUBSTR(x, start [, length]) to return a substring of x that begins at the
position specified by start. You can also provide an optional length for the substring.
SELECT SUBSTR(name, 2, 7)
FROM products
WHERE product_id < 4;
Using Expressions with Functions
You’re not limited to just using columns in functions: you can supply any valid
expression that evaluates to a string. The following example uses the SUBSTR()
function to select the substring little from the string Mary had a little lamb:
Combining Functions
SELECT name, UPPER(SUBSTR(name, 2, 8))
FROM products
WHERE product_id < 4;
Numeric Functions
You use ABS(x) to get the absolute value of x. The absolute value of a number is that
number without any positive or negative sign. The following example displays the
absolute value of 10 and − 10:
CEIL()
You use CEIL(x) to get the smallest integer greater than or equal to x. The following
example uses CEIL() to display the absolute value of 5.8 and -5.2, respectively:
FLOOR()
You use FLOOR(x) to get the largest integer less than or equal to x. The following
example uses FLOOR() to display the absolute value of 5.8 and -5.2, respectively:
MOD()
You use MOD(x, y) to get the remainder when x is divided by y. The following
example uses MOD() to display the remainder when 8 is divided by 3 and 4,
respectively:
POWER()
You use POWER(x, y) to get the result of x raised to the power y. The following
example uses POWER() to display 2 raised to the power 1 and 3, respectively:
SQRT()
You use SQRT(x) to get the square root of x. The following example displays the
square root of 25 and 5, respectively:
SELECT SQRT(25), SQRT(5)
FROM dual;
TRUNC()
You use TRUNC(x, [y]) to get the result of truncating the number x to an optional y
decimal places. If y is omitted, x is truncated to zero decimal places. If y is negative, x
is truncated to the left of the decimal point. The following example displays
truncating 5.75 to zero, 1, and − 1 decimal places:
FIRST_NAME LAST_NAME
---------- ----------
John Brown
In an UPDATE statement, you set the new column value equal to the result returned
by a single row subquery. For example, the following UPDATE statement sets
employee #4’s salary to the average of the high salary grades returned by a subquery:
UPDATE employees
SET salary =
(SELECT AVG(high_salary)
FROM salary_grades)
WHERE employee_id = 4;
Creating a User
To create a user in the database, you use the CREATE USER statement. The
simplified syntax for the CREATE USER statement is as follows:
CREATE USER user_name IDENTIFIED BY password
Deleting a User
CONNECT system/manager
DROP USER jason;
As mentioned, you use GRANT to grant a system privilege to a user. The following
example grants some system privileges to steve using GRANT (assuming you’re still
connected to the database as system):
You grant privileges to a role using the GRANT statement. You can grant both
system and object privileges to a role, as well as grant another role to a role. The
following example grants the required privileges to the product_manager and
hr_manager roles, and grants these two roles to overall_manager:
Block Structure
PL/SQL programs are divided up into structures known as blocks, with each block
containing PL/SQL and SQL statements. A typical PL/SQL block has the following
structure:
[DECLARE
declaration_statements
]
BEGIN
executable_statements
[EXCEPTION
exception_handling_statements
]
END;
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 width INTEGER;
3 height INTEGER := 2;
4 area INTEGER;
5 BEGIN
6 area := 6;
7 width := area / height;
8 DBMS_OUTPUT.PUT_LINE('width = ' || width);
9 EXCEPTION
10 WHEN ZERO_DIVIDE THEN
11 DBMS_OUTPUT.PUT_LINE('Division by zero');
12 END;
13 /
width = 3