Sei sulla pagina 1di 9

S12_L02

DESCRIBE Command
The DESCRIBE command displays the structure of the table. The syntax is:
DESCRIBE <table name>;
atau
DESC <table name>;
DESC returns the table name, table schema, tablespace name, indexes, triggers, c
onstraints, and comments, as well as the data types, primary and foreign keys, a
nd nullable columns.
Basic SELECT Statement
The SELECT * command returns all the rows in a table. The syntax is:
SELECT *
FROM <table name>;
Select Statement with a Condition
To return a subset of the data, modify the SELECT statement. The syntax is:
SELECT <column name 1, column name 2, etc.>
FROM <table name>
WHERE <condition>;
Inserting Data
Using the INSERT command, you can add a row of data to the table. The syntax is:
INSERT INTO <table name>
VALUES (value 1, value 2, value 3, etc);
S12_L03
ALTER TABLE Syntax
To add a new column to a table, use the ALTER TABLE command. The syntax is:
ALTER TABLE <table name>
ADD (<new_column_name> <data type>);
Drop a Column
To drop a column from a table, use the ALTER TABLE command. The syntax is:
ALTER TABLE <table name>
DROP COLUMN <column_name>;
Delete a Row
To delete a row from a table, use the DELETE command. The syntax is:
DELETE from <table name>
WHERE <column_name> = 'some value ;
S15_L01
SELECT Statement
The SELECT statement retrieves information from the database. The syntax for a S
ELECT statement is as follows:
SELECT <column_name(s)>
FROM <table_name>;
In its simplest form, a SELECT statement must include the following:
A SELECT clause, which specifies the columns to be displayed
A FROM clause, which specifies the table containing the columns listed in the SEL
ECT clause
Capabilities of SELECT Statements
Projection: Used to choose columns in a table -> SELECT
Selection: Used to choose rows in a table -> WHERE

Join: Used to bring together data that is stored in different tables by creating
a link between them.
Precedence in Arithmetic Operators
Arithmetic operators perform the mathematical operations of Multiplication, Divi
sion, Addition, and Subtraction. If these operators appear together in an expres
sion, multiplication and division are evaluated first. So the order is: * / + -.
An easy way to remember their operator precedence is the mnemonic device:
My Dear Aunt Sally
NULL Values: Unknown
->yang dioperasikan dengan NULL maka hasilnya NULL
Aliases
There are several rules when using column aliases to format output.
A column alias:
Renames a column heading
Is useful with calculations
Immediately follows the column name
May have the optional AS keyword between the column name and alias
Requires double quotation marks (" ") if the alias contains spaces or special cha
racters, or is case-sensitive
S16_L01
The Concatenation Operator
Concatenation means to connect or link together in a series. The symbol for conc
atenation is 2 vertical bars sometimes referred to as pipes. Values on either side
of the || operator are combined to make a single output column. The syntax is:
string1 || string2 || string_n
When values are concatenated, the resulting value is a character string.
SELECT department_id || ' ' ||department_name
FROM departments;
Concatenation and Literal Values
A literal value is a fixed data value such as a character, number, or date. The
following are examples of literal values:
dollars
1000
January 1, 2009
Using concatenation and literal values, you can create output that looks like a
sentence or statement.
SELECT last_name ||' has a monthly salary of ' || salary || ' dollars.' AS Pay F
ROM employees;
Using DISTINCT to Eliminate Duplicate Rows
SELECT DISTINCT department_id
FROM employees;
S16_L02
Comparison Operators in the WHERE Clause
The = sign can be used in the WHERE clause. In addition to the equal to operator (
=), other comparison operators can be used to compare one expression to another:
= equal to
> greater than
>= greater than or equal to
< less than

<= less than or equal to


