Sie sind auf Seite 1von 11

Tips of SQL 1.

Distinct Clause : (1) must immediately follow Select (2) can be on more than 1 column (3) will then return a unique combination of the column values 2. DATA BASE DESIGN AND MODELLING 3 4 System development cycle (1) Strategy and Analysis : (2) Design user interviews, user and system requirement are gathered and analyzed

: user requirements and system specifications are applied to create a design document (ERD), flow charts etc.

(3) Build and Document : (Develop ERDs), ERDs are mapped to tables, code all program modules (4) Transition (5) Production : user acceptance testing : Perform normal routine maintenance

A relationship occurs between two entities and an entity will map into a table. ERD : entity relationship diagram Consult exam cram pg 271 Relationship must be valid in both directions (one to many, many to many) and must show optimality (may be, must be). PK and FK relationships are collectively termed as referential integrity Normalization? UID (unique identifier) : # PK * Candidate key o Column constraints : Data validity(enforce typing rules), NULL and NOT NULLtype constraints User defined constraints : to enforce business rules Referential constraints : data concurrency. (there is nothing like entity constraints) 2. Order by : default asc, if null then returned in end in default(asc) : last in query, the column may not necessary to in select statement : will override group by : order by avg(price) allowed : sort by no. that matches column no in the select statement, sort by column alias also, sort by column which might not be in select expression
1

