Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

-CAN KAYIM HAYRATI-

DATA TYPES
-VARCHAR2(size): variable-length character data
-CHAR(size): fixed-length character data
-NUMBER(p,s): p digits, s decimal digits
-DATE: date and time value between Jan 1 4712 BC and Dec 31 AD 9999
-LONG: variable-length character data (up to 2 GB)
-CLOB: character data (up to 4 GB)
-RAW and LONG RAW: raw binary data
-BLOB: binary data (up to 4 GB)
-BFILE: binary data stored in an external file (up to 4 GB)
-ROWID: a base-64 number system representing the unique address of a row in its
table

LOGICAL OPERATORS
-AND Syntax: { ... WHERE ... AND ... }
-OR Syntax: { ... WHERE ... OR ...}
-NOT Syntax: { ... WHERE ... NOT (IN, BETWEEN, LIKE)}

Data Manipulation Language


-SELECT
-INSERT
-UPDATE
-DELETE
-MERGE
Data Definition Language
-CREATE
-ALTER
-DROP
-RENAME
-TRUNCATE
-COMMENT
Data Control Language
-GRANT
-REVOKE
Transaction Control
-COMMIT
-ROLLBACK
-SAVEPOINT

----------------------------

DISTINCT = exclude duplicate rows (you may also use UNIQUE)

DESCRIBE(DESC) = displays table structure

LIKE = '%': represents any sequence of zero or more characters '_': represents any
single character