<> not equal to (or != or ^=)
Character strings and dates in the WHERE clause must be enclosed in single quota
tion marks ' ' . But this does NOT make them literal strings. They are still jus
t character and date strings.
Numbers, however, should not be enclosed in single quotation marks.
S16_L03
Comparison Operators
BETWEEN AND
SELECT title, year
FROM d_cds
WHERE year BETWEEN 1999 AND 2001;
atau
SELECT title, year
FROM d_cds
WHERE year >= 1999 AND year <= 2001;
-NOT BETWEEN..AND
SELECT title, year
FROM d_cds
WHERE year NOT BETWEEN 1999 AND 2001;
atau
SELECT title, year
FROM d_cds
WHERE year < 1999 OR year > 2001;
IN: "membership condition." It is used to test whether a value is IN a specified
set of values.
SELECT title, type_code
FROM d_songs
WHERE type_code IN (77,12);
atau
SELECT title, type_code
FROM d_songs
WHERE type_code = 77 OR type_code = 12;
LIKE
Two symbols: the (%) and the underscore (_) -- called wildcard characters, can b
e used to construct a search string.
The percent (%) symbol is used to represent any sequence of zero or more charact
ers. The underscore (_) symbol is used to represent a single character.
SELECT last_name
FROM employees
WHERE last_name LIKE '_o%';
The ESCAPE option backward slash (\) is used to indicate that the underscore or
% is part of the name, not a wildcard value. For example, if the database had st
ored CD track numbers as TRA_6, the WHERE clause would need to be written as:
WHERE track LIKE 'TRA\_%'
IS NULL, IS NOT NULL
The IS NULL condition tests for unavailable, unassigned, or unknown data. IS NOT
NULL tests for data that is available in the database.
S17_L01
Logical Operators
A logical operator combines the results of two or more conditions to produce a s
ingle result. A row is returned ONLY IF the overall result of the condition is t

rue.
AND -- Returns TRUE if both conditions are true.
OR -- Returns TRUE if either condition is true.
NOT -- Returns TRUE if the condition is false.
ORDER
1
2
3
4
5
6
7
8

OPERATORS
Arithmetic + - * /
Concatenation ||
Comparison <, <=, >, >=, <>
IS (NOT) NULL, LIKE, (NOT) IN
(NOT) BETWEEN
NOT
AND
OR

S17_L02
ORDER BY Clause
The default sort order is ascending.
Numeric values are displayed lowest to highest.
Date values are displayed with the earliest value first.
Character values are displayed in alphabetical order.
Null values are displayed last in ascending order and first in descending order.
NULLS FIRST Specifies that NULL values should be returned before non-NULL values.
NULLS LAST Specifies that NULL values should be returned after non-NULL values.
SELECT title, year
FROM d_cds
ORDER BY year DESC;
You can order data by using a column alias. The alias used in the SELECT stateme
nt is referenced in the ORDER BY clause.
SELECT title, year AS "Recording Date"
FROM d_cds
ORDER BY "Recording Date";
Order of Execution
The order of execution of a SELECT statement is as follows:
1.FROM clause: locates the table that contains the data
2.WHERE clause: restricts the rows to be returned
3.SELECT clause: selects from the reduced data set the columns requested
4.ORDER BY clause: orders the result set
Sorting with Multiple Columns
To create an ORDER BY clause to sort by multiple columns, specify the columns to
be returned and separate the column names using commas. If you want to reverse
the sort order of a column, add DESC after its name.
SELECT title, year
FROM d_cds
ORDER BY year DESC, title;
S17_L03
Oracle has two distinct types of functions:
Single-Row (Single-row Input, Single Output)
Multiple-Row (Multiple-row Input, Single Output)/Group Functions
----------------------------------------------------------------Single-row function bisa di:
SELECT, WHERE, ORDER BY
Character Functions:
A. Case Manipulation Functions (hanya 1 parameter):