3. Nested subquery: No order by allowed (order by should appear in the end of the main select) Nesting limits 255 Nested query in parenthesis Can appear in S, I, U, D, create table statements Can use set operators Group by and having allowed Examine: Select ename, sal, deptno From emp Where (sal, deptno) In (select min(sal), deptno from emp group by deptno) If subquery return more than one row In operator otherwise error (=) If subquery returns no rows then error 4. Alter password: Alter user user_name identified by password 5. Which privilege can only be granted to a user : index (others can be granted to user and ROLE. References SQL Plus: SQL plus is an environment from where two kind of commands can be issued: 1. SQL command eg. Select 2. SQL*Plus commands eg. Save : not related to particular select stat : should be in single line (hyphen for continuation) SQL*Plus Command Run form filename, Spool file name (.lis or .lst ext), Spool on|off (send spool file to printer), desc table name, help, $0/S command (eg, host command) : invokes an operating system cmd from within sql plus, Connect, prompt txt diaplays text when running a command file

Set commands : control the environment of SQL plus by assigning a value to a system avriable. Default set of commands can be made and included in a login.sql which is read every time. To see the set commands : show all, show command Maximum no. of parameters report can accept : 9 The structure of the views can also be seen like table : desc view Structure of for and while loop : Syntax of Index Cursor fuctioning Date funtions Drop table table_name, drop view view_name SQL Buffer termination : /, ;/ return twice Spool out : The result of the next SQL query will be sent to the printer within quotes : exactly the same, if not then appear in upper case Column order_date NULL not ordered : specified text to be displayed for null values Equi join is also known as inner join In the outer join which side you put the + sign Non-equi join How many sequential value will the oracle7 preallocate and keep in memory : 20 Like _a% will search name containing a as the second letter Indexes: (1) PK or unique constraint columns : index created automatically (DBA_INDEXES) (2) Manual Indexes : user create by create user. Once created then indistinguishable by the automatic ones. However by using all_cons_column and all_constraints you can distinguish it. Up to 16 columns can be included in a single index Index can be created on columns except long data type. Index Structure : B-tree (max 20 trees, one million values) look up data ROWID and bitmap index
3

B-tree indexes Create index index_name On employee (lastname)

can contain null value

Create unique index index_name On employee (lastname, can include more like firest_name) Bitmap indexes : create bitmap index index_name onemployee (last_name) Once indexes are created then only little alteration is possible. So for changes drop and recreate. All_indexes : storage inf., table name All_objects : status etc All_ind_columns : columns that are indexed Use B-tree indexes for high cardinality and bitmap for low cardinality. Truth table : Not : make reverse AND : False Null True OR : True Null False Char :255 (default is 1) Number : Precision maximum 38

Alter table : (ADD, MODIFY, DROP)

and ENABLE, DISABLE options

Set auto(commit) on : commit issued automatically after DML Sel auto(commit)off : you have to commit it. Views: Simple : data from one table, no grouping Complex: derived form many tables, grouping allowed A view can not contain order by clause With check option : (restrictions imposition) inserts and deletes performs through the views are not allowed to create rows which the view can not select\ Delete, update and insert are not allowed if the view contains group by clause
4

Indexes, pseudocolumns are not allowed PL/SQL Basics: Numerous predefined exceptions need not to be declared. However, user_defined errors need to be declared. User_defined exceptons must be explicitly called using the raise command. Implicit exceptions are invoked automatically when they occur. Pragma declaration: A pragma exception_int decaration usually goes hand in hand with the exception declaration. A pragma is a PL/SQL interpreter directive that remaps standard oracle errors into user_defined errors. Pragma exception_init(exception_name, error_number); Cursor for LOOP : For rec_id in cursor_id Loop --processing end loop No Open, fetch or close commands are required.

Cursor with parameters (parameters are expressed in the where clause) Null is the only executable command that does nothing Procedure Builder : Tool to help creation, debugging and testing of PL/SQL block, Interpretor, Object navigator, program unit editor. Debug actions are of two general types-breakpoints and debug triggers. Breakpoints suspend execution at a specific source line of a programunit and control is passed to the intrepreter. A breakpoint suspends operation just before a specific line of control, allowing you to step into the rest of the program unit. The GO to STEP command is used to resume execution of the program unit after a breakpoint is reached. A breakpoint can also automatically invoke a breakpoint trigger. The breakpoint trigger is a PL/SQL block thats executed when a breakpoint is reached. A debug trigger is a trigger thats fired when a specific line of PL/SQL code is reached. Order of Evaluation: **, NOT, *, / , Soft) (+ _ || ) , ( is null, like between, in) , AND , OR (Ref: Advant

Host variable, eg. Bind variable What is a header : header is in a subprogram such as procedure (before begin is known as header). OBJECT PRIVILEGES: Select snapshot Insert, update, delete : Alter : Index, references : Table, views, sequence,

Table, views Table, sequences : Table

SUBSTR :

(qwjdq4223, 4,4) (fdew3545, -4,4) CREATING TABLES AND COLUMNS

(1) Table name must begin with a letter, A-Z or a-z (unless surrounded by double quotes eg: 3eMp , Desc 3eMp-exact letter case required when referenced). Oracle user must be given CREATE TABLE priv. And have been assigned some tablespace in order to create tables. (2) Name alphanumeric (letter and number)- can not contain anything else (except $, # , _ ) (3) Upto 30 characters (4) Must not duplicate the name of other object in your account (5) Must not be a sql reserved word eg: UPDATE. No blank spaces. (6) Columns : name must begin with a letter. Column name within one table must be unique. varchar2 : 2000 (No default). Varchar2 col. MUST have size specified. For NUMBER (38 max.) and CHAR (255 max, default 1) defaults are available. If not sure of size of NUMBER datatype which keeps changing, dont specify size. NUMBER : 38 max. Can be eg. 4, 4.45 or 4.5678. NUMBER(P) : No decimals. NUMBER(P,S): LONG : Variable length upto 2GB or 231-1. Only one LONG col/table. (7) Default option : Column may be given a default value. This prevents nulls (or errors if NOT NULL is specified) when a row is inserted without a value for the col. Eg. Hiredate date default sysdate, Sal number(7,2) default 0. Defaults can be literals, an expression but not name of another col. Functions such as sysdate and user are valid. Also can be specified after creation of table by ALTER TABLE emp MODIFY(hiredate date default sysdate). CONSTRAINTS: -Unique and NOT NULL constraints are implicitly defined on a PRIMARY Key column. -An index is automatically created with Unique and primary key constraint. -Unique key can have Null values if based on a single a column. -Same combination of columns cannot be used for both a primary and a unique key. -A foreign key is used in a relation with either a primary or unique key elsewhere. -NOT NULL constraint can ONLY be defined at column level others can be both col. and table level. -Only CHECK constraint can be defined at column or table level and can apply to any column in the table, not just on which it is defined. i.e. whether defined as a table or col. constraint, it may reference several columns within the table eg: CHECK (Sal + Comm <=5000). Disable option: While creating table, you can add disable to a constraint definition (the constraint can still be read by ORACLE tools to construct rules in an application). You can enable the constraint later by ALTER TABLE command. Creating a table with rows from another table : -Constraint information is inherited; Copying table can come from more than one table.

-When datatypes specified in new table definition, Oracle gives error may not specify column datatypes in this create table. -constraint information (PK etc.) may be given in new table definition. COMMENT Command: Comment (upto 255 characters) can be inserted about a table or view or a column into the data dictionary. (select comments col. from ALL/USER_COL_COMMENTS or xxxx_TAB_COMMENTS).

ALTER ING TABLES AND CONSTRAINTS ALTER TABLE tablename 4 Clauses (1) ADD adds a new coumn or a new constraint to existing col. ADD (column_name datatype() [NULL/NOTNULL], -adds a new column Primary key (col,col..), -adds table constraints on existing columns Unique (col, col..), Foreign key (col,col..) references table_name (col, col..) Check (condition)) (2) MODIFY modifies definition of existing col. i.e. modify datatype(if empty), increase size, decrease size(if empty), not null to null, NULL to NOT NULL (if col. contains no null values). ALTER TABLE table_name MODIFY (Col_name datatype() NULL/NOT NULL) -To change datatype and to decrease col. size, col. MUST be EMPTY though the size can be increased with data. - Col. containing NULLS connot be changed from NULL to NOT NULL. - Modify option canNOT be used to define constraints on a col. except NULL/NOT NULL. To modify other type of constraints DROP it and then ADD it. -CANNOT add a new NOT NULL if table contains data. Gives Oracle error table must be empty to add mandatory (not null) column. So, make it NULL, fill it completely and then change it to NOT NULL. (3) DROP CONSTRAINT constraint_name [CASCADE] Cascade option Drops any dependent constraint also. DROP PRIMARY KEY DROP UNIQUE (COL,COL..) (4) ENABLE/DISABLE CONSTRAINT constraint_name [CASCADE] PRIMARY KEY UNIQUE (col, col)

DROP TABLE table_name [CASCADE CONSTRAINTS] will remove dependent referential integrity constraints. Dropping a table removes table definition, all data and all indexes associated. Any views or synonyms remains but becomes invalid. Pending transactions are commited. Only creator of table or DBA can drop it.
7

ROLES and PRIVILEGES Changing Password: Alter User username identified by password; -When you use REVOKE, the privileges you specify are revoked from the users you name, and from any other users to whom they have granted those privileges. -A role can be granted to another role Grant Clerk to Manager; role manager will acquire all the properties of role Clerk. USER_ROLE_PRIVS -list of roles granted to the user. SESSION_ROLES -list of roles enabled in current session.

VIEWS -derived from another table or view. -stored as SELECT statement only. When CREATE VIEW command is executed the SELECT statement which follows AS is not executed; instead it is simply stored in data dictionary. -USER_VIEWS (set parameters maxdata, arraysize-to a smaller value(eg:1), Long).-Text stored in a col. of LONG datatype. Simple views Complex Views Based on one table. -derived from many tables. Contains no functions or GROUPS of data. -contains functions or GROUPs of data.

CREATE [OR REPLACE] [FORCE] VIEW view-name [(col,col)] AS SELECT statement [WITH CHECK OPTION [CONSTRAINT constraint-name]] -alternative col_names MUST be specified in the view def. when column_names selected in select clause contains functions, expressions or it does not follow standard table/column naming conventions. Eg. Select min(sal), max(sal), sal * 12 . -If a col alias is used in a query (ANNSAL), a view column alias is NOT required. eg. Create view emp1 as select ename, sal*12 ANNSAL.. **View cannot contain an ORDER BY clause. When you select from view it can be used. -View can be altered without dropping, recreating and regranting object privileges by OR REPLACE option. -FORCE Option creates view even if table does not exist, or there are insufficient table privileges. However, table must exist before view may be used. -WITH CHECK OPTION clause no DML statement (INSERT/UPDATE) can successfully reference the view unless the WHERE clause conditions of the view are met. OTHER Restrictions when altering data thru a view:=
8

DELETE: prohibited if view contains: 1)complex view things:a) Join condition b) Group functions c) GROUP BY clause 2)DISTINCT command 3)ROWNUM UPDATE: prohibited if view contains: 1) any of above 2) columns defined by expressions (eg: sal*12) INSERT: prohibited if view contains: 1) any of above 2) Any NOT NULL columns are not selected by view (eg: empno). DROP VIEW view_name

