You are on page 1of 18

Introducing the Structured Query Language (SQL)

• 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.

Creating a Database 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;

where

• user_name specifies the name you assign to your database user


• password specifies the password for your database user
Oracle Database Types

VARCHAR2(length)

DATE

NUMBER( precision, scale )

CREATE TABLE customers (


customer_id INTEGER
CONSTRAINT customers_pk PRIMARY KEY,
first_name VARCHAR2(10) NOT NULL,
last_name VARCHAR2(10) NOT NULL,
dob DATE,
phone VARCHAR2(12)
);

Adding, Modifying, and Removing Rows


SQL> DESCRIBE customers
SQL> INSERT INTO customers (
2 customer_id, first_name, last_name, dob, phone
3 ) VALUES (
4 6, 'Fred', 'Brown', '01-JAN-1970', '800-555-1215'
5 );

INSERT INTO customers values(6, 'Fred', 'Brown', '01-JAN-1970', '800-


555-1215'
6 );

Modifying an Existing Row in a Table


UPDATE customers
2 SET last_name = 'Orange'
3 WHERE customer_id = 2;

Removing a Row from a Table


SQL> DELETE FROM customers
2 WHERE customer_id = 2;

To undo any changes you make to the database, you use ROLLBACK:

SQL> ROLLBACK;
Quitting SQL*Plus
SQL> EXIT

Selecting All Columns from a Table


SELECT *
FROM customers;

Performing Arithmetic
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
SELECT 2*6
FROM dual;

Using Date Arithmetic


SELECT TO_DATE('31-JUL-2003') + 2
FROM dual;
SELECT TO_DATE('02-AUG-2003') - TO_DATE('31-JUL-2003')
FROM dual;

Using Column Aliases


SELECT price * 2 DOUBLE_PRICE
FROM products;

SELECT 10 * (12 / 3 - 1) AS "Computation"


FROM dual;

Merging Column Output Using Concatenation

SELECT first_name || ' ' || last_name AS "Customer Name"


FROM customers;

Understanding Null Values


SELECT customer_id, first_name, last_name, dob
FROM customers
WHERE dob IS NULL;

SELECT customer_id, first_name, last_name,


NVL(phone, 'Unknown phone number') AS PHONE_NUMBER
FROM customers;

Displaying Distinct Rows


SELECT DISTINCT purchased_by
FROM purchases;

Filtering Rows Using the WHERE Clause


SELECT *
FROM customers
WHERE customer_id = 2;

Using Comparison Operators

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%';

Using the IN Operator


SELECT *
FROM customers
WHERE customer_id IN (2, 3, 5);
Using the BETWEEN Operator
SELECT *
FROM customers
WHERE customer_id BETWEEN 1 AND 3;

Using the Logical Operators

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

Sorting Rows Using the ORDER BY Clause


SELECT *
FROM customers
ORDER BY last_name;