ESCAPE = identifies escape character. Syntax: { ... ESCAPE '\'; }

IS NULL, IS NOT NULL: tests for nulls. Syntax: { ... WHERE ... IS (NOT) NULL; }

BETWEEN = displays values in a range. Syntax: { ... WHERE ... BETWEEN ...
AND ...; }

ORDER BY = sorts datas -ASC: ascending order(min first) -DESC: descending order
(max first)
DEFINE = assigns a value to a var. UNDEFINE = removes assigned value

----------------------------------

Case-Coversion Functions
-LOWER: converts to lower case ex: LOWER('SQL Course'):
sql course
-UPPER: converst to upper case ex: UPPER('SQL Course'):
SQL COURSE
-INITCAP: only converts first char to upper, rest is lower ex: INITCAP('SQL
Course'): Sql Course

Character-Manipulation Functions
-CONCAT: same as || ex:
CONCAT('Hello', 'World'): HelloWorld
-SUBSTR: returns part of the value. m: index, n: count
ex: SUBSTR('HelloWorld',1,5): Hello
-LENGTH: returns length ex:
LENGTH('HelloWorld'): 10
-INSTR: returns numeric position of a named string m: starting index, n: nth
occurence ex: INSTR('HelloWorld', 'W'): 6
-LPAD | RPAD: returns an expression left or right padded m:length, n: blank
ex: LPAD(salary, 10, '*'): *****24000, RPAD(salary, 10, '*'): 24000*****
-TRIM: trims ex: TRIM('H'
FROM 'HelloWorld'): elloWorld
-REPLACE: replaces specified string ex:
REPLACE('JACK and JUE', 'J', 'BL'): BLACK and BLUE

Numeric Functions
-ROUND: rounds value to a specified decimal ex: ROUND(45.925, 2): 45.93,
ROUND(45.924, 2): 45.92, ROUND(45.923, 0): 46, ROUND(45.923, -1): 50
-TRUNC: truncates value to a specified decimal ex: TRUNC(45.929, 2): 45.92,
TRUNC(45.923): 45, TRUNC(45.923, -1): 40
-MOD: returns remainder of division ex: MOD(1600, 300): 100

Date-Manipulation Functions

-MONTHS_BETWWEEN: number of months between two dates ex: MONTHS_BETWEEN('01-SEP-


95', '11-JAN-94'): 19.67...
-ADD_MONTHS: add calendar months to date ex: ADD_MONTHS('31-JAN-96', 1):
'29-FEB-96'
-NEXT_DAY: next day of the date specified ex: NEXT_DAY('01-SEP-95',
'FRIDAY'): '08-SEP-95'
-LAST_DAY: last day of the month ex: LAST_DAY ('01-FEB-95'): '28-
FEB-95'
-ROUND SYSDATE: '25-JUL-03' ex: ROUND(SYSDATE, 'MONTH'):
01-AUG-03, ROUND(SYSDATE, 'YEAR'): 01-JAN-04
-TRUNC SYSDATE: '25-JUL-03' ex: TRUNC(SYSDATE, 'MONTH'):
01-JUL-03, TRUNC(SYSDATE, 'YEAR'): 01-JAN-03

Group Functions
-AVG: average value of n
-MAX: maximum value of expr
-MIN: minimum value of expr
-STDDEV: standart deviation of n
-SUM: sums all values
-VARIANCE: variance of n
-COUNT: counts num of rows
-------------------------------------

CASE = for conditional expressions Syntax: {... CASE ... WHEN ... THEN ...
WHEN ... THEN ... ELSE ... END "..." ...;}

DECODE = similar to CASE Syntax: look at final_codes.txt

GROUP BY = groups datas as wanted Syntax: { ... GROUP BY ...;}

HAVING = restricts results Syntax: { ... GROUP BY ... HAVING ...;}

-------------------------------------

JOINS

-NATURAL JOIN: joins table columns with same column name Syntax: { ... natural join
<table name>; }

-LEFT OUTER JOIN: joins all from left table

-RIGHT OUTER JOIN: joins all from right table

-FULL OUTER JOIN: joins all from right and left

-CROSS JOIN: cross-product of two tables (table 1 has 10 rows, table 2 has 8 rows)
total row 8*10 = 80

-------------------------------------

Set Operators

-UNION: rows from both queries after eliminating duplications


-UNION ALL: rows from both queries including all duplications
-INTERSECT: rows that are common to both queries
-MINUS: rows in the first query that are not present in the second query

-------------------------------------

Manipulating Data (tables)

-INSERT INTO: inserts a new row Syntax(single row): { INSERT INTO


"table_name"("column_names") VALUES ("values"); }
Syntax(multiple rows): { INSERT INTO
"table_name"("column_names") SELECT "column_names" FROM "table_name" WHERE ...; }
-UPDATE: modifies existing values Syntax: { UPDATE "table_name" SET
"column_name" WHERE ...; } note: if you omit where clause, it modifies all rows!

-DELETE: deletes row Syntax: { DELETE FROM "table_name" WHERE ...;


} note: if you omit here clause, it deletes all rows!

-TRUNCATE: removes all rows Syntax: { TRUNCATE TABLE "table_name"; }

-COMMIT: saves changes

-SAVEPOINT 'name': creates a savepoint

-ROLLBACK: discards all pending changes and returns last committed point or default
table
-ROLLBACK TO SAVEPOINT 'name': returns to savepoint

-------------------------------------

Database Objects

-TABLE: basic unit of storage


-VIEW: logically represents subsets of data from one or more tables
-SEQUENCE: generates numeric values
-INDEX: improves the performance of some queries
-SYNONYM: gives alternative name to an object

----

-CREATE TABLE: creates table Syntax: { CREATE TABLE "table_name"


("column_name datatype [default expr]") }

Constraints

-NOT NULL: specifies that the column cannot contain a null value
-UNIQUE: specifies a column or combination of columns whose values must be unique
for all rows in the table
-PRIMARY KEY: uniquely identifies each row of the table
-FOREIGN KEY: used to match values between tables
-CHECK: specifies a condition that must be true

Example usage of CONSTRAINT: CREATE TABLE employees(


employee_id NUMBER(6),
first_name VARCHAR2(20),
department_id NUMBER(4),
email VARCHAR(25),
salary NUMBER(2),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_salary_min
CHECK (salary > 0),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk
UNIQUE (email),
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (employee_id)
);

-ON DELETE CASCADE: deletes row in the child table when a row in parent table
deleted
-ON DELETE SET NULL: converts dependent foreign key values to null

-----------------------------------------

-CREATE VIEW: represents subsets of data from one or more tables SYNTAX: { CREATE
(OR REPLACE) VIEW table_name (column_name) AS SELECT
DROP VIEW view_name: removes view column_name
FROM table_name WHERE ...; }

-SEQUENCE: generates numberic values SYNTAX: { CREATE


SEQUENCE seq_name INCREMENT BY number START WITH number;}
NEXTVAL: gives next available value
CURRVAL: obtains the current sequence value

ALTER SEQUENCE: modifies sequence SYNTAX: { ALTER SEQUENCE


seq_name INCREMENT BY number; }
DROP SEQUENCE seq_name; removes sequence

-INDEX: improves the performance of some queries SYNTAX: { CREATE INDEX


index_name ON table_name(column_name); }
DROP INDEX index_name: removes index

-SYNONYM: gives alternative names to objects SYNTAX: { CREATE


SYNONYM synonym_name FOR object_name}
DROP SYNONYM synonym_name: removes synonym

-------------------------------------------

Typical DBA Privilages

-CREATE USER: creates user


-DROP USER: drops user
-DROP ANY TABLE: can drop a table in any schema
-BACKUP ANY TABLE: can back up any table in any schema with the export utiliy
-SELECT ANY TABLE: can query tables, views or materialized views in any schema
-CREATE ANY TABLE: can create tables in any schema

User Privilages That Can Be Granted By DBA

-CREATE SESSION: connect to the database


-CREATE TABLE: create table in the user's schema
-CREATE SEQUENCE: create a sequence in the user's shema
-CREATE VIEW: create a view in the user's schema
-CREATE PROCEDURE: create a stored procedure, function or package in the user's
schema

-----DBA----

CREATE USER: creates user Syntax: { CREATE USER user_name


IDENTIFIED BY password; }
GRANT: to grant privileges to users or roles Syntax: { GRANT (user_privilege
or role_name) TO (user_name or role_name); }

CREATE ROLE: role is named group of related privilages that can be granted to the
user
Syntax: { CREATE ROLE role_name; }

note: you can change your password by 'ALTER USER user_name IDENTIFIED BY
password;'!!!

---

Object Privilages

-ALTER, DELETE, INDEX, INSERT, REFERENCES, SELECT, UPDATE


Syntax: { GRANT object_priv (column_name) ON object TO [user|role|PUBLIC] [WITH
GRANT OPRION]; }
Ex: GRANT select ON employees TO demo;
GRANT update (department_name, location_id) ON departments TO demo, manager;
GRANT select, insert ON departments TO demo WITH GRANT OPTION;
GRANT select ON alice.departments TO PUBLIC;
Confirming Granted Privilages

-ROLE_SYSTEM_PRIVS: system privileges granted to roles


-ROLE_TAB_PRIVS: table privileges granted to roles
-USER_ROLE_PRIVS: roles accessible by the user
-USER_SYS_PRIVS: system privileges granted to the user
-USER_TAB_PRIVS_MADE: object privileges granted on he user's objects
-USER_TAB_PRIVS_RECD: object privileges granted to the user
-USER_COL_PRIVS_MADE: object privileges granted on the columns of the user's object
-USER_COL_PRIVS_RECD: object privileges granted to the user on specific columns

REVOKE: revokes privilages Syntax: { REVOKE privilage ON object FROM (user|


role|PUBLIC) [CASCADE CONSTRAINTS]; }
Ex: REVOKE select, insert ON departments FROM demo;

-------------------------------

ALTER TABLE: used to add, modify or drop columns Syntax: { ALTER TABLE
table_name (ADD|MODIFY|DROP)
(column_name datatype); }
Adding Constraints

ex: ALTER TABLE emp2 ADD CONSTRAINTS emp_mgr_fk FOREIGN KEY (manager_id) REFERENCES
emp2(employee_id);
ex: ALTER TABLE emp2 MODIFY employee_id PRIMARY KEY;
ex: ALTER TABLE emp2 ADD CONSTRAINT emp_dt_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id) ON DELETE CASCADE;
ex: ALTER TABLE emp2 ADD CONSTRAINT emp_dt_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id) ON DELETE SET NULL;

Dropping Constraints

ex: ALTER TABLE emp2 DROP CONSTRAINT emp_mgr_fk;


ex: ALTER TABLE dept2 DROP PRIMARY KEY CASCADE;

Disabling and Enabling Constraints

ex: ALTER TABLE emp2 DISABLE CONSTRAINT emp_dt_fk;


ex: ALTER TABLE emp2 ENABLE CONSTRAINT emp_dt_fk;

Cascading Constraints

ex: ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS;


ex: ALTER TABLE test1 DROP (col1_pk, col2_fk, col1) CASCADE CONSTRAINTS;

Renaming Table Columns and Constraints

ex: ALTER TABLE marketing RENAME COLUMN team_id TO id;


ex: ALTER TABLE marketing RENAME CONSTRAINT mktg_pk TO new_mktg_pk;

---

FLASHBACK TABLE: recovers tables from bin Syntax: { FLASHBACK TABLE table_name TO
BEFORE DROP; }
note: to see dropped tables use 'SELECT * FROM recyclebin;'!

-----------------------------------
View Naming

-USER: user's view


-ALL: expanded user's view
-DBA: dba's view
-V$: performance-related date

-COMMENT: just a normal comment Syntax: { COMMENT ON TABLE table_name


IS '...'; }
Syntax: { COMMENT ON COLUMN table_name.column_name
IS '...'; }
------------------------------------

Retrieving Data by Using a Subquery as Source

ex: select department_name, city from departments natural join (


select l.location_id, l.city, l.country_id from locations l join countries c
on(l.country_id=c.country_id) join regions using(region_id)
where region_name = 'Europe');

Inserting by Using a Subquery as a Target

ex: insert into (select l.location_id, l.city, l.country_id from locations l


join countries c on (l.country_id = c.country_id) join regions using
(region_id)
where region_name = 'Europe') values (3400, 'Cardiff', 'UK');

Using WITH CHECK OPTION Keyword

ex: insert into (select location_id, city, country_id from locations where
country_id in
(select country_id from countries natural join regions where region_name =
'Europe')
with check option) values (3600, 'Washington', 'US');
note: this is not going to work because of logical mistakes

-----

Insert Types

-Unconditional INSERT: for each row returned by the subquery, a row is inserted
into each of the target tables
-Conditional INSERT ALL: for each row returned by the subquery, a row is inserted
into each target table if the specified condition is met
-Pivoting INSERT: This is a special case of the unconditional INSERT ALL
-Conditional INSERT FIRST: for each row returned by the subquery, a row is inserted
inte the very first target table in which
the condition is met

ex: INSERT ALL


WHEN HIREDATE < '01-JAN-95' THEN
INTO emp_history VALUES(EMPID, HIREDATE, SAL)
WHEN COMM IS NOT NULL THEN
INTO emp_sales VALUES (EMPID, COMM, SAL)
SELECT employee_id EMPID, hire_date HIREDATE, salary SAL,
commission_pct COMM
FROM employees;
Pivoting Insert ex: INSERT ALL
INTO sales_info VALUES (employee_id, week_id, sales_MON)
INTO sales_info VALUES (employee_id, week_id, sales_TUE)
INTO sales_info VALUES (employee_id, week_id, sales_WED)
INTO sales_info VALUES (employee_id, week_id, sales_THUR)
INTO sales_info VALUES (employee_id, week_id, sales_FRI)
SELECT EMPLOYEE_ID, week_id, sales_MON, sales_TUE, sales_WED,
sales_THUR, sales_FRI
FROM sales_source_data

You might also like