Cover | Table of Contents
SELECT u.name,
CASE u.open_to_public
WHEN 'y' THEN 'Welcome!'
WHEN 'n' THEN 'Go Away!'
ELSE 'Bad code!'
END AS column_alias
FROM upfall u;
SELECT u.name,
CASE
WHEN u.open_to_public = 'y' THEN 'Welcome!'
WHEN u.open_to_public = 'n' THEN 'Go Away!'
ELSE 'Bad code!'
END AS column_alias
FROM upfall u;
VARCHAR(max_bytes)
TEXT (max_bytes)
VARCHAR2(max_bytes)
VARCHAR2(max_bytes BYTE) VARCHAR2(max_characters CHAR)
DECIMAL DECIMAL(precision) DECIMAL(precision, scale)
DECIMAL(precision) is a decimal integer of up to precision digits. DECIMAL(precision, scale) is a fixed-point decimal number of precision digits with scale digits to the right of the decimal point. For example, DECIMAL(9,2) can store values up to 9,999,999.99.DECIMAL(5,0). In SQL Server, the effect is the same as DECIMAL(18,0).SMALLINT INTEGER BIGINT
SELECT * FROM upfall WHERE id = '1';
SELECT * FROM upfall u
WHERE u.id = CAST('1' AS INTEGER);
SELECT EXTRACT(DAY FROM CURRENT_DATE);
TO_CHAR({datetime|interval}, format)
TO_DATE(string, format)
TO_TIMESTAMP(string, format)
TO_TIMESTAMP_TZ(string, format)
TO_DSINTERVAL('D HH:MI:SS')
TO_YMINTERVAL('Y-M')
NUMTODSINTERVAL(number, 'unit_ds')
NUMTOYMINTERVAL(number, 'unit_ym')
unit_ds ::= {DAY|HOUR|MINUTE|SECOND}
unit_ym ::= {YEAR|MONTH}
SELECT name,
TO_CHAR(confirmed_date, 'dd-Mon-yyyy') cdate
FROM upfall;DELETE FROM data_source WHERE predicates
DELETE FROM state s WHERE s.population IS NULL;
trip table called J's Tour. If you wish to delete J's Tour, you must issue a statement such as:
DELETE FROM trip WHERE name = 'J''s Tour'
ORDER BY CASE stop
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 6 THEN 3
WHEN 4 THEN 4
WHEN 3 THEN 5
WHEN 5 THEN 6
END DESC;
DELETE FROM township;
UPPER (name) will generate an error message because of the space between UPPER and (name).SELECT SYSDATE FROM dual;
2006-02-07 09:32:32.0
ALTER SESSION SET NLS_DATE_FORMAT = 'dd-Mon-yyyy hh: mi:ss';
CURRENT_DATE
CURRENT_TIMESTAMP[(
precision
)]
LOCALTIMESTAMP[(
precision
)]
SYSDATE
SYSTIMESTAMP[(
precision
)]
DBTIMEZONE
SELECT COUNT(u.county_id) AS county_count
FROM upfall u;
14
SELECT COUNT(DISTINCT u.county_id) AS county_count
FROM upfall u;
6
COUNT(expression) is equivalent to COUNT(ALL expression).SELECT COUNT(*) FROM upfall;
COUNT(*) is used because the concept of null applies only to columns, not to entire rows as a whole. All other aggregate functions ignore nulls.|
Function
|
Description
|
|---|---|
AVG(x)
|
Returns the average (mean) of a group of numbers.
|
COUNT(x)
|
Counts the number of non-null values in a group of values.
|
MAX(x)
|
Returns the greatest value in a group.
|
|
|
WITH recursiveGov
(level, id, parent_id, name,
type) AS
(SELECT 1, parent.id, parent.parent_id,
parent.name, parent.type
FROM gov_unit parent
WHERE parent.parent_id IS NULL
UNION ALL
SELECT parent.level+1, child.id,
child.parent_id, child.name,
child.type
FROM recursiveGOV parent, gov_unit child
WHERE child.parent_id = parent.id)
SELECT level, id, parent_id, name, type
FROM recursiveGOV;
recursiveGOV that is specified using the WITH clause. The subquery consists of two SELECTs unioned together. Consider the first SELECT as the union query's starting point. It includes a predicate to treat rows having null parent_ids as the tree roots. Consider the second SELECT as defining the recursive link between parent and child rows.LEVEL ID PARENT_ID NAME TYPE ----- -- --------- -------- -------- 1 3 - Michigan state 2 2 3 Alger county 2 6 3 Baraga county . . .
CREATE INDEX falls_name ON upfall (name, open_to_public);
falls_name is the name of the index. The table to be indexed is upfall. The index is on the combined values of name and open_to_public.CREATE INDEX falls_name ON upfall (name, open_to_public) TABLESPACE users;
CREATE INDEX falls_name ON upfall (UPPER(name), open_to_public);
UPPER(name).DROP INDEX falls_name;
DROP INDEX falls_name ON upfall;
gov_unit table. The values in the VALUES clause correspond to the columns listed after the table name:INSERT INTO gov_unit (id, parent_id, name, type) VALUES (13, 3, 'Chippewa', 'County');
INSERT INTO gov_unit (id, parent_id, name, type) VALUES (14, DEFAULT, 'Mackinac', NULL);
INSERT INTO gov_unit VALUES (15, DEFAULT, 'Luce', 'County');
INSERT INTO gov_unit
(id, parent_id, name, type)
VALUES (16, 3, 'Menominee', 'County'),
(17, 3, 'Iron', 'County'),
(18, 3, 'Keweenaw', 'County');
INSERT INTO (SELECT id, name, type FROM gov_unit) (id, name, type) VALUES (16, 'Keweenaw', 'County');
INSERT INTO trip (name, stop, parent_stop)
(SELECT 'J''s Tour', stop, parent_stop
FROM trip
WHERE name = 'Munising');
SELECT u.name AS fall, c.name AS county
FROM upfall u, county c;
FALL COUNTY
--------------- ----------
Munising Falls Alger
Munising Falls Baraga
Munising Falls Ontonogan
. . .
SELECT u.name AS fall, c.name AS county
FROM upfall u, county c
WHERE u.county_id = c.id;
FALL COUNTY
--------------- ----------
Munising Falls Alger
Tannery Falls Alger
Alger Falls Alger
. . .
SELECT * FROM upfall CROSS JOIN county;
'This is a text literal'
'Isn''t SQL fun?'
Isn't SQL fun?
'[ and ]' as delimiters, specify:Q'[This isn't as bad as it looks]' q'[This isn't as bad as it looks]'
(, [, and { characters are special cases in that their corresponding closing delimiters must be ), ], and }, respectively. Otherwise, use the same character to close the string that you use to open it:Q'|This string is delimited by vertical bars|'
$tag$This is a dollar-quoted string constant$tag$
$tag$. If you like, you can even use $$ without any intervening tag text. Escape sequences (see ) do not have any effect in dollar-quoted string constants; they are treated as literal character sequences. $$\t$$ yields the string \t, not a tab character.|
Escape
|
Description
|
|---|---|
\0
|
MERGE INTO table alias USING datasource ON (exists_test) WHEN MATCHED THEN UPDATE SET column = value, column = value, . . . WHEN NOT MATCHED THEN INSERT (column, column, . . . ) VALUES (value, value, . . . ) datasource ::= {table|view|(subquery)}
upfall table, specify:
MERGE INTO upfall u
USING (SELECT * FROM new_falls) nf
ON (u.id = nf.id)
WHEN MATCHED THEN UPDATE
SET u.name = nf.name,
u.open_to_public = nf.open_to_public
WHEN NOT MATCHED THEN INSERT
(id, name, datum, zone, northing, easting,
lat_lon, county_id, open_to_public,
owner_id, description, confirmed_date)
VALUES (nf.id, nf.name, nf.datum, nf.zone,
nf.northing, nf.easting, nf.lat_lon,
nf.county_id, nf.open_to_public,
nf.owner_id, nf.description,
nf.confirmed_date);
name and open_to_public for existing waterfalls, although you could choose to update all columns if you wanted to do so. For new falls, all columns are inserted into the upfall table.
MERGE INTO upfall u
USING (SELECT * FROM new_falls) nf
ON (u.id = nf.id)
WHEN MATCHED THEN UPDATE
SET u.name = nf.name,
u.open_to_public = nf.open_to_public
WHERE nf.name IS NOT NULL
DELETE WHERE u.open_to_public = 'n'
WHEN NOT MATCHED THEN INSERT
(id, name, datum, zone, northing, easting,
lat_lon, county_id, open_to_public,
owner_id, description, confirmed_date)
VALUES (nf.id, nf.name, nf.datum, nf.zone,
nf.northing, nf.easting, nf.lat_lon,
nf.county_id, nf.open_to_public,
nf.owner_id, nf.description,
nf.confirmed_date)
WHERE nf.open_to_public = 'y';
nf.name IS NOT NULL to prevent updating any name to a null. The subsequent DELETE WHERE clause then deletes any updated rows that no longer represent publicly accessible falls.upfall table:SELECT u.id, u.name, u.datum FROM upfall u WHERE u.datum = 'NAD1927' OR u.datum <> 'NAD1927';
SELECT u.id, u.name, u.datum FROM upfall u WHERE u.datum IS NULL OR u.datum <> 'NAD1927';
SELECT u.id, u.name,
CASE WHEN u.datum IS NULL THEN
'*None!*'
ELSE u.datum END
FROM upfall u;
name when a description is null and show Unknown! when even the name is null, specify:SELECT id, COALESCE(description, name, '*Unknown!*') FROM upfall;
name = 'Wagner Falls' to return data for only that particular waterfall:SELECT u.zone, u.northing, u.easting FROM upfall u WHERE name = 'Wagner Falls';
|
Operator
|
Description
|
|---|---|
!=, <>
|
Tests for inequality
|
<
|
Tests for less than
|
<=
|
Tests for less than or equal to
|
<=>
|
Null-safe test for equality; supported only by MySQL
|
=
|
Tests for equality
|
>
|
Tests for greater than
|
>=
|
Tests for greater than or equal to
|
BETWEEN
|
Tests whether a value lies within a given range
|
EXISTS
|
Tests whether rows exist matching conditions that you specify
|
IN
|
REGEXP_INSTR(source_string, pattern [, position [, occurrence [, return_option [, match_parameter]]]]) REGEXP_LIKE (source_string, pattern [, match_parameter]) REGEXP_REPLACE(source_string, pattern [, replace_string [, position [, occurrence [, match_parameter]]]]) REGEXP_SUBSTR(source_string, pattern [, position [, occurrence [, match_parameter]]])
SELECT expression_list FROM data_source WHERE predicates GROUP BY expression_list HAVING predicates ORDER BY expression_list
SELECT id, name FROM owner;
ID NAME ------------ --------------- 1 Pictured Rocks 2 Michigan Nature 3 AF LLC 4 MI DNR 5 Horseshoe Falls
SELECT *
FROM owner;
ID NAME PHONE TYPE
------------ --------------- ------------ -------
1 Pictured Rocks 906.387.2607 public
2 Michigan Nature 517.655.5655 private
3 AF LLC private
4 MI DNR 906-228-6561 public
5 Horseshoe Falls 906.387.2635 private
DELETE
FROM (SELECT * FROM upfall u
WHERE u.open_to_public = 'n') u2
WHERE u2.owner_id IS NOT NULL;
SELECT c.name,
(SELECT COUNT(*) FROM upfall u2
WHERE u2.county_id = c.id) fall_count,
(SELECT AVG(fall_count)
FROM (SELECT COUNT(*) fall_count
FROM upfall u3
GROUP BY u3.county_id) x1) avg_count
FROM county c
WHERE (SELECT COUNT(*) FROM upfall u2
WHERE u2.county_id = c.id)
>
(SELECT AVG(fall_count)
FROM (SELECT COUNT(*) fall_count
FROM upfall u3
GROUP BY u3.county_id) x2);
CREATE TABLE simple_example ( id NUMERIC, name VARCHAR(15), last_changed DATE );
CONSTRAINT constraint_name syntax is optional and is often omitted (especially on column constraints such as the NOT NULL constraint).
CREATE TABLE oracle_example (
id NUMBER(6),
name VARCHAR2(15) NOT NULL,
country VARCHAR2(2) DEFAULT 'CA'
CONSTRAINT country_not_null NOT NULL
CONSTRAINT country_check
CHECK (country IN ('CA','US')),
indexed_name VARCHAR2(15),
CONSTRAINT oracle_example_pk
PRIMARY KEY (id),
CONSTRAINT oracle_example_fk01
FOREIGN KEY (name, country)
REFERENCES parent_example (name, country),
CONSTRAINT oracle_example_u01
UNIQUE (name, country),
CONSTRAINT oracle_example_index_upper
CHECK (indexed_name = UPPER(name))
) TABLESPACE users;
users tablespace. The TABLESPACE clause is optional. If you aren't certain which tablespace to specify, you can either omit the clause to accept your default tablespace assignment or ask your database administrator's advice.CREATE SEQUENCE oracle_example_pk NOCYCLE MAXVALUE 999999 START WITH 1;
id value from the sequence whenever a new row is inserted:
ALTER TABLE oracle_example ADD (
lower_name VARCHAR2(15),
CONSTRAINT lower_name
CHECK (lower_name = LOWER(name))
);
ALTER TABLE oracle_example MODIFY (
name VARCHAR2(30) DEFAULT 'Missing!'
CONSTRAINT name_canbe_null NULL,
country DEFAULT NULL,
indexed_name varchar2(30) NOT NULL
CONSTRAINT no_leading_space
CHECK (indexed_name = LTRIM(indexed_name))
);
ALTER TABLE oracle_example DROP CONSTRAINT lower_name; ALTER TABLE oracle_example DROP COLUMN lower_name;
ALTER TABLE db2_example
ADD COLUMN lower_name VARCHAR(15)
ADD CONSTRAINT lower_name
CHECK(lower_name = LOWER(name));
ALTER TABLE db2_example
ALTER COLUMN name
SET DATA TYPE VARCHAR(30)
ALTER COLUMN name SET DEFAULT 'Missing!'
ALTER COLUMN country SET DEFAULT NULL
ALTER COLUMN indexed_name
SET DATA TYPE VARCHAR(30);
no_leading_space constraint added at the column level for other brands must be added at the table level for DB2:
ALTER TABLE db2_example
ADD CONSTRAINT no_leading_space
CHECK (indexed_name = LTRIM(indexed_name));
DROP TABLE table_name;
DROP TABLE table_name CASCADE CONSTRAINTS;
DROP TABLE table_name CASCADE;
SET IMPLICIT_TRANSACTIONS ON
SET IMPLICIT_TRANSACTIONS OFF
SET AUTOCOMMIT=0
SET AUTOCOMMIT=1
SET TRANSACTION options [NAME 'tran_name'] options ::= {READ {ONLY|WRITE} |ISOLATION LEVEL {SERIALIZABLE|READ COMMITTED} |USE ROLLBACK SEGMENT segment_name
NAME
'tran_name
'