CREATE TABLE customers (


customer_id INTEGER
CONSTRAINT customers_pk PRIMARY KEY,

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.

Using Simple Functions

• 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.

Table 3-1: Character Functions


Function Description
ASCII(x) Returns the ASCII value of the character
x.
CHR(x) Returns the character with the ASCII
value of x.
CONCAT(x, y) Appends y to x and then returns the
resulting string.
INITCAP(x) Converts the initial letter of each word in x
to uppercase and returns that string.
INSTR(x, find_string [, start] [, Searches for find_string in x and returns
occurrence]) the position at which find_string occurs.
You can supply an optional start position
to begin the search. Also, you can supply
an optional occurrence that indicates
which occurrence of find_string should be
returned.
LENGTH(x) Returns the number of characters in x.
LOWER(x) Converts the letters in x to lowercase and
returns that string.
LPAD(x, width [, pad_string]) Pads x with spaces to left, to bring the total
length of the string up to width characters.
You can supply an optional pad_string,
which specifies the string to be repeated to
the left of x to fill up the padded space.
LTRIM(x [, trim_string]) Trims characters from the left of x. You
Table 3-1: Character Functions
Function Description
can supply an optional trim_string that
specifies the characters to trim; if no
trim_string is supplied, spaces are
trimmed by default.
NANVL(x, value) New for Oracle Database 10g. Returns
value if x matches the NaN special value
(not a number), otherwise x is returned.
NVL(x, value) Returns value if x is null; otherwise, x is
returned.
NVL2(x, value1, value2) Returns value1 if x is not null; if x is null,
value2 is returned.
REPLACE(x, search_string, Searches x for search_string and replaces
replace_string) it with replace_string.
RPAD(x, width [, pad_string]) Same as LPAD(), but with x padded to the
right.
RTRIM(x [, trim_string]) Same as LTRIM(), but x is trimmed from
the right.
SOUNDEX(x) Returns a string containing the phonetic
representation of x. This lets you compare
words that are spelled differently, but
sound alike in English.
SUBSTR(x, start [, length]) Returns a substring of x that begins at the
position specified by start. An optional
length for the substring may be supplied.
TRIM([trim_char FROM) x) Trims characters from the left and right of
x. You can supply an optional trim_char
that specifies the characters to trim; if no
trim_char is supplied, spaces are trimmed
by default.
UPPER(x) Converts the letters in x to uppercase and
returns that string.

SELECT ASCII('a'), ASCII('A'), ASCII('z'), ASCII('Z'),


ASCII(0), ASCII(9)
FROM dual;

SELECT CHR(97), CHR(65), CHR(122), CHR(90),


CHR(48), CHR(57)
FROM dual;

SELECT CONCAT(first_name, last_name)


FROM customers;
SELECT product_id, INITCAP(description)
FROM products
WHERE product_id < 4;

The next example displays the position where the second occurrence of e occurs,
starting from the beginning of the product name using INSTR():

SELECT name, INSTR(name, 'e', 1, 2)


FROM products
WHERE product_id = 1;

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():

SELECT name, LENGTH(name)


FROM products;

LOWER() and UPPER()

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.

SELECT UPPER(first_name), LOWER(last_name)


FROM customers;

LPAD() and RPAD()

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.

SELECT RPAD(name, 30, '.'), LPAD(price, 8, '*+')


FROM products
WHERE product_id < 4;

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.

SELECT customer_id, NVL(phone, 'Unknown Phone Number')


FROM customers;

NVL2()

NVL2(x, value1, value2) returns value1 if x is not null. If x is null, value2 is returned.

SELECT customer_id, NVL2(phone, 'Known', 'Unknown')


FROM customers;

REPLACE()

You use REPLACE(x, search_string, replace_string) to search x for search_string


and replace it with replace_string.

SELECT REPLACE(name, 'Science', 'Physics')


FROM products
WHERE product_id = 1;

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:

SELECT SUBSTR('Mary had a little lamb', 12, 6)


FROM dual;

Combining Functions
SELECT name, UPPER(SUBSTR(name, 2, 8))
FROM products
WHERE product_id < 4;

Numeric Functions

Table 3-2: Numeric Functions


Function Description Examples
ABS(x) Returns the absolute value ABS(10) = 10
of x. ABS(-10) = 10
ACOS(x) Returns the arccosine of x. ACOS(1) = 0
ACOS(-1) = 3.14159265
ASIN(x) Returns the arcsine of x. ASIN(1) = 1.57079633
ASIN(-1) = -1.5707963
ATAN(x) Returns the arctangent of x. ATAN(1) = .785398163
ATAN(-1) = -.78539816
ATAN2(x, y) Returns the arctangent of x ATAN2(1, -1) =
and y. 2.35619449
BITAND(x, y) Returns the result of >BITAND(0, 0) = 0
performing a bitwise AND BITAND(0, 1) = 0
on x and y. BITAND(1, 0) = 0
BITAND(1, 1) = 1
BITAND(1010, 1100) = 64
COS(x) Returns the cosine of x, COS(90 * 3.1415926) = 1
where x is an angle in COS(45 * 3.1415926) = -1
radians.
COSH(x) Returns the hyperbolic COSH(3.1415926) =
cosine of x. 11.5919527
CEIL(x) Returns the smallest integer CEIL(5.8) = 6
greater than or equal to x. CEIL(-5.2) = -5
EXP(x) Returns the result of the EXP(1) = 2.71828183
number e raised to the EXP(2) = 7.3890561
power x, where e is
Table 3-2: Numeric Functions
Function Description Examples
approximately 2.71828183.
FLOOR(x) Returns the largest integer FLOOR(5.8) = 5
less than or equal to x. FLOOR(-5.2) = -6
LOG(x, y) Returns the logarithm, base LOG(2, 4) = 2
x, of y. LOG(2, 5) = 2.32192809
LN(x) Returns the natural LN(2.71828183) = 1
logarithm of x.
MOD(x, y) Returns the remainder MOD(8, 3) = 2
when x is divided by y. MOD(8, 4) = 0
POWER(x, y) Returns the result of x POWER(2, 1) = 2
raised to the power y. POWER(2, 3) = 8
ROUND(x [, y]) Returns the result of ROUND(5.75) = 6
rounding x an optional y ROUND(5.75, 1) = 5.8
decimal places. If y is ROUND(5.75, -1) = 10
omitted, x is rounded to
zero decimal places. If y is
negative, x is rounded to
the left of the decimal
point.
SIGN(x) Returns -1 if x is negative, SIGN(-5) = -1
1 if x is positive, or 0 if x is SIGN(5) = 1
zero. SIGN(0) = 0
SIN(x) Returns the sine of x. SIN(0) = 0
SINH(x) Returns the hyperbolic sine SINH(1) = 1.17520119
of x.
SQRT(x) Returns the square root of SQRT(25) = 5
x. SQRT(5) = 2.23606798
TAN(x) Returns the tangent of x. TAN(0) = 0
TANH(x) Returns the hyperbolic TANH(1) = .761594156
tangent of x.
TRUNC(x [, y]) Returns the result of TRUNC(5.75) = 5
truncating x an optional y TRUNC(5.75, 1) = 5.7
decimal places. If y is TRUNC(5.75, -1) = 0
omitted, x is truncated to
zero decimal places. If y is
negative, x is truncated to
the left of the decimal
point.
ABS()

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:

SELECT ABS(10), ABS(-10)


FROM dual;

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:

SELECT CEIL(5.8), CEIL(-5.2)


FROM dual;

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:

SELECT FLOOR(5.8), FLOOR(-5.2)


FROM dual;

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:

SELECT MOD(8, 3), MOD(8, 4)


FROM dual;

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:

SELECT POWER(2, 1), POWER(2, 3)


FROM dual;

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:

SELECT TRUNC(5.75), TRUNC(5.75, 1), TRUNC(5.75, -1)


FROM dual;

Using Datetime Functions


Datetime Functions
Function Description
ADD_MONTHS(x, y) Returns the result of adding y months to x. If y is negative,
y months are subtracted from x.
LAST_DAY(x) Returns the last day of the month that contains x.
MONTHS_BETWEEN(x, Returns the number of months between x and y. If x
y) appears before y on the calendar, the number returned is
positive, otherwise the number is negative.
NEXT_DAY(x, day) Returns the datetime of the next day following x; day is
specified as a literal string—SATURDAY, for example.
ROUND(x [, unit]) Rounds x. By default, x is rounded to the beginning of the
nearest day. You may supply an optional unit string to
indicate the rounding unit. For example, YYYY rounds x
to the first day of the nearest year.
SYSDATE() Returns the current datetime set for the operating system
on which the database resides.
TRUNC(x [, unit]) Truncates x. By default, x is truncated to the beginning of
the day. You may supply an optional unit string that
indicates the truncating unit. For example, MM truncates
x to the first day of the month.

Writing Single Row Subqueries

Subqueries in a WHERE Clause


SELECT first_name, last_name
FROM customers
WHERE customer_id =
(SELECT customer_id
FROM customers
WHERE last_name = 'Brown');

FIRST_NAME LAST_NAME
---------- ----------
John Brown

SELECT product_id, name, price


FROM products
WHERE price >
(SELECT AVG(price)
FROM products);

Subqueries in a HAVING Clause


SELECT product_type_id, AVG(price)
FROM products
GROUP BY product_type_id
HAVING AVG(price) <
(SELECT MAX(AVG(price))
FROM products
GROUP BY product_type_id);

Writing an UPDATE Statement Containing a Subquery

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;

DELETE FROM employees


WHERE salary >
(SELECT AVG(high_salary)
FROM salary_grades);

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

Changing a User’s Password


CONNECT jason/marcus
PASSWORD
Changing password for JASON
Old password: ******
New password: ******
Retype new password: ******
Password changed

Deleting a User
CONNECT system/manager
DROP USER jason;

Granting System Privileges to a User

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):

GRANT CREATE SESSION, CREATE USER, CREATE TABLE TO steve;/public

Revoking System Privileges from a User


REVOKE CREATE TABLE FROM steve;

The next example revokes EXECUTE ANY PROCEDURE

Granting Privileges to Roles

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:

GRANT SELECT, INSERT, UPDATE, DELETE


ON product_types TO product_manager;
GRANT SELECT, INSERT, UPDATE, DELETE
ON products TO product_manager;
GRANT SELECT, INSERT, UPDATE, DELETE
ON salary_grades TO hr_manager;
GRANT SELECT, INSERT, UPDATE, DELETE
ON employees TO hr_manager;
GRANT CREATE USER TO hr_manager;
GRANT product_manager, hr_manager 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

IF count > 0 THEN


message := 'count is positive';
IF area > 0 THEN
message := 'count and area are positive';
END IF
ELSIF count = 0 THEN
message := 'count is zero';
ELSE
message := 'count is negative';
END IF;

You might also like