SEQUENCE generator CREATE SEQUENCE [user.] sequence_name [increment by n] default 1 (if increment value is positive, seq. will ascend, if increment is ve, seq. Descend [start with n] default 1 for ascending and MAXVALUE for descending (default 1). [maxvalue n/ nomaxvalue] default 10e27-1 for ascending, 1 for descending. [minvalue n/ nominvalue] default 1 for ascending sequences, 10e27-1 for descending. [CACHE] [CYCLE/ NOCYCLE] (col_name not specified in create clause since the unique sequence is are generated automatically for the primary key col) RESOURCE privilege required to create a sequence. Insert into dept values (dept_seq.NEXTVAL, ACCOUNTING, NEW YORK); Select dept_seq.NEXTVAL from sys.dual; Psuedocol. CURRVAL (current sequence no. i.e. that has just been generated or that has last been returned to that users process). NEXTVAL must be used to generate a seq. no. in the current user session before you can reference CURRVAL. Insert into dept values (dept_seq.CURRVAL, ACCOUNTING, NEW YORK); RULES for using NEXTVAL and CURRVAL: May be used within: 1) SELECT clause of a select statement (except for view). 2) VALUES list of INSERT statement. 3) SET clause of UPDATE statements. 4) Outermost SELECT (main query) of a subquery. Restrictions: may not be used: 1) In SELECT list of a view. 2) With keyword DISTINCT
9

