SQL
SQL
A database management system (DBMS) is a software package with computer programs that control the creation, maintenance, and the use of a database. What is a RDBMS? A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. A short definition of an RDBMS is: a DBMS in which data is stored in tables and the relationships among the data are also stored in tables. The data can be accessed or reassembled in many different ways without having to change the table forms. Example: Oracle, MS SQL Server, NCR Teradata, IBM DB2, MySQL, MS Access, SyBase etc. Most popular databases currently in use are based on the relational database model. What is a Database? Databases are designed to offer an organized mechanism for storing, managing and retrieving data/information. They do so through the use of tables. Database FrontEnd User End User www.irctc.co m (or)
Oracle 11g/ 10g/ 9i/ 8i Teradata V2R6.0/ V2R5.0 MSSQL 2008/ 2005/ 2000 IBM DB2 9.7/ 9.5/ 9.1/8 MySQL 6.0/ 5.5/ 5.4/ 5.1/ 5.0 MS Access 2010/ 2007/ 2005 SyBase 12/11 etc.
What is a database schema? Pronounce skee-ma, the structure of a database system, described in a formal language supported by the database management system (DBMS). In a relational
database, the schema defines the tables, the fields in each table, and the relationships between fields and tables. Example: Sales Schema
What is a table? The foundation of every RDBMS is a database object called table. Every database consists of one or more tables, which store the data/information. Each table has its own unique name and consists of columns and rows. The database table columns (also called table fields) have their own unique names and have a pre-defined data types. The table rows contain the actual data for the columns. Here is an example of a simple database table, containing employee data. The first row, listed in bold, contains the names of the table columns: Table: Employees Column First_Name John Steven Paula James Column Last_Name Smith Goldfish Brown Smith Column Email [email protected] [email protected] [email protected] [email protected] Column DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980
What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. The standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", "Alter" and "Drop" can be used to accomplish almost everything that one needs to do with a database. DDL Data Definition Language Used to CREATE or ALTER Tables, Views, Indexes etc. DML Data Manipulation Language Used to SELECT, INSERT, UPDATE, DELETE data from tables
Selecting Data from a table The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1" ,"column2"etc from "tablename" [where "condition"]; [] = optional To select all columns, use * e.g. select * from employees. Where clause is used to filter data. E.g: select * from employees where last_name = 'Smith' Creating a DB table The create table statement is used to create a new table. Here is the format of a simple create table statement: create table "tablename" ("column1" "data type", "column2" "data type", "column3" "data type"); There are different types of data type e.g. NUMBER VARCHAR2 BINARY FLOAT DATE Eg: create table EMP_SAMPLE (EMP_ID number, EMP_NAME Varchar2(30), EMP_START_DATE DATE) Note: If you any of the insert, update or delete statements, you must commit (means save) or rollback (means revert). INSERT Statement The insert statement is used to insert or add a row of data into the table. To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis(, followed by a list of column names separated by commas, followed by a closing parenthesis), followed by the keyword values, followed by the list of values enclosed in parenthesis. Rules: The order of values should match up with the column names order that you specify.
Strings should be enclosed in single quotes Numbers and dates should not. insert into "tablename" (first_column,...last_column) values (first_value,...last_value); Eg: insert into EMP_SAMPLE (E_ID,EMP_NAME) values (101,MyName); commit; * If you want to enter values in all the columns of a table , then you dont have to specify column names. Eg: insert into EMP_TARGET values (102,MyName, sysdate) UPDATE Statement The update statement is used to update or change records that match a specified criteria. This is accomplished by carefully constructing a where clause. update "tablename" set "columnname" = "newvalue" [,"nextcolumn" = "newvalue2"...] where "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"]; e.g. update EMP_SAMPLE set EMP_NAME = 'Smith', where EMP_ID = 101; commit; * if you dont specify where cluase in the update statement, the value will be updated for all the rows of that column. e.g. update EMP_SAMPLE set EMP_NAME = 'Smith', rollback; Delete Statement The delete statement is used to delete records or rows from the table. delete from "tablename" where "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"]; e.g : delete from EMP_SAMPLE where EMP_NAME = 'Smith'; commit;
Commit and Rollback When DML statements like DELETE, UPDATE, INSERT are executed on a table, data is not truly saved (i.e. committed) to the table until COMMIT is executed. Remember to commit your data changes using COMMIT command. If you accidentally changed data in a table using DMLs like INSERT/UPDATE/DELETE and if you have not committed the changes yet, then you can use ROLLBACK command to get the old data back into the table. Never leave un-committed data in a table either COMMIT or ROLLBACK. (Reason: Un-committed transactions create table locks!) FROM Keyword: This keyword is used to determines the data source at the time of retrieving data. Eg : Select employee_id, first_name FROM employee; WHERE statement: y This is used to filter the records from an sql statements
Syntax: Select column1, column2 , column3 .. FROM employee Where <condition>; Example: Select EMP _NAME, EMP_ID, from EMP _SAMPLE Where EMP _NAME=smith; Delete EMP _NAME, EMP_ID from EMP _SAMPLE Where EMP _ID=102; y y Here only one record will be deleted IF we omit the where condition all the records will be deleted
Example: Update EMPLOYEE set EMP _ID=111 where EMP _ID=102; Commit; *If we dont use where condition all the records will be updated. NOTE : we can not use group function in where clause. Eg: Select EMP_ID,EMP_NAME, count(EMP_ID) from employee Group by EMP_ID,EMP_NAME where count(EMP_ID)>3; *It will give error
Group by Clause: Group By clause is used to divide the output of a query into groups. Syntax: Select column1, column2, group _function ( column name ) from Table name [Where <condition>] [Group by column1, column2]; Example: Select job from employee group by job; Example: Select EMP_NAME,EMP_ID from EMP_SAMPLE Group by EMP_NAME , EMP _ID; Example: Select TO _CHAR ( HIRE_DATE , YYYY ) YEAR GROUP from EMPLOYEES Group by TO _CHAR( HIRE_DATE, YYYY ); Rules: y y y y Columns present in select statement must be there in group by clause. All group by clause column list may or may not used in select clause. Column aliases cannot be used in select statements. Extra non group function is used in a select clause , we should not use individual result columns.
ORDER BY CLAUSE: Order by clause can be used to sort the rows. Syntax: Select column1, column2. From table name [Where conditions] Order by columns ASC/DESC; ASC: Ascending order, it displays the output in ascending order
DESC: Descending order, this command will display the output in descending oder. Example: Select EMP _NAME, EMP _ID from EMP _SAMPLE ORDER BY EMP _ID; Example: Select FIRST_NAME, EMPLOYEE_ID, PHONE from EMPLOYEE ORDER BY EMPLOYEE_ID DESC; Example: Select emp _id, emp _name from emp _sample Order by 2; *It will sort based on emp _name because emp _name position is 2.
Rules: y y y y The ORDER BY clause must be the last clause of the sql statement. An expression, an alias, column position can be used as the sort Condition, but the position value must be existing in the select list. The default order is ascending order.
HAVING CLAUSE: The having clause is used to filter data is associated with group function. Syntax: Select [column], group _function (column) From table name [Where condition] [Group by group _by _expression] [Having having _expression] [Order by column/alias]; Example: Select EMP _NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLE Group by EMP_ID having count (EMP_ID)>3; NOTE: We can use count/group function in having clause, but group function Cannot be used in where clause. Example: select EMP _NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLE Group by EMP_ID where count (EMP_ID)>3; *It gives Error, we need to use having clause in place of where clause to avoid errors. Rules: y y y The column which is used in having clause must be used in group by clause. when having clause condition false it returns no rows selected, when where Condition returns zero.
DISTINCT keyword: The DISTINCT keyword is used to eliminate the duplicate rows in the result. We can specify multiple columns after the distinct keyword , it effects all the selected columns. Syntax : Select DISTINCT column1,column2. From table name. Eg : select FIRST_NAME from EMPLOYEES;
CONSTRAINTS: y y Constraints are used to impose business rules to DBs. It allows to enter only valid data.
There are six types of constraints in OraclE. 1) 2) 3) 4) 5) 6) NOT NULL Constraint UNIQUE Constraint PRIMARY KEY Constraint FOREIGN KEY Constraint CHECH Constraint DEFAULT Constraint
The Constraint clause can appear in y CREATE Table y ALTER Table y CREAT View Level of Constraints: 1. Column Level : Used to define constraints next in column name Define with each column Composite key cannot be defined Syntax: CREATE table table name (column1 data _type () Constraint Constraint _name Constraint _type, Column2 data _type (), column3 data _type ()); 2. Table Level: Defining Constraints after defining all columns Not Null cannot be defined Syntax: CREATE table table name (column1 data _type(), Column2 data _type (), column3 data type (), Constraint Constraint _name Constraint _type (column1, column2...));
NOT NULL Constraint: Used to avoid NULL values into columns. Data must be entered. Duplication values allowed. NOT NULL should be defined at column level Only.
Syntax: Create table table name (column1 data _type(),column2 data _type() Constraint constraint _name NOT NULL, Column3 data _type () NOT NULL); Example: CREATE table student(Sid number(4) Constraint sid_nn NOT NULL, Name varchar2 (20), Gender char); *Here constraint keyword and constraint name are optional but recommended. UNIQUE Constraint: y y y y y y y y y y Used to avoid DUPLICATE values into columns. Accepts NULL values. A table can have any number of UNIQUE keys Which is not possible in PRIMARY KEY Composite UNIQUE key is possible and always defined at table level only. A table can have more than one composite UNIQUE key. An index will be created automatically. A composite UNIQUE key cannot have more than 32 columns. The same combination of columns should not make both Unique and primary key.
UNIQUE key defined at column level: Syntax: CREATE table table name (column1 data _type() constraint Constraint _name .UNIQUE,column2 data _type(), Column3 data _type() UNIQUE); Example: CREATE table product _master (product _no varchar2 (6), Product _name varchar2 (20) constraint pn_nn NOT NULL, Description varchar2 (20), quantity number (8) constraint qty _un UNIQUE);
At table level: Syntax: CREATE table table name (column1 Data _type (), Column2 Data _type (), Column3 Data _type (), Constraint Constraint _name UNIQUE (column1, column2); Example: CREATE table customer (c_id number number (4) NOT NULL, c_name varchar2 (30) ,email varchar2(20),
Constraint name_email_un UNIQUE ( c_name, email)); PRIMARY KEY Constraint: y y y y y Used to define key columns of a table. It will not accept Null values and Duplicate values, When we need both NOT NULL and UNIQUE for a single column we will go for PRIMARY KEY. It is provided with an automatic index.
Rules: y y y y y Only one primary key or composite primary key is allowed per table. A composite PRIMARY KEY cannot have more than 32 columns. PRIMARY KEY cannot support in Nested objects. Composite PRIMARY KEY cannot be defined at column level. You cannot designate the same column or combination of columns as both a primary key and a unique key.
PRIMARY KEY constraint Defined at Column Level: Syntax: CREATE table table name (column1 data _type() constraint Constrain _name PRIMARY KEY, Column2 data _type (), column3 data _type ()); Example: CREATE table S _market (item _id number constraint id_pk PRIMARY KEY, Item_name varchar2 (20) constraint name_nn NOT NULL, item_rate number(8,2) NOT NULL, p_date date constraint dt_un UNIQUE); At table Level: Syntax: CREATE table table name(column1 data_type(), column2 data_type(), Column3 data_type(), Constraint constraint_name PRIMARY KEY(column1,column2); *composite primary key is defined at table level only as shown in example. Example: CREATE table product( prod _id number(4), prod _name varchar2(20),prod_rate number(6,2), mf_date date NOT NULL, Constraint p_pk PRIMARY KEY(prod_id,prod_name)); FOREIGN KEY(or) REFERENTIAL INTEGRITY Constraint: This FOREIGN KEY represents relationships between tables. A FOREIGN KEY column values can be derived from
PRIMARY KEY or UNIQUE A FOREIGN KEY is column that references a column of same table or another table. The table or view containing the foreign is called the Child object. The foreign key can be defined at column level or table level. A composite FOREIGN KEY can be declared at table level only. The referenced unique or primary key constraint on the parent table or view must already be defined You cannot define a foreign key in a REATE table statement thet contains an AS Sub query clause. Instead, you must create the table without the constraint and then add it later with an ALTER table statement . When you specify a foreign key at column level you need only the REFERENCES clause, but when you specify the FOREIGN KEY at table level you must specify the FOREIGN KEY keyword and one or more column names. Rules: Master table cannot be update if child records exist. A composite FOREIGN KEY cannot have more than 32 columns. A child and parent tables must be on same database. Note: FOREIGN KEY identifies the column or combination of columns in the Child table that makes up of the foreign key. REFERENCES identifies the parent table and the column or Combination of columns that make up the referenced key. CASCADE option used to remove the child table record automatically, When parent record is removed. Specify SET NULL if we want Oracle to convert dependent FOREIGN KEY values to NULL. FOREIGN KEY at column level: Syntax: CREATE table table name(column1 data _type() constraint constraint_name FOREIGN KEY(column1) REFERENCES parent_table_name( column name), column2 data _type() constraint nn constraint_type,column3 data_type()); * FOREIGN KEY(column1) is optional when defining at column level. FOREIGN KEY at Table Level: Syntax : CREATE table table name( column1 data _type(), column2 data _type(), Column3 data _type(), constraint constraint_name FOREIGN KEY( column1,column2) REFERENCES parent table(column));
*When FOREIGN KEY defining at table level FOREIGN KEY keyword is mandatory. [When creating a table with foreign key there must be one parent table with Primary key or unique constraint.] Step 1: CREATE table DEPT(DEPTNO number(2) constraint dno_pk PRIMARY KEY constraint deptno_chk CHECK(deptno between 10 and 99),dname varchar2(15) constraint dname_nn NOT NULL constraint dname_ck CHECK(Dname=upper(dname)), Loc varchar2(15) default NEW YORK constraint loc_chk CHECK (loc in(NEW YORK,DALLAS, BOSTON, CHICAGO))); Step 2: CREATE TABLE EMP(empno number(4) constraint empno_pk PRIMARY KEY, ename varchar2(20) constraint ename_nn NOT NULL CHECK(substr(ename,1,1) between A AND Z) AND ename=upper(ename)), job varchar2(15) constraint job_chk CHECK(job IN(ANALYST, CLERK, MANAGER, PRESIDENT, SALESMAN)), Mgr number(4) constraint mgr_fk_self REFERENCES emp(empno) ON DELETE SET NULL, Hiredate date DEFAULT SYSDATE, sal number(8,2) constraint sal_nn NOT NULL constraint CHK(sal between 1000 and 10000), comm Number(8,2), deptno number(2) constraint deptno_fk REFERENCES dept(deptno), ON DELETE CASCADE); CHECK: y y y y Used to impose a conditional rule on a table column. It defines a condition that each row must satisfy. A column can have any number of check constraints Check constraints can be defined at column level or table level
Rules: This cannot be include are y y y Syntax: Queries that refer to values in other rows References to the CURRVAL,NEXTVAL,LEVEL or ROWNUM Calls to functions SYSDATE,UID,USER,USERENV.
Create table table name(column1 data_type(),column2 data_type() CONSTRAINT CONSTRAINT_NAME CHECK(<condition>),column4 data type.); Example: CREATE table student(s_id number constraint sid_chk CHECK(s_id BETWEEN 1 and 60), name varchar2(20) NOT NULL, T_marks number(3) CHECK( T_marks BETWEEN 0 AND 100)); DEFAULT:
y y y
If values are not provided for the table column default value will be considered. The default value can be a literal, an expression, or a SQL function. The default expression must match the data type of column.
Syntax: Create table table name(column1 data_type(), column2 data_type() DEFAULT expression/value,column3 data_type()); Example: CREATE table school(sid number PIMARY KEY, name varchar2(20) NOT NULL, Fee number(6,2) default 5000, fee_due number(6,2)); Adding Constraints to a Existing Table: Syntax : Alter table table name ADD constraint constraint_name Constraint type (column names); Example: ALTER table emp add constraint emp_pk primary key(empno); * NOT NULL and DEFAULT added to existing column by using the MODIFY clause Of the ALTER TABLE statement. Example: ALTER table emp modify hiredate date DEFAULT sysdate; DROPPING CONSTRAINTS: y y y We can find the constraint name in USER_CONSTRAINTS and USER_CONS_COLUMNS whis is to be dropped. Alter table statement is used with DROP clause. The CASCADE option of the DROP clause causes any dependent constraints also to be dropped.
When constraint is dropped, the constraint is no longer available in data dictionary. ALTER table table name DROP PRIMARY KEY/UNIQUE(column)/CONSTRAINT constraint_name[CASCADE];
Syntax :
Example : ALTER table emp DROP primary key; Example : ALTER table dept DROP UNIQUE(Dname); Note: When we Drop PRIMARY KEY or UNIQUE constraints the related INDEX will drop automatically. *We can find the index_name of table by following syntax. SELECT INDEX_NAME from USER_INDEXES where table_name= EMP; DISABLING Constraint: The constraint can be disabled without dropping or recreating it. Syntax: ALTTER table table name DISABLE constraint constraint_name [CASCADE] *The CASCADE clause disable dependent constraints. Example : ALTER table emp DISABLE Constraint emp_pk CASCADE; ENABLE Constraint: The disabled constraint can be enabled without dropping. Syntax : ALTER table table name ENABLE constraint clause. Example: ALTER table emp ENABLE constraint emp_pk. y y Enabling a constraint applied to all the data in a table. When an UNIQUE or PRIMARY KEY constraint is ENABLED, the UNIQUE or PRIMARY KEY index is automatically created.
VIEWING Constraints: All constraints can be stored in USER_CONSTRAINTS table The code that they contained is P-primary U-unique
R-references C-check& not null Syntax: SELECT owner, constraint _name, constraint _type from user _constraints WHERE table _name= <table name>; Example: SELECT owner, constraint _name, constraint _type from user _constraints WHERE table _name= EMP; Note: When we drop the table all corresponding integrity constraints will dropped Automatically. INDEXES: y y Index is a schema object, which a pointer locates the physical address of Data Index is used by Oracle server ti speed up the retrieval,manipulate the rows.
Specification of INDEXES: y y y y y INDEX can be created explicitly or automatically. INDEX is activated when indexed column is used in where clause. INDEX Necessity of disk I/O by using an indexed path to locate data quickly. INDEX is used and maintained automatically by the Oracle server. When you drop a table, corresponding indexes are also dropped.
Creation Types of INDEXES: a. Automatic Index: A Unique index is created automatically when you define a PRIMARY KEY Or UNIQUE constraint in a table dropped. b. User created Index : y y y Users can create non unique indexes on columns to speed up access to the rows Any number of Indexes can be created on one table. USER_INDEXES holds the details of Indexes.
*When index is created it forms two dimensional matrix which is independent of the table, it will hold the sorted data, extracted from table columns and address field identifies the location of the record in Oracle Database(ROWID). Note: The records in the index are stored in the ascending order of the INDEX column.
Rules To Create INDEX: y The table or cluster to be indexed must be in own schema. y INDEX object privilege should be available on the table to INDEXED. y CREATE any index SYSTEM privilege must be available. y UNLIMITED TABLESPACE system privilege or SPACE QUOTA on TABLESPACES must be available y INDEX cannot be created on columns contain data type as LONG,LONG RAW,LOB,REF. y If INDEX is locally partitioned then the table must be portioned. y For Global Temporary table INDEX is also temporary with the same scope,as that of the table. Syntax: CREATE [UNIQUE] or [BITMAP] INDEX index _name ON Table _name (column name) TABLESPACE TableSpacename. *TableSpacenames are Stored in USER_TABLESPACES. CHANGING TABLESPACE QUOTQ UNLIMITED: ALTER tablespace TableSpacename space QUOTA UNLIMITED. Types of INDEXES: NORMAL INDEXES: They are default indexes BITMAP INDEX: y y y y y y INDEXES associated with ROWIDS called as BITMAP INDEX. Specify BITMAP to indicate that has to be create with a BITMAP for each DISTINCT KEY. BITMAP indexes should be used only when the data is infrequently updated. The Oracle OPTIMIZER can dynamically convert Bitmap Indexes to ROWIDs During the query processing.
Syntax: CREATE BITMAP INDEX index _name ON table _name(column _name); Example: CREATE BITMAP INDEX si _ind ON student(sid); CREATE BITMAP INDEX emp_ind ON emp(deptno); Rules:
y y
BITMAP indexes should not be used for tables involved in ONLINE TRANSACTION PROCESSING APPLICATIONS. We cannot specify both UNIQUE and BITMAP.
COMPOSITE INDEX: y y A composite index also called a concatenated index is an index created on multiple columns of a table. Columns in a composite index can appear in any order and need not be adjacent columns of the table. CREATE BITMAP INDEX stud_ind ON student(sno, sname);
Example:
UNIQUE INDEX: y y Unique indexes guarantee that no two rows of a table have duplicate values in the columns that define the index. Unique index is automatically created when primary key or unique constraint is created.
Example: CREATE UNIQUE INDEX stud_ind ON student(sno); COMPOSITE UNIQUE INDEX: y Composite Unique Index is an Index On Multiple unique Columns.
Example: CREATE Unique Index Eno_ename_ind ON EMP(empno,ename); NON-UNIQUE INDEX: y Non-Unique indexes do not impose the above restriction on the column values.
Example: CREATE INDEX stud_ind ON student(sno); BTREE INDEX or ASCENDING INDEX: y y y The default type of index used in an oracle database is the btree index. A btree index is designed to provide both rapid access to individual rows and quick access to groups of rows within a range. The btree index does this by performing a succession of value comparisons. Each comparison eliminates many of the rows.
DESCENDING INDEX: y y The order used by B-tree indexes has been ascending order. You can categorize data in B-tree index in descending order as well. This feature can be useful in applications where sorting operations are required.
Example: CREATE INDEX stud_ind ON student (sno desc); REVERSE KEY INDEX: y y A reverse key index when compared to standard index, reverses each byte of the column being indexed while keeping the column order. When the column is indexed in reverse mode then the column values will be stored in an index in different blocks as the starting value differs. Such an arrangement can help avoid performance degradations in indexes where modifications to the index are concentrated on a small set of blocks.
Example: CREATE INDEX stud_ind ON student(sno, REVERSE); FUNCTION BASED INDEX: When we create a INDEX on column with function it is called as FUNCTION BASED index. The index expression is built from table columns, constraints, SQL functions and user _defined functions. The value of function should not be NULL in subsequent queries. Example: CREATE INDEX dname_ind ON dept(upper(Dname)); Note: These indexes are used when the query statement is executed through the specified function.
PARTITION INDEX: Similar to partitioning tables, oracle allows you to partition indexes too. Like table partitions, index partitions could be in different tablespaces. 1. LOCAL INDEXES y y Local keyword tells oracle to create a separte index for each partition. In the local prefixed index the partition key is specified on the left prefix. When the underlying table is partitioned baes on, say two columns then the index can be prefixed on the first column specified.
y y
Local prefixed indexes can be unique or non unique. Local indexes may be easier to manage than global indexes.
2. GLOBAL INDEXES: y y y y y A global index may contain values from multiple partitions. An index is global prefixed if it is partitioned on the left prefix of the index columns. The global clause allows you to create a non-partitioned index. Global indexes may perform uniqueness checks faster than local (partitioned) indexes. You cannot create global indexes for hash partitions or subpartitions.
Example: CREATE INDEX stud_index ON student(sno) global; *INDEXES are Stored in USER_INDEXES. Global Temporary Table: Once Transactions are commit, table will be deleted. Example: CREATE Global Temporary Table g_id AS Select empno, ename, sal, d.deptno, d.dname from emp e,dept d Where e.deptno=d.deptno. *No data is there in this table. INSERT into g_id(select empno,ename,sal,d.d.deptno,d.dname from emp e,dept d Where e.deptnpo=d,deptno); SELECT *FROM g_id; Output: 14 records will display. Commit; (When we say commit the transactions will be rollback) SELECT *FROM g_id;
Output: No rows selected, because the will be rollback from the table. Difference between UNIQUE and UNIQUE INDEX: y y y Two data base objects are created at the time of UNIQUE (they are UNIQUE and DEFAULT INDEX) At the time of UNIQUE INDEX Only one database will be created. UNIQUE will give the REFERENCE to the other table, where as UNIQUE INDEX cannot give any reference.
User _constraints and User _indexes will store the INDEXES. DEFAULT indexes are available in USER_INDEXES and USER_CONSTRAINTS. But USER INDEXES are not available in USER_CONSTRAINTS. To see INDEXES on a Table DESC USER_INDEXES; TYPES OF FUNCTIONS: 1. SINGLE ROW FUNCTIONS 2. GROUP FUNCTIONS SINGLE ROW FUNCTIONS: y They are used to manipulate data items. y They accept one or more arguments and return one value for each row returned y By the query. The argument can be: y User-supplied constant. y Variable value. y Column name y Expression Syntax: FUNCTION_NAME(column/Expr,Argument1,Argument2) Features of Single-row Functions: y y y y Acting on each row returned in the query. Returning one result per row Can be used in SELECT, WHERE and ORDER BY Clause. Can be nested.
Row Types of Single functions: 1. String/Character functions 2. Numeric functions 3. Date functions 4. Miscellaneous functions 5. Conversion functions String/Character functions: Accept character input and can return both character and number values. UPPER: This will convert the string into uppercase. Syntax: upper (string) Example: Select upper('computer') from dual; UPPER ----------COMPUTER LOWER: This will convert the string into lowercase. Syntax: lower (string) Ex: Select lower(GOLDENGATE); Output: goldengate. CONCAT: y y y
It concatenates the first character value to the second character value. Only two parameters are accept. It returns the character data type.
Syntax : CONCAT(COLUMN1/EXPRESSION1,COLUMN2/EXPRESSION2); Example: Select CONCAT(golden, gate) from Dual; OUTPUT: goldengate
Example: Select concat(concat(ename,job),sal) from EMP; Note: The concatenation symbol is ||. This symbol is used to concat the more than one strings or expressions. Example: Select 'i' || ' am' || ' coming' from dual; OUTPUT: iamcoming LENGTH: y We can find the LENGTH of the String or expression, we may use column names also in this function.
Syntax: length (string/expression) Example: Select length('goldengate') from dual; OUTPUT: 10 Example: Select Length(golden gate) fom dual. OUTPUT: 11 * spaces in the string also treated as one character, but string should be in single Quotes. Example: Select Length(ename) from EMP It gives the length of each employee name of EMP table.
RPAD: This will allows you to pad/add the right side of a column/expression with any set of characters. Syntax: rpad (string, length [padding _char]) Example: Select rpad('goldengate',15,'*'), rpad('golden',15,'*#') from dual; OUTPUT: goldengate***** golden#########
y y
When adding the character to given string it includes the no. of characters present in the string Default padding character was blank space.
LPAD: This will allows you to pad/add the left side of a column with any set of characters. Syntax : lpad(string,length,[adding character]); Example: select lpad(goldengate,20, %) from dual; OUTPUT: %%%%%%%%%%goldengate Example: Select Lpad(ename,10, $) from EMP; OUTPUT: $$$$$smith $$$$$$john $$$$$$king All 14 rows will be displayed by adding $ on left side of each employee. Example: select lpad(sal,12,@) from emp; OUTPUT: @@@@@@@@@sal, here sal is taken as string. LTRIM: This will remove/cut off unwanted characters from the left end of string. Syntax: ltrim (string [,unwanted _chars]); Example: Select ltrim('goldengate, golden') from dual; OUTPUT: gate If you havent specified any unwanted characters it will display entire string. RTRIM: It will remove all the right most characters appear in the set. Syntax: RTRIM (char, set); Example: Select Rtrim(goldengateabab, ab) from dual; OUTPUT: goldengate.
Example: Select RTrim(job,er) from EMP; TRIM: It removes the characters from both (left, right) sides. If we specify Leading concentrates on leading characters. If Trailing is specified it concentrates on trailing characters. If both or none is specified concentrates on both leading and trailing. Returns the varchar2 type Example: Select Trim (d from goldendd) from dual; Select Trim (Leading s from ssmithss) from dual; Select trim(Trailing s from ssmithss) from dual; Select trim(both s from ssmithss) from dual; REPLACE: This will replace the set of characters of a string by the given string. If the replacement string is omitted or null, all occurrences of each string are removed. Syntax: REPLACE (TEXT, SEARCH_STRING, [REPLACEMENT_STRING]); Example: Select Replace(olden, o, go) from dual; OUTPUT: golden, here o is Replaced with go Example: Select replace(g o l d e n g a t e, ) from dual; OUTPUT: goldengate, here we omitted the replacement string hence all the Spaces are removed. TRANSLATE: This will Replace the string character by character. Syntax: TRANSLATE (string, old_character, new_character); Example: Select Translate(goldengate, ge, xy) from dual; OUTPUT: xoldynxaty. Here g is replaced by x, e is replaced by y. Example: Select translate(led, l, R) from dual;
OUTPUT: Red. Example: Select translate(ledl, le, Ra) from dual; OUTPUT: RedR ASCII: This will return the decimal representation in the database character set of the first character of the string Syntax: ASCII (string) Example: Select ASCII(a) from dual; OUTPUT: 97. Example: Select ASCII(Ward) from dual; OUTPUT: 87. If we pass more than one character only one character is passed. CHR: This will return the character having the binary equivalent to the string in either the Database character set or the national character set. Syntax: CHR(number) Example: Select CHR(65) from dual; OUTPUT: A SOUNDEX: y This will be used to find words that sound like other words, exclusively used in where clause.
Syntax: soundex (string) Example: Select *from Emp where soundex(ename)=soundex(smith); SUBSTR: This will be used to extract substrings.
Syntax: SUBSTR (String, starting _position(m),no_of_characters(n)) If m is 0, it is treated as 1. If m is positive, Oracle counts from beginning of character to find the first character. If n is omitted, returns all characters to the end of character. If n is less than 1 or 0, a null is returned and floating points passed automatically converted to integers. Example: Select substr(goldengate,1,4) from dual; OUTPUT: gold Example: Select substr(goldengate,3,6) from dual; OUTPUT: ldenga Example: Select substr(goldengate,-4,3) from dual; OUTPUT: gat INSTR: It returns the numeric position of a named character. Syntax: INSTR (Column/Expression, character, [M], [N]) It searches for a character in a string/column from its Mth character and Nth number of occurrence it displays the position of character. y M can be positive or negative, if negative it searches backward from the end of column/expression. y The value of N should be positive. y The default value of both M and N are 1. y If search is unsuccessful, the return value is zero. Example: y Select instr('goldengate','g',1,2) from dual; INSTR ('GOLDENGATE','G', 1, 2) --------------------------7 Select instr('goldengate','g',2,2) from dual; INSTR ('GOLDENGATE','G', 2,2)
--------------------------0 Select instr('goldengate','g',-1,2) from dual; INSTR ('GOLDENGATE','G',-1, 2) ---------------------------1 INITCAP: y It returns a string with the first letter of each word in upper case, keeping all other in lower case.
Example: select initcap('golden gate') from dual; INITCAP('GOLDEN GATE) ----------Golden Gate SELECT upper('goldengate'), lower('GOLDENGATE'), initcap('golden gate') from dual; UPPER ('GOL LOWER('GOL INITCAP('GO ---------- ---------- ----------GOLDENGATE goldengate Golden Gate DECODE: y Decode will act as value by value substitution. For every value of field, it will checks for a match in a series of if/then tests.
Syntax: decode (value, if1, then1, if2, then2, . else); y y y y If the number of parameters are odd and different then decode will display nothing. If the number of parameters are even and different then decode will display last value. If all the parameters are null then decode will display nothing. If all the parameters are zeros then decode will display zero
SQL> select decode(2,2,5,1,1,3) from dual; DECODE(2,2,5,1,1,3) ------------------5 SQL> select decode(2,3,5,5) from dual; DECODE(2,3,5,5) --------------5 SQL> select decode(2,3,5) from dual; DECODE(2,3,5) ------------SQL> select decode(3,4,5,6,7,4) from dual; DECODE(3,4,5,6,7,4) ------------------4 SQL> select decode(3,4,5,6,7) from dual; DECODE(3,4,5,6,7) ----------------SQL> select decode(1,1,2,2,3,3,3,3,5) from dual; DECODE(1,1,2,2,3,3,3,3,5) ------------------------GREATEST: This will give the greatest string, number from the given strings, numbers. Syntax: greatest (strng1number1, string2/number2, string3/number3 stringn) Example: Select greatest (10, 20, 12, 30) from dual;
GREATEST (10, 20, 12, 30) --------------------30 SQL> select greatest (12, 35, 23, 32) from dual; GREATEST (12, 35, 23, 32) --------------------35 SQL> select greatest ('golden','hyderabad','india') from dual; GREAT ----india SQL> select greatest ('golden, gate') from dual; GREATE -----golden SQL> select greatest ('gate, golden') from dual; GREATE -----Golden If any of the parameters is null it will display nothing. LEAST: This will give the least string/number . Syntax: greatest (strng1/number1, string2/number2, string3/number3 stringn) Example: SQL> select least('smith','john','scott') from dual; LEAST ---John SQL> select least (121,111,123,321,234,431,102) from dual; LEAST (121,111,123,321,234,431,102) ---------------------------------102
COALESCE: This will give the first non-null string/expression. Syntax: coalesce (strng1, string2, string3 stringn); Example: SQL> select coalesce('ab','xy','rt'),coalesce('','as','xy') from dual; COALESCE COALESCE -- -------ab as SQL> select coalesce(100,null,120),coalesce(null,100,120),coalesce(null,'aw','fh') from dual; COALESCE (100,NULL,120)COALESCE (NULL,100,120)COALESCE(NULL,AW,FH) ---------------------- ------------ ---------------------------- -----------------------------------100 100 aw NUMBER FUNTIONS: These functions accept number input and return numeric values. Many functions that return values that are accurate to 38 decimal digits. ROUND FUNCTION: Syntax: ROUND (m,n) y y y y It returns m round to n places right of the decimal point. If n is omitted n is rounded to 0,places. If n is negative round of the digits left of the decimal point. n must be an integer.
Example: select ROUND (123.34,1) from dual; ROUND (123.34,1) --------------123.3 select round (-122.236,2) from dual; ROUND (-122.236,2) -----------------122.24
Select round(345.37,1) from dual; ROUND (345.37,1) --------------345.4 select round (237.385,-2) from dual; ROUND(237.385,-2) ----------------200 TRUNC: This will truncate digits of precision from a number. Syntax: TRUNC (VALUE, PRECISION) Example: SLECT TRUNC (123.23, 2) FROM DUAL; TRUNC (123.23, 2) --------------123.23 Select trunc(113.343,2) from dual; TRUNC (113.343,2) ---------------113.34 Select trunc(3234.22341,3) from dual; TRUNC (3234.22341,3) ------------------3234.223 Select trunc (-324.3456,2) from dual; TRUNC (-324.3456,2) ------------------324.34 Select trunc(-345.3456,-2) from dual; TRUNC (-345.3456,-2) -------------------300
ABS: y y Absolute value is the measure of the magnitude of value. Absolute value is always a positive number.
Syntax: abs (value) Example: Select abs(5),abs(-6),abs(0),abs(-7.34) from dual; ABS (5) ---------5 SIGN: y Sign gives the sign of a value. ABS (-6) ABS (0) ABS (-7.34) ---------- ---------- --- ------6 0 7.34
Syntax: sign (value) Example: Select sign (-5), sign (6), sign (0), sign (null) from dual; SIGN (-5) SIGN (6) SIGN (0) ------------------- ----------1 1 0 SIGN (NULL) ----------
SQRT: y This will give the square root of the given value. Syntax: sqrt (value) Here value must be positive. Example: Select sqrt(4),sqrt(12),sqrt(16),sqrt(28) from dual; SQRT(4) SQRT(12) SQRT(16) SQRT(28) ---------- ---------------------------2 3.46410162 4 5.29150262 Select sqrt(1),sqrt(null),sqrt(0) from dual; SQRT(1) SQRT(NULL) SQRT(0) ---------- ---------- ---------1 0
MOD This will give the remainder. Syntax: mod (value, divisor) Ex: select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4) from dual; MOD(7,4) MOD(1,5) ------------ ---------3 1 NVL This will substitutes the specified value in the place of null values. This is used to convert a NULL value to an actual value. Syntax: nvl (null _col/exp1, replacement _value/exp2) Exp1: Is the source value or expression that may contain NULL. Exp2: is the target value for converting NULL. Select nvl(100,200) from dual; NVL (100,200) -----------100 Select nvl(null,100) from dual; NVL (NULL, 100) ------------100 Select 1000+null from dual; 1000+NULL ---------Select 1000+nvl (null, 0) from dual; 1000+NVL (NULL, 0) ---------------1000 POWER Power is the ability to raise a value to a given exponent. Syntax: power (value, exponent) select power(2,5),power(-2,3),power(0,0),power(1,1) from dual; POWER (2,5) POWER(-2,3) POWER(0,0) POWER(1,1) -------------------------------------32 -8 1 1 MOD(NULL,NULL) --------------------MOD(0,0) ----------0 MOD(-7,4) -------------3
EXP This will raise e value to the give power. Syntax: exp (value) Select exp (0), exp (1), exp (-1), exp (5) from dual; EXP (0) ---------1 LN This is based on natural or base e logarithm. Syntax: ln (value) Here value must be greater than zero which is positive only. Select ln(2),ln(5) from dual; LN(2) ---------.693147181 LN(5) ---------1.60943791 EXP (1) ---------2.71828183 EXP (-1) ---------367879441 EXP (5) ---------148.413159
Select ln(0) from dual; Error Argument '0' is out of range LOG This is based on 10 based logarithm. Syntax: log (10, value) -- here value must be greater than zero which is positive only. Select log(10,100), log(10,2), log(10,1), log(10,null) from dual; LOG(10,100) LOG(10,2) LOG(10,1) LOG(10,NULL) ---------------------------------------2 .301029996 0 CEIL This will produce a whole number that is greater than or equal to the specified value. Syntax: ceil (value) Select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from dual; CEIL(5) CEIL(5.1) CEIL(-5) --------- ----------- ---------5 6 -5 CEIL(-5.1) ------------5 CEIL(0) -------0 CEIL(NULL) --------------
FLOOR This will produce a whole number that is less than or equal to the specified value. Syntax: floor (value) Select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual; FLOOR(5) ----------5 FLOOR(5.1) FLOOR(-5) -----------------------5 -5 FLOOR(-5.1) FLOOR(0) FLOOR(NULL) ---------------------------------------6 0
BITAND This will perform bitwise and operation. Syntax: bitand (value1, value2) select bitand(2,3), bitand(0,0), bitand(1,1), bitand(null,null), bitand(-2,-3) from dual; BITAND(2,3) BITAND(0,0) BITAND(1,1) BITAND(NULL,NULL) ----------------------------------------------2 0 1 -4 GREATEST This will give the greatest number. Syntax: greatest (value1, value2, value3 valuen) Select greatest (1, 2, 3), greatest (-1, -2, -3) from dual; GREATEST (1, 2, 3) GREATEST (-1,-2,-3) -----------------------------------------3 -1 y If all the values are zeros then it will display zero. y y If all the parameters are nulls then it will display nothing. If any of the parameters is null it will display nothing. This will give the least number. Syntax: least (value1, value2, value3 valuen) Select least (1, 2, 3), least (-1, -2, -3) from dual; LEAST (1, 2, 3) -------------------1 LEAST (-1,-2,-3) -----------------------3 BITAND(-2,-3) -------------
LEAST
y y y
If all the values are zeros then it will display zero. If all the parameters are nulls then it will display nothing. If any of the parameters is null it will display nothing. This will return the first not null value.
COALESCE Syntax: coalesce (value1, value2, value3 valuen) Select coalesce(1,2,3), coalesce(null,2,null,5) from dual; COALESCE(1,2,3) --------------1 DATE FUNCTIONS: y y y Oracle stores the dates in an internal numeric format. The default display and input format for any date is DD-MON-YY. We can change the default format to our desired format by using the following command. COALESCE(NULL,2,NULL,5) ----------------------2
Alter session set nls_date_format = DD-MONTH-YYYY; But this will expire once the session was closed. SYSDATE: It is a date function that returns current date and time. Select SYSDATE from dual; Date arithmetic: As database stores dates as numbers, it allows to perform calculations using arithmetic operators. We can perform the following operations.. y y y Date + number date adds a number of days to a date. Date Number Date subtracts the number of days from date. Date + Number/24 adds a number of hours to date
Example: Select sysdate from dual; Select Sysdate, Sysdate+48/24 from dual; CURRENT_DATE This will returns the current date in the session s timezone. select current_date from dual; CURRENT_DATE -----------------25-NOV-11 CURRENT_TIMESTAMP This will returns the current timestamp with the active time zone information. Select current_timestamp from dual; CURRENT_TIMESTAMP -----------------------------------------------------25-NOV-11 03.42.41.383369 AM +05:30 SYSTIMESTAMP This will returns the system date, including fractional seconds and time zone of the database. Select systimestamp from dual; SYSTIMESTAMP -----------------------------------------------------25-NOV-11 03.49.31.830099 AM +05:30 LOCALTIMESTAMP This will returns local timestamp in the active time zone information, with no time zone information shown. Select localtimestamp from dual; LOCALTIMESTAMP -------------------------------------------25-NOV-11 03.44.18.502874 AM
DBTIMEZONE This will returns the current database time zone in UTC format. (Coordinated Universal Time) Select dbtimezone from dual; DBTIMEZONE ---------------07:00 SESSIONTIMEZONE This will return the value of the current sessions time zone. Select sessiontimezone from dual; SESSIONTIMEZONE -----------------------------+05:30 MONTHS_BETWEEN FUNCTION: Syntax: Months _between (D1,D2) It gives the difference between D1 and D2 in number of months. If D1 is later than D2, the result is positive, else negative. Select months_between(sysdate,'25-DEC-04') from dual; MONTHS_BETWEEN(SYSDATE,'25-DEC-04') ----------------------------------83 Select months_between('22-DEC-2010',sysdate) from dual; MONTHS_BETWEEN('22-DEC-2010',SYSDATE) -------------------------------------11.128056 NEXT DAY FUNTION: Syntax: Next_day(D,Char) It returns the date of the first week day named by char, that is later than the data D.
select next_day(sysdate,'wed') from dual; NEXT_DAY( --------30-NOV-11 select next_day(sysdate,'sat') from dual; NEXT_DAY --------26-NOV-11 LAST DAY FUNCTION: Syntax: last _day (D) It returns the date of the last day of the month that contains D. Mostly is used to determine how many days are left in the current month. Select last_day(sysdate), last_day(sysdate)-sysdate daysleft from dual; LAST_DAY --------- ------30-NOV-11 DAYSLEFT --5
ROUNDING OF DATES: Syntax: Round (date, format) Returns date rounded to the unit specified by the format. If format is omitted, date is rounded to the nearest day. select round(sysdate,'month') from dual; ROUND (SYSDATE. --------01-DEC-11 TRUNCATING DATES: Syntax: Trunc(Date, format) Returns date with the time portion of the day truncated to the specified unit.
Select round (sysdate,'DAY'),Trunc(sysdate,'DAY') from dual; ROUND (SYS TRUNC (SYS --------- --------27-NOV-11 20-NOV-11 Select round (sysdate,'MONTH'),trunc(sysdate,'MONTH') from dual; ROUND (SYS TRUNC(SYS --------- --------01-DEC-11 01-NOV-11
CONVERSION FUNCTION: The conversion functions convert a value from one data type to another. Conversion in Oracle is two types. Implicit conversion. It works according to the convention specified by the Oracle. CHAR to NUMBER conversion succeed only if the character string represents a valid NUMBER. CHAR to DATES conversion succeed only if the character string represents the default format of DD-MON-YY. Explicit conversion. SQL provided three conversion functions to convert one data type to another. The explicit conversion functions are TO_ CHAR To Character function. TO_DATE To Date conversion TO_NUMBER To Number conversion. TO_CHAR Conversion: This function is used in two ways. 1. TO_CHAR (Number Conversion) 2. TO_CHAR (Date Conversion) TO_CHAR(Number Conversion):
1 . Decimal Indicator: D 99D99 It returns the specified position of the decimal character. The default decimal delimiter is period. SQL> select 1234,to_char(1234,'9999D99') from dual; 1234 TO_CHAR( ---------- -------1234 1234.00 SQL> select 127864,to_char(127864,'9999D99') from dual; 127864 TO_CHAR( ---------- -------127864 ######## SQL> select 12345,to_char(12345,'99999D99') from dual; 12345 TO_CHAR(1 ---------- --------12345 123450 2. SCIENTIFIC NOTATION INDICATOR: EEEE 9.9EEEE Returns the numeric value using scientific notation. SQL> select to_char(3247,'9.9EEEE') from dual; TO_CHAR(3 --------3.2E+03 3 . GROUP SEPARATOR: G 9G9999 y y Returns the specified position of the group separator. Multiple group separators can be specified.
SQL> select to_char(3426354,'99G99G999') from dual; TO_CHAR(34 ---------34,26,354 LOCAL CURRANCY INDICATOR : L y L999 or 999L
SQL> select to_char(1234,'L9999') from dual; TO_CHAR (1234,'L --------------$1234 SQL> select to_char(23765,'L99G999D99', 'NLS_CURRENCY=IndRupees') from dual; TO_CHAR (23765,'L99G9 -------------------IndRupees 23, 765.00 TRAILING MINUS INDICATOR: MI 9999MI y y It returns negative value with a trailing minus sign -. Returns positive value with a trailing blank.
SQL> select -10000, to_char(-10000,'L99g999d99MI') from dual; -10000 TO_CHAR (-10000,'L99G ---------- --------------------10000 $10,000.00SQL> select 12000, to_char(120000,'9g99g999d99MI','NLS_CURRENCY=IndRupees') from dual; 12000 TO_CHAR (1200 ---------- -----------12000 1, 20,000.00 NEGATIVE NUMBER INDICATOR: PR 9999PR y y Returns negative number in <>. It can appear only as trailing declaration.
SQL> select to_char(-10000,'L99g999d99pr') from dual; TO_CHAR(-10000,'L99G9 --------------------<$10,000.00> SQL> select to_char(12000,'L99g999d99pr') from dual; TO_CHAR(12000,'L99G99 --------------------$12,000.00 ROMAN NEGATIVE INDICATOR: RN returns upper roman number rn returns lower roman number. The value can be an integer between 1 and 3999. SQL> select 12,to_char(12,'RN'),to_char(12,'rn') from dual; 12 TO_CHAR (12,'RN' TO_CHAR(12,'RN' ---------- --------------- --------------12 XII xii HEXADECIMAL INDICATOR: X XXXX y y y Returns the Hexadecimal value of the specified number of digits. If number is not an integer, Oracle rounds it to an integer. Accepts only positive or 0.
SQL> select 2000, to_char (2000,'xxxx') from dual; 2000 TO_CH ---------- ----2000 7d0 GROUP SEPARATOR: 9,999 y y Returns a comma in the specified position. Multiple commas can be specified.
SQL> select 20000,to_char(20000,'99,999.99') from dual; 20000 TO_CHAR (20 ---------- ---------20000 20,000.00 DOLLAR INDICATOR: Returns value with a leading dollar sign. SQL> select 200000,to_char(200000,'$9,99,999.99') from dual; 200000 TO_CHAR (20000 ---------- ------------200000 $2, 00,000.00 ZERO INDICATORS: Returns lading OR trailing Zeros. SQL> select 10000,to_char(10000,'09999999'), to_char(10000,'0999990') from dual; 10000 TO_CHAR(1 TO_CHAR( ---------- --------- -------10000 00010000 0010000 ISO CURRENCY INDICATOR: C C9999 Returns specified position of the ISO currency symbol. SQL> select 8000,to_char(8000,'C9999.99') from dual; 8000 TO_CHAR(8000,'C ---------- --------------8000 USD8000.00 Date format Models: The date format models can be used in the TO_CHAR function too translate a DATE value from original format to use format. DATE FORMATS D -- No of days in week DD -- No of days in month DDD -- No of days in year MM -- No of month
MON -- Three letter abbreviation of month MONTH -- Fully spelled out month RM -- Roman numeral month DY -- Three letter abbreviated day DAY -- Fully spelled out day Y -- Last one digit of the year YY -- Last two digits of the year YYY -- Last three digits of the year YYYY -- Full four digit year SYYYY -- Signed year I -- One digit year from ISO standard IY -- Two digit year from ISO standard IYY -- Three digit year from ISO standard IYYY -- Four digit year from ISO standard Y, YYY -- Year with comma YEAR -- Fully spelled out year CC -- Century Q -- No of quarters W -- No of weeks in month WW -- No of weeks in year IW -- No of weeks in year from ISO standard HH -- Hours MI -- Minutes SS -- Seconds FF -- Fractional seconds AM or PM -- Displays AM or PM depending upon time of day A.M or P.M -- Displays A.M or P.M depending upon time of day AD or BC -- Displays AD or BC depending upon the date A.D or B.C -- Displays AD or BC depending upon the date FM -- Prefix to month or day, suppresses padding of month or day TH -- Suffix to a number SP -- suffix to a number to be spelled out SPTH -- Suffix combination of TH and SP to be both spelled out SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual; TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI ---------------------------------------------------24 december 2006 02:03:23 pm sun SQL> select to_char(sysdate,'dd month year') from dual; TO_CHAR(SYSDATE,'DDMONTHYEAR') ------------------------------------------------------24 december two thousand six SQL> select to_char(sysdate,'dd fmmonth year') from dual;
TO_CHAR(SYSDATE,'DD FMMONTH YEAR') ------------------------------------------------------24 december two thousand six SQL> select to_char(sysdate,'ddth DDTH') from dual; TO_CHAR(S -----------24th 24TH SQL> select to_char(sysdate,'ddspth DDSPTH') from dual; TO_CHAR(SYSDATE,'DDSPTHDDSPTH -----------------------------------------twenty-fourth TWENTY-FOURTH SQL> select to_char(sysdate,'ddsp Ddsp DDSP ') from dual; TO_CHAR(SYSDATE,'DDSPDDSPDDSP') -----------------------------------------------twenty-four Twenty-Four TWENTY-FOUR TO_DATE This will be used to convert the string into data format. Syntax: to_date (date) select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day') from dual; TO_CHAR(TO_DATE('24/DEC/20 -------------------------24 * december * Sunday SQL> select to_char(sysdate,'i') from dual; T 1 SQL> select to_char(sysdate,'ww') from dual; TO -48
AGGREGATE/GROUP FUNCTIONS: Group functions operate on set of rows to give one result per each group. Group functions can appear in select lists and in ORDER BY and HAVING clauses. Syntax: group_function(distinct/all column); Rules: The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE. All group functions ignore null values except COUNT (*). Average function: It returns the average value of column. It ignores NULL values. Syntax: avg(distinct/all column) select avg(sal), avg(DISTICT sal) from employees; Sum Function: It returns the SUM value of column. Syntax: sum(distinct/all Column) Select SUM(comm.), SUM(distinct comm) from employees; Maximum Function: It returns the maximum value of column Syntax: max(distinct/all column) Select max(sal) from employees; Minimum Function: It returns the minimum value of column. Syntax : min(distinct/all Column) Select min(sal) from employees;
Standard Deviation Function: It returns the standard deviation of the column. Syntax: stddev(distinct/all Column) Select STDDEV (sal), STDDEV(DISTINCT sal) from employees;
Variance Function: It returns the variance column Syntax: variance (distinct/all column) Select variance (sal),variance(distinct sal) from employees; Count Function: It gives the no of rows in the Query. If * used to returns all rows, it includes duplicated and NULLs. Syntax: Count (distinct/all column) Select count (employee _name) from employees; Select count (*) from employees; MISCELLANEOUS FUNCTIONS: UID: This will returns the integer value corresponding to the user currently logged in. select uid from dual; UID ---------319 USER: This will returns the login s user name. select user from dual; USER ---------------scott
VSIZE: This will returns the number of bytes in the expression. Select vsize(123), vsize('computer'), vsize('12-jan-90') from dual; VSIZE(123) VSIZE('COMPUTER') VSIZE('12-JAN-90') -------------------------------------------------------3 8 9 RANK: This will give the non-sequential ranking. Select rownum,sal from (select sal from emp order by sal desc); ROWNUM SAL ---------- ---------1 5000 2 3000 3 3000 4 2975 5 2850 6 2450 select rank(2975) within group(order by sal desc) from emp; RANK(2975)WITHINGROUP(ORDERBYSALDESC) --------------------------------------------------------4 DENSE_RANK: This will give the sequential ranking. select dense_rank(2975) within group(order by sal desc) from emp; DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC) ----------------------------------------------------------------3 OPERATORS: Arithmetic Operators: Arithmetic operators can be used to create expressions on NUMBER and DATE data. Arithmetic operators are +, - , *, /. Operator precedence *, /, +, -
Arithmetic operators can be used in any clause of SQL statements, except the FROM clause. Select empno, ename, sal,sal+500 from employees; HANDLING NULL VALUES: y y y y Null value is unknown value, undefined value. Not equal to 0 or blank space. It represented with null keyword. No operations allowed on null,(if performed any arithmetic operations it returns null only)
Select 1000+null from dual; 1000+NULL ---------Select 2500*null from dual; 2500+NULL ------------NVL FUNCTION: Syntax: NVL (Exp1, Exp2) y y Exp1 is source value or expression that may contain NULL. Exp2 is target value for converting NULL.
Data type of Expression1 and Expression should be same. SQL> select 1000+nvl(null,0) from dual; 1000+NVL(NULL,0) ---------------1000
SQL> select nvl(null,100) from dual; NVL(NULL,100) ------------100 NVL2 FUNCTION: Syntax : NVL2(exp1,exp2,exp3) y y y y If exp1 is NOT NULL, NVL2 returns exp2. If exp1 is NULL, NVL2 returns exp3. Exp1 may any data type. The data type of return value is always same as the data type of exp2, unless exp2 is Character data type.
SQL> select nvl2(null,0,1000) from dual; NVL2(NULL,0,1000) ----------------1000 SQL> select nvl2(100,250,300) from dual; NVL2(100,250,300) ----------------250 SQL> select nvl2(null,200,null) from dual; NVL2(NULL,200,NULL) -------------------
NULLIF FUNCTION: Syntax: NULLIF (exp1, exp2) y Compares two expressions and returns null if they are equal. y Returns first if they are not equal. select nullif(100,200) from dual; NULLIF(100,200) --------------100
SQL> select nullif(300,300) from dual; NULLIF(300,300) --------------SQL> select nullif('smith','smith') from dual; NULLI ----SQL> select nullif('smith','john') from dual; NULLI ----Smith Relational or Comparison operators: <>, ^=,! = these three are not equal operators. >, >= <, <= = Select ename,sal from employees where sal>2000; Select ename,sal from employee where sal<=1500; Logical operators: A logical condition combines the result of two component conditions to produce a single result. Three logical operators available in Oracle AND Operator: y y It returns FALSE if either is FALSE, else returns unknown. It returns the result based on two or more conditions.
Select ename,sal,job from emp where (sal>=1500 and sal<=5000) and job=MANAGER; OR Operator: y y It returns TRUE if either of component conditions are TRUE. It returns FALSE if both are FALSE, else returns unknown.
Select ename,job,sal from emp where sal>=2000 OR deptno=20; NOT Operator: y y y It returns TRUE if following condition is FALSE. It returns FALSE if following condition is TRUE. If the condition is unknown, it returns unknown.
Select empno,ename,sal from emp where NOT empno=7788; The default precedence order is ALL Comparison operators NOT Logical condition AND Logical condition OR Logical condition SQL OPERATORS: BETWEENAND: This is used to display the rows based on a range of values. The declared range is inclusive. The lower limit should be declared first. Select empno, ename, sal from EMP where comm. between 200 and 800; IN Operator: This operator is used to test for values in a specified list. The operator can be used upon any datatype. Select empno,ename,sal from EMP where job in(MANAGER,CLERK); Select empno,deptno,sal from EMP where deptno in(10,20,30); NOT IN: Select empno, ename,sal from EMP where deptno NOT IN(20,30); LIKE Operator: y y y Use the like condition to perform wildcard. The LIKE operator searches of valid search string values. Search condition may contain either literal or numbers.
The available wild cards are % _ it represents any sequence of zero or more characters. It represents the any single character, only at that position only.
Select ename,empno from EMP where ename LIKE M%; It displays the employee details whose name starts with M Select ename,empno,sal from EMP where ename LIKE _O%; It displays the employee details who contains O as second letter of names. NOT LIKE: Select empno,ename,sal from EMP where ename NOT LIKE M%; It display the employee details not starting with M. IS NULL, IS NOT NULL Operator: y y The operator tests for NULL values. It is only the operator that can be used to test for NULLs
Select ename,empno,sal from EMP where comm. Is NULL. Select ename,empno,deptno where mgr is NOT NULL. SET OPERATORS: y y y The set operators allow you to combine rows returned by two or more queries The number of columns and the column types returned by the queries must match, although the column names may be different. All set operators have equal precedence, if a SQL statements contains multiple SET operators, the Oracle server evaluates them from left(top) to right(bottom) if no parentheses explicitly another order.
DIFFERENT TYPES OF SET OPERATORS: UNION Operator. UNION ALL Operator INTERSECT Operator MINUS Operator. Whenever theses operators are used select statement must have Equal no of columns, similar data type columns
Description Returns all the rows retrieved by the queries, including duplicate rows. Returns all non-duplicate rows retrieved by the queries. Returns rows that are common to both queries. Returns the remaining rows when the rows retrieved by the second query are subtracted from the rows retrieved by the first query.
1) Select job from EMP where deptno=10; UNION Select job from EMP where deptno=20; 2) selct deptno,job from EMP where deptno=10; UNION ALL Select deptno,job from EMP where deptno=20;
3) select job from EMP where Deptno=10; INTERSECT Select job from EMP where deptno=20; 4 ) select job from EMP where deptno=10; MINUS S ELECT JOB FROM EMP where deptno=20; JOINS: y y When data from more than one table in the database is required, a join condition is used. A join is a query that combines rows from two or more tables, views, or materialized views. a join is performed whenever multiple table appear in the quires FROM clause.
Join Conditions: y y A column in the join condition need not be part of the SELECT list. When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access.
EQUI JOIN or Simple Join: y Based on equality condition tables are joined.
y y
Only matching records are displayed. Joining tables must have at least one common column with same data type and same values. ( not column name same).
Syntax: Select col1,col2,col3. From <table1>,<table2> Where <table>.<common col name>=<table2>.<column col name> And.. Example:
Select empno,ename,emp.deptno deptno,dname from emp,dept Where emp.deptno=dept.deptno; Using table aliases: Select e.empno, e.ename, d.deptno, d.dname from emp e,dept d Where e.deptno=d.deptno; Non Equi Joins: y Between operator is used in non equi joins, it called as between join.
Syntax: Select col1,col2. From <table A>,<table B> Where <table A>.<col1> between <table B>.<col1> and <table B>.<col2>; Example: Select e.ename,e.sal,s.grade from emp e.salgrade s Where e.sal between 1000 and 3000; SELF JOIN: y y y y It indicates joining the table to itself. The same table appears twice in the FROM clause and is followed by table aliases. The table aliases must qualify the column names in the join condition. It is used on same table the table must have at least 2 column with same,datatype,values
Example: Select e.ename employee name,m.ename manager name from emp e,emp m Where e.mgr=m.empno; OUTER JOIN: y y y y Is used to retrieve all the rows from one table but matching rows from other table. An outer join extends the result of a simple or inner join. It is use an operator (+), it called join operator. (+) used with table which missing the data.
Syntax: Select table1.column, table2.column from table1, table2 Where table1.column (+) =table2.column; Rules: (+) operator can appear only in the where clause. (+) used only with one table. Example: Select e.ename,d.deptno,d.dname from emp e , dept d Where e.deptno(+)=d.deptno ORDER BY e.deptno; Here from emp table only matching record will display, where as in dept table all the records will display. LEFT OUTER JOIN: y This will display the all the records from the left side table and only matching records from the right side table To perform a left outer join, the WHERE clause is, WHERE table1.column1 = table2.column2 (+); Example: Select empno, ename, job, dname, loc from emp e left outer join dept d On (e.deptno=d.deptno); Or
Select empno, ename, job, dname, loc from emp e,dept d where e.deptno=d.deptno (+); RIGHT OUTER JOIN: y y This will display all the records from right side of the table and only matching records from left side of the table. To perform a right outer join, the WHERE clause is, WHERE table1.column1(+)= table2.column2;
Example: Select empno, ename, job, dname, loc from emp e right outer join dept d On (e.deptno=d.deptno); Or Select empno, ename, job, dname, loc from emp e,dept d where e.deptno(+)=d.deptno; FULL OUTER JOIN: y This will display the all matching records and the non-matching records from both tables.
Note: Full outer join=left outer join + right outer join; Example: select empno,ename,job,dname,loc from emp e full outer join dept d on(e.deptno=d.deptno);
CROSS JOIN: y This will return a Cartesian product from the two tables.
Example: select empno,ename,job,dname,loc from emp cross join dept; NATURAL JOIN: y y Natural join compares all the common columns. If several columns have same names but data types do not match, the natural join can be used.
Example: select empno,ename,job,dname,loc from emp natural join dept; INNER JOIN: y This will display all the records that have matched.
Example: Select empno,ename,job,dname,loc from emp inner join dept using(deptno); USING CLAUSE Example: select empno,ename,job ,dname,loc from emp e join dept d using(deptno); ON CLAUSE Example: select empno,ename,job,dname,loc from emp e join dept d SUBQUERIES: y y y Nesting of queries, one within the other is termed as a sub query. A statement containing a sub query is called a parent query. Sub queries are used to retrieve data from tables that depend on the values in the table itself. on(e.deptno=d.deptno);
Root query: the query which is not depend on any other query for its Conditions value. Or Independent query. Example: Select ename,sal from emp where deptno=10;
Parent query: the query which depend on any other query for its condition value. Sub query: y y y The query which provides conditional values to its parent query. Solve the problem by combining the two queries, placing one query inside the other query. Two clauses of comparison conditions are used in sub queries
1. Single-row operator:
y y
A single-row subquery is one that returns either zero rows or one row to the outer SQL statement. A subquery can be placed in the WHERE clause of another query.
Example: select * from emp where sal > (select sal from emp where empno = 7566); y we can use other comparison operators, such as <>, <, >, <=, and >=, with a single-row subquery.
Example: SELECT product_id, name, price FROM products WHERE price >(SELECT AVG(price)FROM products); y y If a sub query is placed in FROM clause these types of sub queries are called as INLI NE views, because the sub query provides data in line with the FROM clause. SELECT product _id FROM (SELECT product _id FROM products WHERE product _id < 3);
Example:
A sub query may not contain an ORDER BY clause. Instead, any ordering must be done in the Outer query.
Example: SELECT product _id, name, price FROM products WHERE price > (SELECT AVG (price)FROM products) ORDER BY product_id DESC; 2 . Multiple-row operators: y A multiple-row sub query can return one or more rows to an outer SQL statement.
y IN
To handle a sub query that returns multiple rows, outer query may use the IN, ANY, or ALL operator. Equal to any value in the list. Compare value to each value returned by the sub query.
ANY/SOME ALL
Example: 1. Select ename,deptno from emp where sal IN(select max(sal) from emp group by deptno); 2. Select ename,ename,sal,deptno from emp where 1sal <SOME(1250,3000,2500); 3. Select ename,job,sal from emp where sal<ANY(select sal from emp where job=CLERK); 4. Select ename,job,sal from emp where sal>ANY(select sal from emp where deptno=10); Note: < ANY/SOME Means less than the maximum value in the list. >ANY/SOME Means more than the minimum value in the list. Example: 1. Select ename,job from emp where sal>ALL(select sal from emp where deptno=30); 2. Select ename,job,sal from emp where sal<ALL(select avg(sal) from emp group by deptno); Note: > ALL means more than the maximum in the list. < ALL means less than the minimum value in the list. Pair wise comparison WHERE clause based subquery: Example: Select ename,sal,deptno from emp where(deptno,sal) in(select deptno,max(sal) from emp group by deptno) and deptno<>10; Non Pair wise comparison WHERE clause based subquery: Example:
Select ename,sal,deptno from emp where deptno in(select deptno from emp group by deptno) and sal in(select max(sal) from emp group by deptno) and deptno<>10; Note: One of the values returned by the inner query is a null, and hence the entire query returns no rows. The reason is that all conditions that compare anull value result in a null. Sub SELECT statements: y These are SELECT statements declared as part of the SELECT list.
Example: Select ename,sal,(select sum(sal) from emp total salary,(select MIN(sal) from emp) lowest salary from emp; Co-related Sub query: y It is another way of performing queries upon the data with a simulation of joins.
Syntax: select column1,column2 from table1 alias1 where column1 operator(select column1,column2 from table2 alias2 where table1.column operator table2.column); Example: Select deptno,ename,sal from emp e where deptno=(select deptno from dept d where e.deptno=d.deptno); EXISTS: y Returns true if inner query is success other wise false. Example: Select empno,ename,deptno from emp where deptno=10 and EXISTS(Select co unt(*) from emp where deptno=10 and job= ANALYST group by job having count(*)>5); * can nest subqueries inside other subqueries to a depth of 255.
VIEWS: y A view is a database object that is a logical representation of a table. It is delivered from a table but has no storage of its own and often may be used in the same manner as a table. A view takes the output of the query and treats it as a table, therefore a view can be thought of as a stored query or a virtual table. It can be defined as an stored select statement. It will not hold data or store data by itself. It is a logical table based on one or more tables or views. DML, DESC, SELECT allowed on views.
y y y y y
ADVANTAGES: y y Provides high security while sharing data between users. USER_VIEWS hold the details of views.
Syntax: CREATE [OR REPLACE] [FORCE| NOFORCE] VIEW view _name[(alias name)] as Sub query/select statement [with (check option/read only) CONSTRAINT <constraint name>; OR REPLACE: Re creates the view if it is already exists. FORCE: creates a view even the base table does not exists. WITH CHECK OPTION: specifies that only rows accessible to the view can be INSERTED or UPDATED or DELETED. WITH READ ONLY: Ensures that no DML operations can be performed on this view.
TYPES OF VIEWS: 1. Simple view 2. Complex view 1 . Simple view: A simple view can be created on single table. Example: 1. Create view emp_view as select *from employees; 2. Create view student_view as select name student name,sid studentid, marks from student;
2 . Complex view: The view which is created with following clauses Join condition Group by Having clause Set operators Distinct Group function Example: 1. Create view emp_info as select e.empno employeeno,e,ename name,d.deptno departmentid,d.dname from emp e,dept d Where d.deptno=e.deptno order by d.deptno; 2. Create or replace view select e.ename,e.job,d.deptno from emp e,dept d where e.deptno=d.deptno UNION Select ename,sal,com from emp where deptno in(10,20); Modifying a view Example: Create or replace view emp_view as select ename,job from emp where deptno=20; View with column declarations: Example: Create or replace view empv(id_number,name,sal,department-id) as select empno,ename,sal,deptno from emp; DROPPING VIEW: y Dropping a view has no affect on the tables upon which the view is created.
Syntax: DROP VIEW View_name; Example: DROP VIEW emp_view; VIEWS WITH DML
View with not null column -- insert with out not null column not possible -- update not null column to null is not possible -- delete possible View with out not null column which was in base table -- insert not possible -- update, delete possible View with expression -- insert , update not possible -- delete possible View with functions (except aggregate) -- insert, update not possible -- delete possible y View was created but the underlying table was dropped then we will get the message like view has errors . y View was created but the base table has been altered but still the view was with the initial definition, we have to replace the view to affect the changes.
Complex view (view with more than one table) -- insert not possible -- update, delete possible (not always) VIEW WITH CHECK OPTION CONSTRAINT: Example: Create view stud as select *from student where marks = 500 with check option Constraint Ck; - Insert possible with marks value as 500 - Update possible excluding marks column - Delete possible VIEW WITH READ ONLY OPTION: Example: Create or replace view empview (employee_id,employee_name,job_title) as Select employee_id,last_name,job_id from employees where department_id=10 wuth read only; VIEW CONSTRAINTS: y The view constraints are not invoked when the base table is not having any constraints when the base table is having constraints then only the view constraints will be invoked.
y y y
The view constraints are subset of table constraints. Only UNIQUE,PRIMARY KEY and FOREIGN KEY Constraints can be specified on views. The CHECK constraints is imposed using WITH CHECK CONSTRAINTS.
INITIALLY DEFERRED: Oracle should check this CONSTRAINT at the end of the subsequent transactions. NOT DEFERRABLE: Constraint can never be DEFERRED to the end of the transaction. DEFERRABLE: y y y It is not possible to to change NOT DEFERRABLE to INITIALLY DEFERRABLE, In this case drop the constraint and again add the constraint with DEFERRABLE option Then we can modify the constraint to INITIALLY DEFERRED.
SNAPSHOT: y y y y SNAPSHOT is a database object. It is a static picture of data. SNAPSHOT has Structure and Data NO DML possible on snapshot, only SELECT is possible
Syntax : create SNAPSHOT <snapshot name AS Select *from <username>.<objectname>@<databaselink>; Example: Create snapshot sn as select *from scott.emp@orcl. It is static when we do any change on base table there is no effect in snapshot. When we delete base table snapshot data will not be deleted. These are created by DBAs.
Syntax : create MATERIALIZED VIEW <view name> [refresh on commit] [enabled query rewrite] As <select statements>; Example: Create materialized view emp_info enabled query rewrite As select deptno,sum(sal0,count(empno) from emp group by deptno; y y y y To create materialized view we need privilege. Grant query rewrite to <user name> Alter session set QUERY_REWRITE_ENABLED=TRUE; We use this option to read the changes of base table.
HIERARCHICAL Queries: y y These are executed upon tables that contain hierarchical data. To execute the hierarchical queries, we need the following queries
START WITH: it specifies the root rows of the hierarchy. CONNECT BY: It is used to specify the relationship between parent rows and child rows of the hierarchy. WHERE: it is used to restrict the rows returned by the query. Rules: y y y They cannot be used to perform joins. They cannot select data from a view, whose query perform a join. If order by clause is used rows can be returned based on order by clause.
2. Select ename,empno,mgr,job from emp START WITH JOB= PRESIDENT CONNECT BY PRIOR empno=mgr;
PSEUDO COLUMNS: The available pseudo columns are CURRVAL NEXTVAL LEVEL ROWID ROWNUM Currval and Nextval: y y y These are applied upon the SEQUENCE schema object. CURRVAL returns current value of sequence. NEXTVAL returns next value of the sequence.
These can be used only in The SELECT list of SELECT statement. The values clause of INSERT statement. The set clause of UPDATE statement. returns current value of sequence. returns next value of sequence.
SCHEMANAME.SEQUENCENAME.CURRVAL SCHEMANAME.SEQUENCENAME.NEXTVAL.
Creating sequence: CREATE SEQUENCE <SEQUENCENAME> [INCREMENT BY n] [START WITH n] [MAXVALUE n|NOMAXVALUE] [MINVALUE n|NOMINVALUE] [CYCLE |NOCYCLE] [CACHE n|NOCACHE] ORDER/NOORDER; If the above parameters are not specified by default START WITH will be 1 INCREMENT BY will be 1 SEQUENCE is NOCYCLE The CACHE value will be 20 SEQUENCE is ORDER Example: Create sequence deptno INCREMENT BY 10 START WITH 10 MINVALUE 0
Modifying a sequence: Alter sequence <sequence name> [INCREMENT BY n] [MAXVALUE n|NOMAXVALUE] [MINVALUE n|NOMINVALUE] [CYCLE |NOCYCLE] [CACHE n|NOCACHE]; Example: Alter sequence deptno INCREMENT BY 10 MAXVALUE 500 NOCACHE NOCYCLE; *You must be the owner or alter privilege for the sequence to modify it. START WITH option cannot be changed using alter sequence statement. To see the present value of sequence after creating currval execution not possible, atleast one time nextval statement must be execute on the sequence. Select dept.currval from dual; It will give error; Select dept.nextval from dual;
Now we can see the current value. DROPPING sequence: Syntax: drop sequence <sequence name>; DROP sequence dept;
LEVEL: This LEVEL pseudo column returns 1 for root row,2 for a child of a root,and so on. To establish the hierarchical with level we need START WITH Clause CONNECT BY Clause Example: 1. select ename , job, MGR ,Level from emp; 2. Select level,ename,empno,mgr,job from emp start with job=presidentConnect by prior empno=mgr order by level; Select Nth highest value from table Syntax : Select level,max(colname) from <tablename> Where level=&levelno Connect by prior colname>colname Group by level; Example: select level,max(sal) from emp where level=&levelno connect by prior sal>sal group by level; ROWNUM: y y y y The Oracle engine assign a ROWNUM value to each row is it is retrieved. The first row select has a ROWNUM 1,the second has 2,and so on When order by clause follows a ROWNUM ,the row will be re-ordered by order by clause. It can be used in SELECT,WHERE,GROUP FUNCTION,HAVING
Example: 1. select rownum,empno,ename,deptno from emp; 2. Select rownum,empno,ename,sal from emp where rownum<=5; 3. Select rownum,ename from emp group by ronum,ename having mod(ronum,2)=0; ROWID: y y y y ROWID is an exact physical address of row. ROWID is used by oracle to locate any row The ROWID value is assign by oracle itself; ROWIDs are unique identifies for a row in a table
The ROWID can never be INSERTED,UPDATED and DELETED manually. The ROWID pseudo column can be used in SELECT and WHERE clauses. Example: 1. select rowed,empno,enamefrom emp; 2. Select max(rowid) from emp; OLAP features in ORACLE: ROLLUP: y y It is used with group by clause to display the summarized data. ROLLUP grouping produces subtotal and grant total.
Syntax : GROUP BY ROLLUP(col1,col2..) Example: 1. select deptno,job,sum(sal) from emp group by rollup(deptno,job); 2. Select job,deptno,sum(sal) from emp group by rollup(job,deptno); CUBE y y CUBE grouping produces a result set containing the rows from ROLLUP and cross tabulation rows. It is extension similar to ROLLUP.
Syntax: GROUP BY CUBE (col1, col2...) Example: select deptno,job,sum(sal) from emp group by cube(job,deptno);
LOCKS IN TABLE: y y y Locks are the mechanisms cued to prevent destructive interaction between users accessing the same resources simultaneously. A resource can either table or a specific row in a table. Thus locks provide a high degree of data concurrency.
Locks can be acquired at two different levels: 1 . ROW LEVEL LOCK(for specific row): y In row level lock ,a row is locked exclusively so that other users cannot modify the row until the transaction holding the lock is committed or rollback.
Example: select *from emp where empno=7788 FOR UPDATE of hiredate; 2 . TABLE LEVEL LOCK: This will protect table data. Table lock can be in several modes a. Share lock b. Share update lock c. Exclusive lock Syntax : Lock table <table name> in <share or share update or exclusive mode>;
a. Share lock: y A share lock locks the table allowing other users to only query but not INSERT,UPDATE or DELETE rows in a table. Example: lock table emp in share mode; b. Share update lock: y It locks rows that are to be updated in a table. y It permits other users to concurrently query,insert,update or delete even lock other rows in the same table. y It prevents the other users from updating the row that has been locked. Example: lock table emp in share update mode;
c. Exclusive lock:
when it is issued by the user ,it allows the other user to only query but not insert,delete or update rows in a table. y It is almost similar to share lock but only one user can place an exclusive lock on a table at a time, where as many users can place a share lock on the same table at the same time. Example: lock table emp in exclusive mode; y
Note: locks can be released by issuing either rollback or commit; ROLES IN ORACLE: It is a named group of related privileges that can be granted to the user. Rather than assigning privileges one at a time directly to USER, we can CREATE a ROLE, assign PRIVILEGES to that ROLE, and then GRANT that ROLE to multiple USERS and ROLES. Syntax : CREATE ROLE <rolename> IDENTIFIED BY <password>; Example: create role sales_manager identified by manager; Note: we can alter the ROLE for password and new password; Granting Role to user: Example: Grant sales_manager to Scott; Granting multiple roles to another ROLE: Grant ROLE1,ROLE2. TO <target rolename>; Revoking ROLE: Revoke sales_manager from scott; Dropping a ROLE: Syntax : Drop ROLE <rolename> Example: drop role sales_manager; SYNONYMS:
y y y
It is a database object ,which acts as an alternate name for an existing object, Next to view. The create synonym privilege is necessary to create a synonym. DML, description, select allowed on SYNONYM
Synonyms are two types: PRIVATE: created by user. Bused by specific users which have permission. Syntax : create [public] synonym <synonym name> FOR <username>.<objectname>[@database link]; Example: CREATE SYNONYM empdet FOR emp; Create synonym emp_syn for scott.emp; To see synonyms: Select synonym_name from user_synonyms where table_name=emp; PUBLIC SYNONYM: Created by Data Base Administrations. It can accessed by all USERS. Example: CREATE PUBLIC SYNONYM empdet FOR scott.emp; Synonym is created for tables,views,procedures,functions,package DROPPING SYNONYM: Syntax : Drop SYNONYM <synonym name>; Example: DROP synonym empdet; If table is dropped, the synonym created on the table become as invalid.