-LOWER
-UPPER
-INITCAP
B. Character Manipulation Functions:
-CONCAT (2 parameter yang akan digabungkan)
-SUBSTR (3 parameter: string_asal, indeks_karakter_mulai, sebanyak_brp_karakter)
-LENGTH (1 paramater)
-INSTR (2 parameter: string_asal, karakter_yg_dicari) ->posisi brp
-LPAD (3 parameter: string_asal, total_jml_karakter, karakter_utk_melengkapi_sd_
total_jml_karakter)
-RPAD (3 parameter: string_asal, total_jml_karakter, karakter_utk_melengkapi_sd_
total_jml_karakter)
-TRIM (karakter_yang_ingin_diremove FROM string_asal)
-REPLACE (3 parameter: string_asal, string_yang_akan_di_replace, replacement_str
ing)
Substitution Variables
dengan menambahkan :variable_name supaya nilai yang dicari di bagian WHERE sesua
i input user
misal where last_name= :l_name
Number Functions:
1. ROUND (2 parameter: column/expression, decimal_place)
Jika decimal_place tidak dispesifikasikan, maka sama dengan nol
2. TRUNC (2 parameter: column/expression, decimal_place)
Jika decimal_place tidak dispesifikasikan, maka sama dengan nol
3. MOD (2 parameter)
Date Functions: (Format: DD/MON/YYYY)
-SYSDATE
-MONTHS_BETWEEN (selisih brp bulan, 2 parameter:tgl1, tgl2)
-ADD_MONTHS (menambah brp bulan, 2 parameter: tgl, brp_bulan)
-NEXT_DAY (next day dari specified date, 2 parameter: tgl, nama_hari)
-LAST_DAY (last day dari bulan, 1 parameter: tgl)
-ROUND (2 parameter: tgl, 'MONTH'/'DATE')
-TRUNC (2 parameter: tgl, 'MONTH'/'DATE')
Conversion Functions:
-TO_CHAR (2 parameter: column/expression, format)
-TO_NUMBER (2 parameter: column/expression, format)
-TO_DATE (2 parameter: column/expression, format)
NULL Functions:
-NVL (2 parameter: column/expression, nilai_pengganti_jika_null)
-NVL2 (3 parameter: column/expression, nilai_pengganti_jika_tidak_null, nilai_pe
ngganti_jika_null)
-NULLIF (2 parameter: expression1, expression2)
Jika kedua eskpresi sama, return null. Jika tidak sama, return expression1
-COALESCE(expression1, expression2, ..., expression-n)
Return expression sampai ditemukan expression yg tidak null
Conditional Expressions:
-CASE
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END

-DECODE
DECODE(columnl|expression, search1, result1
[, search2, result2,...,]
[, default])
JOIN ANSI&Oracle
-Cross Join
-----ANSI
-----SELECT name, event_date, loc_type, rental_fee
FROM d_events CROSS JOIN d_venues;
-----Oracle
-----SELECT name, event_date, loc_type, rental_fee
FROM d_events, d_venues;
-Equi Join
-----ANSI
-----Natural Join (nama kolom dan tipe data sama):
SELECT p.song_id , t.song_id
FROM d_play_list_items p NATURAL JOIN d_track_listings t
--------------------------------------------------------USING Clause (nama kolom sama, tipe data berbeda):
SELECT p.song_id , t.song_id
FROM d_play_list_items p JOIN d_track_listings t
USING(song_id);
--------------------------------------------------------ON Clause (nama kolom berbeda)
SELECT p.song_id , t.song_id
FROM d_play_list_items p JOIN d_track_listings t
ON (p.song_id = t.id_song);
-----Oracle
-----SELECT p.song_id , t.song_id
FROM d_play_list_items p, d_track_listings t
WHERE p.song_id = t.song_id;
-Non Equi Join
-----ANSI
-----SELECT p.code, e.cost
FROM d_packages p JOIN d_events e
ON (e.cost BETWEEN p.low_range AND p.high_range)
-----Oracle
-----SELECT p.code, e.cost
FROM d_packages p, d_events e
WHERE e.cost BETWEEN p.low_range AND p.high_range
-Outer Join
LEFT:
-----ANSI

-----SELECT d.department_id, e.last_name


FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);
-----Oracle (+) menunjukkan missing data
-----SELECT d.department_id, e.last_name
FROM employees e, departments d
WHERE e.department_id = d.department_id(+);
RIGHT:
-----ANSI
-----SELECT d.department_id, e.last_name
FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);
-----Oracle (+) menunjukkan missing data
-----SELECT d.department_id, e.last_name
FROM employees e, departments d
WHERE e.department_id(+) = d.department_id;
FULL:
-----ANSI
-----SELECT d.department_id, e.last_name
FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id);
-----Oracle
-----Tidak bisa diterapkan
GROUP Functions
-Tiap fungsi mengembalikan sebuah nilai/hasil.
AVG
COUNT
MIN
MAX
SUM
VARIANCE
STDDEV
-Mengabaikan null values kecuali COUNT(*)
-Hanya bisa digunakan di SELECT dan HAVING
-COUNT(expression) returns the number of non-null values in the expression colum
n.
SELECT COUNT (YEAR)
FROM d_cds
WHERE year < 2001;
-COUNT(DISTINCT expression) returns the number of unique non-null values in the
expression column.
SELECT COUNT (DISTINCT year) FROM d_cds WHERE year < 2001;
-The SELECT statement to include null values:
SELECT AVG(NVL(customer_orders, 0))
GROUP BY Guidelines

Important guidelines to remember when using a GROUP BY clause are:


If you include a group function (AVG, SUM, COUNT, MAX, MIN, STDDEV, VARIANCE) in
a SELECT clause along with any other individual columns, each individual column
must also appear in the GROUP BY clause.
You cannot use a column alias in the GROUP BY clause.
Nesting Group Functions
Group functions can be nested to a depth of two when GROUP BY is used.
SELECT max(avg(salary))
FROM employees
GROUP by department_id;
HAVING
The WHERE clause is used to restrict rows; the HAVING clause is used to restrict
groups returned from a GROUP BY clause.
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 1;
ROLLUP
In GROUP BY queries, you are quite often required to produce subtotals and total
s, and the ROLLUP operation can do that for you.
The action of ROLLUP is straightforward: it creates subtotals that roll up from
the most detailed level to a grand total. ROLLUP uses an ordered list of groupin
g columns in its argument list.
First, it calculates the standard aggregate values specified in the GROUP BY clau
se.
Next, it creates progressively higher-level subtotals, moving from right to left
through the list of grouping columns.
Finally, it creates a grand total.
CUBE
CUBE, like ROLLUP, is an extension to the GROUP BY clause. It produces cross-tab
ulation reports.
It can be applied to all aggregate functions including AVG, SUM, MIN, MAX, and C
OUNT.
Columns listed in the GROUP BY clause are cross-referenced to create a superset
of groups. The aggregate functions specified in the SELECT list are applied to t
his group to create summary values for the additional super-aggregate rows.
GROUPING SETS
GROUPING SETS is another extension to the GROUP BY clause. It is used to specify
multiple groupings of data. It gives you the functionality of having multiple G
ROUP BY clauses in the same SELECT statement, which is not allowed in the normal
syntax.
GROUPING Functions
Using a single column from the query as its argument, the GROUPING function will
return a 1 for an aggregated (computed) row and a 0 for a non-aggregated (retur
ned) row.
The syntax for the GROUPING is simply GROUPING (column_name). It is used only in
the SELECT clause and it takes only a single column expression as the argument.
Set Operators
-UNION
-UNION ALL
-INTERSECT
-MINUS

Select location_id, department_name "Department", TO_CHAR(NULL) "Warehouse"


FROM Departments
UNION
SELECT location_id, TO_CHAR(NULL) "Department", warehouse_name
FROM warehouses;
SELECT hire_date, employee_id, to_date(null) start_date, to_date(null) end_date,
job_id, department_id
FROM employees
UNION
SELECT to_date(null), employee_id, start_date, end_date, job_id, department_id
FROM job_history
ORDER BY employee_id
SUB QUERIES
s06_L01 S.D S06_L04
DML
S07_L01 S.D S07_L03
DDL
s08_L01 S.D S08_L03
CONSTRAINT
S10_L01 S.D S10_L03
VIEW
S11_L01 S.D S11_L03
SEQUENCE, INDEX, SYNONYM
S12_L01 S.D S12_L02
OBJECT PRIVILEGES
S13_L01 S.D S13_L02
DB TRANSACTION
S14_L01

Potrebbero piacerti anche