3) With the ORDER BY, GROUP BY, CONNECT BY, or HAVING clauses of select statement. 4) With set operators- UNION, INTERSECT, MINUS 5) within a subquery. Sequences are treated in a similar way to tables and can be altered or dropped. ALTER SEQUENCE [user.] sequence_name [increment by n] [maxvalue n/ nomaxvalue] cannot be less than the current seq. no. [minvalue n/ nominvalue] Eg: ALTER SEQUENCE dept_seq Maxvalue 100000 [start with] CANNOT be changed using alter seq. command. The seq. must be dropped and recreated in order to restart at a different no. To modify a seq. must have ALTER privil. On the sequence by the owner. ALTER or SELECT priv. can be granted by the owner on sequence WITH GRANT OPTION. USER_SEQUENCES , ALL_SEQUEMCES. DROP SEQUENCE [user.] seq_name INDEXES Types UNIQUE ensures values are unique in specified col. NON UNIQUE -ensures fastest performance query results(default). SINGLE COLUMN -only one col exists in index. CONCATENATED upto 16 cols. included in a single index, for either performance or uniqueness check purposes. UNIQUE Index: created automatically on primary key and unique constraint col. Index created manually: CREATE [UNIQUE] INDEX index_name ON table_name (col,col.) Rule-based use of Indexes by oracle optimizer:= -Indexed col. must be referenced in WHERE clause. It should not be a part of a function or expression. Eg: where UPPER(ename)=JONES or where hiredate+7= 01-JAN-84 Cost-based use of Indexes by oracle optimizer:=above+some calculations. Indexing Suggestions:= 1) Index col. frequently used in WHERE clause including JOIN cols. 2) Create CONCATENATED index, if two or more cols. are frequently used together in WHERE or JOIN conditions. Generally, cols. used in join conditions should be indexed. 3) Index all cols. where unique values required.

10

4) Avoid more than 3 indexes/table. (not apply for reference table on which only SELECT is common operation). 5) A table with more than 200 rows will benefit from indexing if less than 10% rows are to be returned by a query. EXPLAIN PLAN facility: execution plan for an SQL statement can be requested and written to a table. USER_INDEXES. Select table_name, index_name from user_indexes. DROP INDEX index_name.

11

Das könnte Ihnen auch gefallen