SQL Basics
SQL Basics
Basics:
SELECT … FROM …: selects contents within parameter set in first section from parameter set in second section
{SELECT *
FROM table2;} shows all contents
{SELECT col1
FROM table2;} shows contents of column 1
{SELECT col1, col 2
FROM table2;} shows columns 1 and 2
SELECT … AS … FROM …: selects column specified but displays it with the alias specified from selected table
{SELECT col1 AS alias
FROM table2;} shows column 1 with the name “alias”
{SELECT col1 AS “alias name”
FROM table2;} shows column 1 with the name “alias name” **quotations are needed when there is a space in
the new name
{SELECT col1 “alias”
FROM table2;} shows column 1 with the name “alias” **the AS keyword is optional in newer SQL
SELECT …+… FROM …: use of arithmetic equations in database using field values in specified columns
**use operators: + add; - subtract; * multiply; / divide
{SELECT col1+col2
FROM table2} shows the product of col1+col2 with the name “col1+col2”
{SELECT col1*col2 “grand total”
FROM table2;} shows product of col1*col2 with name “grand total”
DESCRIBE: shows structure of table selected (i.e. column names, data types, width)
{DESC table2;}
CREATE TABLE … AS (subquery): creates a new table from existing database tables
{CREATE TABLE table3
AS (SELECT col1, col2, col3
FROM table1);} creates a new table named “table3” and copies the data from table1 col1, col2, and col3 to the
new table; the SELECT statement within is the subquery
2
{ALTER TABLE table2
MODIFY col3 DEFAULT sysdate;} adds a default value of the system date to col3 in table2
ALTER TABLE … DROP UNUSED COLUMNS: completes deletion of any columns that were set unused
{ALTER TABLE table2
DROP UNSED COLUMNS;} permanently deletes columns that were previous set unused in table2
TRUNCATE TABLE: deletes all column rows, but maintain table name and structure (everything shown in DESC
command)
{TRUNCATE TABLE newtable2;} will erase all data within newtable2 and leave only the structure
(column names, datatypes, sizes, table name)
DROP TABLE: removes a table from the database; sends to recycling bin
{DROP TABLE newtable2;} deletes newtable2 and puts it into the recycling bin
DROP TABLE … PURGE: used to permanently delete a table straight from database
{DROP TABLE newtable2 PURGE;} permanently deletes newtable2 from the entire database
FLASHBACK TABLE … TO BEFORE DROP: recovers a dropped table if PURGE option has not yet been used
{FLASBACK TABLE newtable2
TO BEFORE DROP;} restores a table that was dropped to the database
ALTER TABLE … ADD CONSTRAINT … PRIMARY KEY (…): sets primary key constraint using given name to specified column
in specified table
{ALTER TABLE table2
ADD CONSTRAINT table2_col1_pk PRIMARY KEY (col1);} adds a primary key named “table2_col1_pk” to col1 of
table2
3
ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY (…) REFERENCES … (…): sets a foreign key constraint to specified
column in specified table using the primary key found in another table’s column to reference
{ALTER TABLE table2
ADD CONSTRAINT table2_col2_fk FOREIGN KEY (col2)
REFERENCES table1 (col1);} sets foreign key constraint named “table2_col2_fk” to col2 of table2 using the
primary key found in table1, col1
ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY (..) REFERNCES … (…) ON DELETE CASCADE: sets a foreign key just as
the original command but that key will now allow the refenced parent table to delete records that correspond to the
table with the foreign key (child table) and that deletion will also delete any records found in the child table that went
with the newly deleted record
{ALTER TABLE table2
ADD CONSTRAINT table2_col2_fk FOREIGN KEY (col2)
REFERENCES table1 (col1) ON DELETE CASCADE;} sets the foreign key as specified and allows deletion of
corresponding records from the parent table
DROP TABLE … CASCADE CONSTRAINTS: removes a table from the database even if a foreign key is referencing the table
{DROP TABLE table1 CASCADE CONSTRAINT;} deletes table1 even though another table is referencing its
primary key
ALTER TABLE … ADD CONSTRAINT … UNIQUE (…): sets a unique constraint to specified column in specified table
{ALTER TABLE table3
ADD CONSTRAINT table3_col4_uk UNIQUE (col4);} adds a unique constraint to col4 of table3
ALTER TABLE … ADD CONSTRAINT … CHECK (…): sets a check constraint to ensure the specified condition is met before
new data is entered into the table
{ALTER TABLE table3
ADD CONSTRAINT table3_col5_ck CHECK (col5 >= col4);} adds a check constraint that will prevent any data being
entered in col5 from being smaller than the data in column 4
{ALTER TABLE table3
ADD CONSTRAINT table3_col3_ck CHECK (col3 = ‘new’ OR col3 = ‘used’);}
ALTER TABLE … MODIFY (… CONSTRAINT … NOT NULL): adds a constraint to specified column in specified table that
prevents the entered data from being null (empty)
{ALTER TABLE table1
MODIFY (col1 CONSTRAINT table1_col1_nn NOT NULL);} sets a not null constraint with the name of
“table1_col1_nn” to col1 in table1
***NOT NULL cannot be set a table level, but can be set when creating a table:
{CREATE TABLE table6
(col1 CHAR (2),
col2 NUMBER (2) NOT NULL,
col3 VARCHAR2 (15));} this creates table6 where col3 cannot be null- the downside to this is that you
cannot name the constraint if created this way
4
Working with Constraints: Table Level
CREATE TABLE … (… CONSTRAINT … CONSTRAINTTYPE (…)): while creating a table this will set a constraint to the
specified column of the new table
{CREATE TABLE table5
(col1 CHAR (3),
col2 NUMBER (1),
CONSTRAINT table5_col1_pk PRIMARY KEY (col1));} this sets a primary key constraint on col1 of table
one at the time of table creation
{CREATE TABLE table5
(col1 NUMBER (4),
col2 CHAR (10),
CONSTRAINT table5_col2_fk FOREIGN KEY (col2));} sets a foreign key constraint on col2 of table5 at the
time of table creation
{CREATE TABLE table7
(col1 NUMBER (2),
col2 VARCHAR2 (10),
col3 VARCHAR2 (25),
CONSTRAINT table7_col3_uk UNIQUE (col3));} sets a unique constraint on col3 of table7 at the time of
table creation
{CREATE TABLE table6
(col1 NUMBER (3),
col2 CHAR (10),
CONSTRAINT table6_col2_ck CHECK (col2 > col1));} sets a check constraint to col2 to ensure the inputted
data is more than what is in col1
Data Manipulation
INSERT INTO … (…) VALUES (…): puts new data into table and columns specified
{INSERT INTO table2 (col1, col2, col3)
VALUES (3, ‘red’, ’02-22-22’);} adds corresponding data to field in matching columns (ex. 3 was entered to col1,
red was entered in col2)
*** this cannot be used to input into virtual columns (columns that get their value from a mathematic equation of other
columns) that data must be left out to allow the data base to determine it
INSERT INTO … (…) VALUES (..’.): puts in data that contains a single quote that will not be used by Oracle
{INSERT INTO table2 (col1, col2)
VALUES (‘Pam’, ‘O’’Hara’);} inserts the name Pam to col1 and O’Hara to col2- the second ‘ denotes to Oracle that
is not an operator but literal
INSERT INTO … (…) SELECT … FROM …: inserts specified data from another table into specified table and columns
{INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM table2;} inserts the values of col1, col2 and col3 from table2 into col1, col2, and col3 of table 1
UPDATE … SET … = ‘…’ WHERE … = ‘…’: changes the specified values in the specified columns to the new values that are
defined only in the circumstance that is specified
{UPDATE table2
SET col1 = ‘yes’
5
WHERE col3 = ‘blue’;} changes the values of col1 in table2 to “yes” if col3 is “blue”
UPDATE … SET …= ‘&…’ WHERE …= ‘&…’: opens a substitution variable to specified columns and you can enter what you
would like substituted in
{UPDATE table3
SET col1 = ‘&Col1’
WHERE col2 = ‘&Col2’;} will open prompt windows to ask what you want substituted into col1 when col2 is what
you input to the next pop-up box
DELETE FROM … WHERE …= ’…’: deletes records from the specified table where the parameter set is equal to the
inputted value
{DELETE FROM table2
WHERE col1 = ‘1’;} deletes the record in table1 the contains “1” as the value in col1
COMMIT: permanently saves the DML statements issued previously; you can run this explicitly by running the command
or it will run implicitly when you exit client tools (SQL Developer)
{COMMIT;} permanently saved all DML statements issued in database
ROLLBACK: will undo all DML statements in the current session if they have not been committed
{ROLLBACK;} undoes all DML statements that have altered the database within your current session
SAVEPOINT: creates a bookmark like save between commands that can sometimes be named
{SAVEPOINT;} saves the previous DML statement and can potentially name the save marker to use for ROLLBACK
command to undo DML statements made since
LOCK TABLE … IN SHARE MODE: locks the structure of a table, the execution of DDL operations and specific rows from
alteration but allows others to access portions of the data
{LOCK TABLE table1 IN SHARE MODE;} locks table1 into share mode so others can still access portions of the data in
table1 but cannot alter its structure
LOCK TABLE … IN EXCLUSIVE MODE: locks the data and structure of the table so that it cannot be altered and new or
addition locks cannot be placed on it
{LOCK TABLE table1 IN EXCLUSIVE MODE;} locks table1 from any data alteration or addition or deletion of locks
SELECT … FROM … WHERE … FOR UPDATE: used to lock data until an update has been rolled back or committed on the
selected data- prevents changes to the data by another user while data is being updated in another command
{SELECT *
FROM table1
WHERE col1 = ‘1’
FOR UPDATE;} selects all of the records in table1 where col1’s value is “1” for an update and locks the
data in each corresponding record until the update has been committed
{SELECT col1
FROM table1
WHERE col1 = ‘yes’
FOR UPDATE;} selects data in col1 of table1 and locks it until the update id committed only if the col1
value is ‘yes’
6
Utilizing Database Objects:
CREATE SEQUENCE …: creates a sequence with the name you have given – can be used on multiple tables all at once, but
will gap values as used- independent objects in a database
Parameters that can be used in a sequence:
INCREMENT BY: specifies the interval between two sequences values, ascending order unless negative interval is
specified – default value is 1
START WITH: establishes starting value used in a sequence – default value is 1
*if you want a 4 digit number, start with 1000 to avoid using 3 digit numbers
MINVALUE …: used to set a minimum value for a sequence, unnecessary if value is moving up as a positive
integer because the minimum would be the starting value
MAXVALUE …: used to set a maximum value for a sequence; if a MINVALUE is set on a decreasing sequence a
MAXVALUE must be set, usually as the starting value
NOMINVALUE: default value set if parameter is not specified – default is 1 in increasing values, default is -10^26
for decreasing values
NOMAXVALUE: default value set if parameter is not specified- default is 10^27 in increasing values, default is -1
for decreasing values
CYCLE: restarts the sequence if a MINVALUE or MAXVALUE is reached – cannot be used with a primary key field
NOCYCLE: default set by sequence to not reuse values after a MIN or MAX is reached and will display error when
new value is requested
ORDER: used in application cluster environments (multiple users accessing at one time), returned sequence
values in the order requests are received
NOORDER: default set in sequence that does not keep order when responding to requests
CACHE …: used to tell Oracle to generate a certain number of values in the sequence ahead of time to assign
more quickly when requests are received; generated values are lost if they go unused or the system crashes
after generation because Oracle will not generate the same value more than once in a sequence unless it has
restarted, these losses also go undocumented – default value is 20 if not specified
NOCACHE: default value set by sequence that generates the next value every time a request is received
{CREATE SEQUENCE table1_col1_seq;} creates a sequence titled table1_col1_seq – this will use default sequence
C parameters
{CREATE SEQUENCE table1_col1_seq
INCREMENT BY 2
START WITH 1000;} creates a sequence that will be used by table1 in col1 to create values starting at 1000 that
increase by 2 every time a request is fulfilled
{CREATE SEQUENCE table3_col5_seq
INCREMENT BY 1032
START WITH 2001
MINVALUE 2001
MAXVALUE 50000
NOCYCLE
ORDER
CACHE 10;} creates a sequence that will be used in table3 in col1 to create values beginning at 2001 and ending
at 50000 using an increment of 1032 and not restarting the count once the max is reached and assigning the
numbers in the order they are requested
CREATE INDEX … ON …(…): used to create a B-tree index using the specified table and column(s)
{CREATE INDEX table1_col1_idx
ON table1 (col1);}
7
Verifying Object Existence:
SELECT object_name FROM user_objects WHERE object_type = ‘…’: displays instances of a certain kind of object that
exists in your database
{SELECT object_name
FROM user_objects
WHERE object_type = ‘SEQUENCE’;} will display all sequences created within the database and display their
names
{SELECT *
FROM user_sequences;} displays all sequences created within the database and their properties
INSERT INTO … (…) VALUES (..pseudocolumn…): uses the next sequence value to input data into a table
{INSERT INTO table1 (col1, col3, col7)
VALUES (table1_col1_seq.NEXTVAL, 156, ‘blue’);} inserts the next value in the sequence named table1_co1_seq
into col1 of table1 and the following values into their respective columns
{INSERT INTO table2 (col1, col2, col3)
VALUES (1564, table2_col2_seq.CURRVAL, ‘Terry’);} inserts the current value being used by the sequence into
the specified column – does not generate a new value, used to copy information from table to table relating to
the same data
Sorting Data:
SELECT … FROM … WHERE … *comparison operator* …: displays all records where the comparison operator clause if
fulfilled
Comparison Operators:
= : equal to
> : Greater than
< : less than
<> : not equal to
<= : less than or equal to
>= : greater than or equal to
[NOT] BETWEEN … AND … : specifies a range
[NOT] LIKE : searches for patterns
Wildcards:
_ : used to signify an unidentified character space
% : used to signify an unidentified string or characters of any size
\ : used to signify a literal use of a wildcard
[NOT] IN : used like OR operator to search for records meeting at least one or the listed conditions
IS [NOT] NULL : searches for fields that are empty
{SELECT *
FROM table1
WHERE col1 = ‘Jim’;} will display all records from table1 where the col1 field in “Jim”
{SELECT *
FROM table2
WHERE col2 > 60;} will display all records from table2 where the col2 field if greater than 50
{SELECT *
FROM table3
WHERE col1-col2 > col2*.1;} will display all records where col1-col2 (revenue) is more than 10% of col2 value
{SELECT *
8
FROM table1
WHERE col1 <> ‘PA’:} will display all records from table1 where the col1 field is not set to “PA”
{SELECT *
FROM table2
WHERE col1 BETWEEN ‘A’ AND ‘F’;} will display all records from table2 where the col1 field is alphabetically
between the letters A and F
{SELECT *
FROM table3
WHERE col3 = 42 OR col5 = ‘red’;} will display all records where the col3 value is 42 or where the col5 value is
red, it will display them together in one query
{SELECT col2, col5
FROM table3
WHERE col2 IN (‘Jim’,’Linda’,’Debby’);} will display col2 and col5 from table3 of records where the col2 value is
Jim, Linda or Debby
{SELECT col2
FROM table5
WHERE col4 LIKE ‘B%’;} will display col2 values of records where col5 begins with B
{SELECT col3
FROM table5
WHERE col2 LIKE ‘10_3%’;} will display col3 of table5 where col2 value is starts as 10 has any one character and
then can be followed by any string of characters