You are on page 1of 181

Introduction to SQL

DBMS: Data Base Management System 1)In dbms no relationship concept 2)It supports Single User only 3)It treats Data as Files internally 4)It supports 3 rules of E.F.CODD out off 12 rules 5)It requires low Software and Hardware Requirements. 6)DBMS does not impose any constraints or security with regard to data manipulation. It is user or the programmer responsibility to ensure the ACID PROPERTY of the database 7)In DBMS Normalization process will not be present 8)FoxPro, IMS are Examples

RDBMS: Relational Data Base Management System the database which is used by relations(tables) to acquire information retrieval 1)It is used to establish the relationship concept between two database objects, i.e, tables 2)It supports multiple users 3)It treats data as Tables internally 4)It supports minimum 6 rules of E.F.CODD 5)It requires High software and hardware requirements. 6)SQL-Server, Oracle are examples 7)RDBMS is based on relational model, in which data is represented in the form of relations, with enforced relationships between the tables. 8)RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY. 9)In RDBMS, normalization process will be present to check the database table cosistency 10)RDBMS helps in recovery of the database in case of loss of database due to system failure or any other reason
2

What is the difference between VARCHAR, VARCHAR2 and CHAR data types? Both CHAR and VARCHAR2 types are used to store character string values, however, they behave very differently. The VARCHAR type should not be used: CHAR CHAR should be used for storing fix length character strings. String values will be space/blank padded before stored on disk. If this type is used to store variable length strings, it will waste a lot of disk space. SQL> CREATE TABLE char_test (col1 CHAR(10)); Table created. SQL> INSERT INTO char_test VALUES ('qwerty'); 1 row created. SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM char_test;
3

COL1 LENGTH(COL1) ASCII Dump ---------- ------------ ---------------------------------------------------------qwerty 10 Typ=96 Len=10: 113,119,101,114,116,121,32,32,32 ,32 Note: ASCII character 32 is a blank space. VARCHAR Currently VARCHAR behaves exactly the same as VARCHAR2. However, this type should not be used as it is reserved for future usage. SQL> CREATE TABLE varchar_test (col1 VARCHAR2(10)); Table created. SQL> INSERT INTO varchar_test VALUES ('qwerty'); 1 row created.

SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar_test; COL1 LENGTH(COL1) ASCII Dump ---------- ------------ ---------------------------------------------------------qwerty 6 Typ=1 Len=6: 113,119,101,114,116,121 VARCHAR2 VARCHAR2 is used to store variable length character strings. The string value's length will be stored on disk with the value itself. SQL> CREATE TABLE varchar2_test (col1 VARCHAR2(10)); Table created. SQL> INSERT INTO varchar2_test VALUES ('qwerty'); 1 row created.

SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar2_test; COL1 LENGTH(COL1) ASCII Dump ---------- ------------ ---------------------------------------------------------qwerty 6 Typ=1 Len=6: 113,119,101,114,116,121

Oracle Datatypes These Oracle datatypes are as follows: Character Strings

CHAR (size) A fixed-sized field of characters. The largest this particular datatype can become is 2000 bytes. In other words, it can only hold 2000 characters. If you dont specify the length of the

CHAR datatype, the default size is a single character (i.e. 1 byte).

NCHAR (size) A fixed-sized field of characters, where the character set is determined by its definition. So, the maximum size is 2000 bytes per row or 2000 characters. This handles multibyte character sets. VARCHAR2 (size) A variablesized field of characters. The largest this datatype can become is 4000 characters. NVARCHAR2 (size) A variablesized field of characters, where the character set is determined by its definition. The maximum size is 4000 bytes per row or 4000 characters. This handles multibyte character sets.

Note: The VARCHAR2 datatype is the successor of VARCHAR. So it is


7

recommended that you use VARCHAR2 as a variable-sized array of characters.

LONG A variable-sized field of characters. The maximum size of this field is 2GB. NUMBER (precision, scale) A variable-sized number, where the precision is between 1 and 38 and size is between -84 and 127. A NUMBER datatype with only one parameter is NUMBER (precision), where the parameter specifies the precision of the number. A NUMBER datatype with no parameters is set to its maximum size. DATE A fixed-sized 7 bit field that is used to store dates. One
8

Number

Date and Time

thing to note is that the time is stored as part of the date. The default format DD-MON-YY can be overridden by NLS_DATE_FORMAT.

TIMESTAMP (precision) A variable-sized value ranging from 7 to 11 bytes, that is used to represent a date/time value. It includes both date and time. The precision parameter determines how many numbers are in the fractional part of SECOND field. The precision of the SECOND field within the TIMESTAMP value may have a value ranging from 0 to 9 with a default precision of 6. TIMESTAMP (precision) WITH TIME ZONE A fixed-sized value of 13 bytes, which represents a date/time value along with a time zone setting. There are two ways one can set the time zone. The first is by using the UTC offset, say
9

+10:0, or secondly by the region name, say Australia/Sydney.

TIMESTAMP (precision) WITH LOCAL TIME A variable value ranging from 7 to 11 bytes. This particular datatype is similar to the TIMESTAMP WITH TIME ZONE datatype. The difference is that the data is normalised to the database time zone when stored. The entry is manipulated to concur with the clients time zone when retrieved. INTERVAL DAY (day_precision) TO SECOND (second_precision) A fixed-sized 11 byte value that represents a period of time. It includes days, hours, minutes and seconds. INTERVAL YEAR (year_precision) TO MONTH - A fixed-sized 5 byte value that
10

Intervals

represents a period of time. It includes years and months. Binaries

RAW (size) A variable-sized field of raw binary data. The maximum size for this datatype is 2000 bytes. LONG RAW - A variable-sized field of raw binary data. The maximum size for this datatype is 2 GB. BLOB The Binary Large Object is a field that holds unstructured binary data. The maximum size for this datatype is 4 GB. CLOB The Character Large Object is a field that holds single byte character data. The maximum size for this datatype is 4 GB.

11

NCLOB The National Character Large Object is a field that holds either single byte of multibyte character data dependent on the national character set. The maximum size for this datatype is 4 GB. BFILE An external binary file. The maximum size for this file is 4 GB. The size is also limited by the operating system. ROWID A datatype that contains binary data that is used to identify a row. 6 bytes for normal indexes on non-partitioned tables, local indexes on partitioned tables and row pointers for chained/migrated rows.
12

Rows

Each ROWID is:


o

10 bytes for global indexes on partitioned tables.

UROWID The Universal ROWID is the datatype used to store both logical and physical ROWID values as well as foreign tables accessed through a gateway.

Alternatives for ANSI Standard Datatypes Instead of using ANSI standard datatypes, you can use Oracle defined datatypes. View the table below to see the Oracle datatype alternative for ANSI standard datatypes. ANSI Standard CHARACTER and CHAR Oracle Datatype CHAR

13

CHARACTER VARCHAR2 VARYING and CHAR VARYING NUMERIC, NUMBER DECIMAL, DEC, INTEGER, INT and SMALLINT FLOAT, REAL, FLOAT DOUBLE PRECISION DATE (DD/MMM/YYYY) DATE

14

15

SQL Structured Query Language SQL is a standard language for accessing and manipulating databases. SQL is the set of commands used to access data within the Oracle Database. SQL Commands: 1. DDL (Data Commands Definition Language)

Commands that define or delete database objects such as tables or views. CREATE, ALTER, DROP

To create a table: CREATE TABLE (column_name datatype [column_constriant]);


16

table_name

Eg. CREATE TABLE student(regno number(10), name varchar2(20), course varchar2(10)); To add a new column : ALTER TABLE table_name ADD (column_name datatype [column_constraint]);

Eg. ALTER TABLE ADD(college varchar2(20));

student

To modify existing column: ALTER TABLE table_name (column_name [column_constraint]); Eg. ALTER TABLE MODIFY(name varchar2(30)); MODIFY datatype student

17

To rename the existing column: ALTER TABLE tablename RENAME COLUMN oldcolumn TO newcolumn; Eg. ALTER TABLE student RENAME COLUMN regno TO rno; To drop a column: ALTER TABLE tablename COLUMN column_name; Eg: ALTER COLUMN name; TABLE stud DROP DROP

To drop multiple columns: ALTER TABLE tablename DROP(column_name1,column_name2); Eg: ALTER TABLE (mark1,mark2); student DROP

To rename the existing table: ALTER TABLE oldtablename RENAME TO newtablename;

18

Eg. ALTER TABLE student RENAME TO stud; To drop a table: DROP TABLE table_name; Eg. DROP TABLE student; 2. DML (Data Manipulation Language) Commands Commands that query and update the actual data. SELECT, INSERT, UPDATE, DELETE To select particular column SELECT "column_name" "table_name"; SELECT store_name Store_Information; To select all columns SELECT * FROM tablename;
19

FROM FROM

SELECT * FROM Store_Information;

To insert values to all columns of the table (need not the specify the column names) INSERT INTO "table_name" ("value1","value2", ...); INSERT INTO values(10032,aparna,100,98,97); VALUES student

To insert values to particular columns of the table (need to specify the column names) INSERT INTO ("column1","column2",...) ("value1","value2", ...); "table_name" VALUES

INSERT INTO Store_Information (store_name, Sales, Date) VALUES ('Los Angeles', 900, 'Jan-101999'); TO INSERT MULTIPLES ROWS USING SINGLE INSERT
20

You can insert multiple rows using the following syntax: INSERT ALL INTO mytable (column1, column2, column3) VALUES ('val1.1', 'val1.2', 'val1.3') INTO mytable (column1, column2, column3) VALUES ('val2.1', 'val2.2', 'val2.3') INTO mytable (column1, column2, column3) VALUES ('val3.1', 'val3.2', 'val3.3') SELECT * FROM dual;

Example #1 If you wanted to insert 3 rows into the suppliers table, you could run the following SQL statement: INSERT ALL INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM') INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft') INTO suppliers (supplier_id,

21

supplier_name) VALUES (3000, 'Google') SELECT * FROM dual;

TO INSERT MULTIPLE ROWS IN MULTIPLE TABLES USING SINGLE INSERT You can also insert multiple rows into multiple tables. For example, if you wanted to insert into both the suppliers and customers table, you could run the following SQL statement: INSERT ALL INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM') INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft') INTO customers (customer_id, customer_name, city) VALUES (999999,

22

'Anderson Construction', 'New York') SELECT * FROM dual; This example will insert 2 rows into the suppliers table and 1 row into the customers table.

To update any column value UPDATE "table_name" SET "column_1" = [new value] WHERE {condition} UPDATE Store_Information SET Sales = 500 WHERE store_name = "Los Angeles" AND Date = "Jan-08-1999" To delete a specific row/record DELETE FROM "table_name" WHERE {condition that uniquely identify specific record}; DELETE FROM Store_Information WHERE store_name = "Los Angeles"

To delete all rows / records


23

DELETE FROM table_name; DELETE FROM Store_Information; NOTE: THE SENSITIVE VALUES ARE CASE

The value sastra to the column college is difference from the value SASTRA. Difference between Truncate & Delete Truncate: It is a DDL command. Cannot rollback Memory released immediately Where clause cannot be used

Delete: DML command Can rollback Memory not released immediately Where clause can be used

24

3. DCL (Data Commands

Control

Language)

Commands that control access to the data and to the database GRANT, REVOKE GRANT Statement The GRANT Statement grants access privileges for database objects to other users. It has the following general format: GRANT privilege-list object-list TO user-list ON [TABLE]

privilege-list is either ALL PRIVILEGES or a comma-separated list of properties: SELECT, INSERT, UPDATE, DELETE. object-list is a comma-separated list of table and view names. user-list is either PUBLIC or a comma-separated list of user names.

25

GRANT Statement Examples GRANT SELECT ON s,sp TO PUBLIC GRANT SELECT,INSERT,UPDATE(color) ON p TO art,nan GRANT SELECT ON supplied_parts TO sam WITH GRANT OPTION

REVOKE Statement The REVOKE Statement revokes access privileges for database objects previously granted to other users. It has the following general format: REVOKE privilege-list ON [TABLE] object-list FROM user-list The REVOKE Statement revokes each privilege in privilege-list for each object (table) in objectlist from each user in user-list. All privileges must have been previously granted.
26

REVOKE Statement Examples REVOKE SELECT ON s,sp FROM PUBLIC REVOKE SELECT,INSERT,UPDATE(color) ON p FROM art,nan REVOKE SELECT ON supplied_parts FROM sam

To view all the created table names in your user area: SELECT * FROM TAB; Or SELECT * FROM CAT;

To see the description of the created table:


27

DESC tablename; DESC student;

To clear screen: Clear scr;

KEY CONSTRAINTS You can place constraints to limit the type of data that can go into a table. Such constraints can be specified when the table when the table is first created via the CREATE TABLE statement, or after the table is already created via the ALTER TABLE statement.

28

Common types of constraints include the following:

NOT NULL Constraint: Ensures that a column cannot have NULL value. DEFAULT Constraint: Provides a default value for a column when none is specified. UNIQUE Constraint: Ensures that all values in a column are different. CHECK Constraint: Makes sure that all values in a column satisfy certain criteria. Primary Key Constraint: Used to uniquely identify a row in the table. Foreign Key Constraint: Used to ensure referential integrity of the data.

Primary Key constraint A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do with the actual record). A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key.

29

Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the existing table structure (using ALTER TABLE). Below are examples for specifying a primary key when creating a table: CREATE TABLE table_name(column_name data_type CONSTRAINT constraint_name); CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name varchar(30)); Below are examples for specifying a primary key by altering a table: ALTER TABLE table_name constraint_name(column_name) ALTER TABLE Customer PRIMARY KEY (SID); ADD

ADD

Note: Before using the ALTER TABLE command to add a primary key, you'll need to
30

make sure that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.

To add primary key constraint while creating the table without constraint name CREATE TABLE table_name(column_name data_type PRIMARY KEY); Create table st (regno number(10) primary key, name varchar2(10));

To add constraint primary key while creating the table with constraint name CREATE TABLE table_name(column_name data_type CONSTRAINT constraint_name PRIMARY KEY);

31

Create table constraint pk1 varchar2(10));

st (regno number(10) primary key, name

To add primary key constraint after creating the table ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY(column_name); alter table st add constraint pk1 primary key(regno); Composite Primary Key A key that consists of 2 or more attributes that uniquely identify an entity occurrence CREATE TABLE track( album CHAR(10), disk INTEGER, posn INTEGER, song VARCHAR(255),
32

PRIMARY KEY (album, disk, posn) ) To create a dummy table with the same contents(with all columns) of some other table CREATE TABLE dummy_table_name AS SELECT * FROM old_table_name; create table st1 as select * from st; To create a dummy table with same contents(with some specified columns) of some other table CREATE TABLE dummy_table(column1, column2,) AS SELECT column1,column2,.. FROM copying_table; create table st2(reg,name) regno,name from st; as select

To create a dummy table with the same description of some other table ( with no contents copied to new table)

33

CREATE TABLE dummy_table AS SELECT * FROM copying_table WHERE false_condition; Create table st1 as select * from st2 where 1>2; (when any false condition is given in where clause while creating dummy table no contents will be copied to new table) Foreign Key constraint A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted. For example, say we have two tables, a CUSTOMER table that includes all customer data, and an ORDERS table that includes all customer orders. The constraint here is that all orders must be associated with a customer that is already in the CUSTOMER table. In this case,
34

we will place a foreign key on the ORDERS table and have it relate to the primary key of the CUSTOMER table. This way, we can ensure that all orders in the ORDERS table are related to a customer in the CUSTOMER table. In other words, the ORDERS table cannot contain information on a customer that is not in the CUSTOMER table.

The structure of these two tables will be as follows: Table CUSTOMER column name characteristic SID Primary Key Last_Name First_Name Table ORDERS
35

column name characteristic Order_ID Primary Key Order_Date Customer_SID Foreign Key Amount In the above example, the Customer_SID column in the ORDERS table is a foreign key pointing to the SID column in the CUSTOMER table. Below we show examples of how to specify the foreign key when creating the ORDERS table: CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date date, Customer_SID integer references CUSTOMER(SID), Amount double); Below are examples for specifying a foreign key by altering a table. This assumes that the ORDERS table has been created, and the foreign key has not yet been put in:

36

ALTER TABLE ORDERS ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); alter table st2 add constraint fk1 foreign key(reg) references st(regno);

Check Constraint The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the database will only insert a new row or update an existing row if the new value satisfies the CHECK constraint. The CHECK constraint is used to ensure data quality

37

For example, in the following CREATE TABLE statement, CREATE TABLE Customer (SID integer CHECK (SID > 0), Last_Name varchar (30), First_Name varchar(30)); Column "SID" has a constraint -- its value must only include integers greater than 0. So, attempting to execute the following statement, INSERT INTO Customer 3','Gonzales','Lynn'); values ('-

will result in an error because the values for SID must be greater than 0. alter table st check(age<=100)); add(age number(3)

insert into st values(1006,'fff','cse',101); Unique Constraint The UNIQUE constraint ensures that all values in a column are distinct.

38

For example, in the following CREATE TABLE statement, CREATE TABLE Customer (SID integer Unique, Last_Name varchar (30), First_Name varchar(30)); column "SID" has a unique constraint, and hence cannot include duplicate values. Such constraint does not hold for columns "Last_Name" and "First_Name". So, if the table already contains the following rows: SID Last_Name First_Name 1 Johnson Stella 2 James Gina 3 Aaron Ralph

Executing the following SQL statement, INSERT INTO ('3','Lee','Grace'); Customer values

will result in an error because '3' already exists in the SID column, thus trying to insert another
39

row with that value violates the UNIQUE constraint. Please note that a column that is specified as a primary key must also be unique. At the same time, a column that's unique may or may not be a primary key. In addition, multiple UNIQUE constraints can be defined on a table. alter table st add constraint uk1 unique(name); not null constraint By default, a column can hold NULL. If you not want to allow NULL value in a column, you will want to place a constraint on this column specifying that NULL is now not an allowable value. For example, in the following statement, CREATE TABLE Customer (SID integer NOT NULL, Last_Name varchar (30) NOT NULL, First_Name varchar(30));

40

Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL. An attempt to execute the following SQL statement, INSERT INTO Customer (Last_Name, First_Name) values ('Wong','Ken'); will result in an error because this will lead to column "SID" being NULL, which violates the NOT NULL constraint on that column. alter table st modify(regno constraint nn not null);

Default constraint The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value. For example, if we create a table as below:

41

CREATE TABLE Student (Student_ID integer Unique, Last_Name varchar (30), First_Name varchar (30), Score DEFAULT 80); and execute the following SQL statement, INSERT INTO Student (Student_ID, Last_Name, First_Name) values ('10','Johnson','Rick'); The table will look like the following: Student_ID Last_Name First_Name Score 10 Johnson Rick 80 Even though we didn't specify a value for the "Score" column in the INSERT INTO statement, it does get assigned the default value of 80 since we had already set 80 as the default value for this column. alter table st modify(branch default cse); To insert the same contents into some other table

42

insert into st1(regno,name,branch) select regno,name,branch from st;

To view the constraints select table_name,constraint_name, constraint_type from user_constraints;

To drop constraint alter table st drop constraint uk1; To drop primary key constraint without dropping foreign key constraint (Cascade) alter table st drop constraint_name cascade; constraint

To delete parent record without without deleting child record


43

(on delete cascade) alter table st add constraint fk2 foreign key(reg) references st(regno) on delete cascade;

NOTE: (I) CONDITION TO DROP PARENT TABLE( IF TABLE HAS PRIMARY AND FOREIGN KEYS CONSTRAINTS AND NOT CASCADED)

FIRST CHILD TABLE SHOULD BE DROPPED AND THEN ONLY PARENT TABLE SHOULD BE DROPPED. (II) CONDITION TO INSERT RECORDS ( IF TABLE HAS PRIMARY AND FOREIGN KEYS CONSTRAINTS AND NOT CASCADED) FIRST RECORDS SHOULD BE INSERTED INTO PARENT TABLE AND THEN ONLY

44

IT SHOULD BE INSERTED INTO CHILD TABLE. (III) CONDITION TO DELETE RECORDS ( IF TABLE HAS PRIMARY AND FOREIGN KEYS CONSTRAINTS AND NOT CASCADED)

FIRST RECORDS SHOULD BE DELETED FROM CHILD TABLE AND THEN ONLY IT SHOULD BE DELETED FROM PARENT TABLE.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema.

Column OWNER

Datatype

NULL D VARCHAR2(30) NOT O c NULL d

45

Column CONSTRAINT_NAME

Datatype

NULL D VARCHAR2(30) NOT N c NULL d VARCHAR2(1)

CONSTRAINT_TYPE

T c d

46

Column

Datatype

NULL D

TABLE_NAME

VARCHAR2(30)

SEARCH_CONDITION

LONG

R_OWNER

VARCHAR2(30)

R_CONSTRAINT_NAME

VARCHAR2(30)

N a NULL th v c d T c c O re re c N u c NOT

47

Column

Datatype

DELETE_RULE

VARCHAR2(9)

NULL D d re D re c (

STATUS

VARCHAR2(8)

E s c (

DEFERRABLE

VARCHAR2(14)

DEFERRED

VARCHAR2(9)

W c d W c in d

48

Column VALIDATED

Datatype

NULL D W VARCHAR2(13) o c (

GENERATED

VARCHAR2(14)

W n c u g

BAD

VARCHAR2(3)

in th s c a m a re th
49

Column

Datatype

NULL D re c th

fu fo S

RELY

VARCHAR2(4)

fu O S a D A D G F W e c e u S

50

Column

Datatype

LAST_CHANGE

INDEX_OWNER

INDEX_NAME

INVALID

VIEW_RELATED

NULL D c O S W DATE c la d N VARCHAR2(30) u in N VARCHAR2(30) in s u p c W VARCHAR2(7) c in W VARCHAR2(14) c d

51

Column

Datatype

NULL D v

SQL LOGICAL OPERATORS

= - Equal to != or <> - Not equal to > - Greater than

52

>= - Greater than or equal to < - Less than <= - Less than or equal to in - Equal to any item in a list not in - Not equal to any item in a list between - Between two values, greater than or equal to one and less than or equal to the other

not between - Not between two values begins with - Begins with specified value contains - Contains specified value not contains - Does not contain specified value
53

is null - Is blank is not null - Is not blank like - Like a specified pattern. % means any series of characters. _ means any single character.

not like - Not like a specified pattern. % means any series of characters. _ means many single character.

AND / OR The syntax for a compound condition is as follows: SELECT "column_name" FROM "table_name" WHERE "simple condition" {[AND|OR] "simple condition"}+
54

SELECT store_name FROM Store_Information WHERE Sales > 1000 OR (Sales < 500 AND Sales > 275)

IN SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...)

SELECT * FROM Store_Information WHERE store_name IN ('Los Angeles', 'San Diego')

BETWEEN

55

SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND 'value2' SELECT * FROM Store_Information WHERE Date BETWEEN 'Jan-06-1999' AND 'Jan-10-1999'

LIKE SELECT FROM WHERE {PATTERN} "column_name" "table_name" "column_name" LIKE

character, and end with 'Z'. For example, 'ABZ' and 'A2Z' would both satisfy the condition, while 'AKKZ' would not (because there are two characters between A and Z instead of one).

56

s that start with 'ABC'. For example, 'ABCD' and 'ABCABC' would both satisfy the condition. example, 'WXYZ' and 'ZZXYZ' would both satisfy the condition. 'AN' anywhere. For example, 'LOS ANGELES' and 'SAN FRANCISCO' would both satisfy the condition.

SELECT * FROM Store_Information WHERE store_name LIKE '%AN%'

ORDER BY we need to list the output in a particular order. This could be in ascending order, in descending order, or could be based on either numerical value or text value. In such cases, we can use the ORDER BY keyword to achieve our goal.

57

SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC] The [] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before the ORDER BY clause. ASC means that the results will be shown in ascending order, and DESC means that the results will be shown in descending order. If neither is specified, the default is ASC. It is possible to order by more than one column. In this case, the ORDER BY clause above becomes ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]

AGGREGATE FUNCTIONS Aggregate functions are statistical functions such as count, min, max etc. They are used to compute a single value from a set of attribute values of a column:

58

AVG,SUM,COUNT,MIN,MAX count Counting Rows Example: How many tuples are stored in the relation EMP? select count(_) from EMP; Example: How many different job titles are stored in the relation EMP? select count(distinct JOB) from EMP; max Maximum value for a column min Minimum value for a column Example: List the minimum and maximum salary. select min(SAL), max(SAL) from EMP; Example: Compute the difference between the minimum and maximum salary. select max(SAL) - min(SAL) from EMP; sum Computes the sum of values (only applicable to the data type number)
59

Example: Sum of all salaries of employees working in the department 30. select sum(SAL) from EMP where DEPTNO = 30; avg Computes average value for a column (only applicable to the data type number) Note: avg, min and max ignore tuples that have a null value for the specified attribute, but count considers null values.

GROUP BY (USED WHENEVER AGGREGATE FUNCTIONS ARE USED) SELECT SUM(M1) FROM ST GROUP BY BRANCH; HAVING SELECT avg(M1) FROM ST GROUP BY BRANCH HAVING SUM(M1)>500;

60

select * from worker where age>any(select age from worker where age=30); select * from worker where age>all(select age from worker where age=30);

ANY select * from worker where age>any(select age from worker where age in(32,34)); (value 33 is applicable) ALL select * from worker where age>all(select age from worker where age in(32,34)); (Here age values must be greater than 34, which is maximum value ) EXISTS select phone from workerskill wk where exists(select name from worker w where wk.name=w.name);

61

DISPLAY FORM

COLUMNS

IN

SPECIFIED

SELECT SNO AS SERIAL, STUDENT_NAME FROM ST;

SNAME

UNION SELECT NAME FROM WORKER UNION SELECT NAME FROM WORKERSKILL; (NO DUPLICATES) UNION ALL SELECT NAME FROM WORKER UNION ALL SELECT NAME FROM WORKERSKILL; (WITH DUPLICATES) INTERSECT

62

SELECT NAME FROM WORKER INTERSECT SELECT NAME FROM WORKERSKILL; (COMMON VALUES)

MINUS SELECT NAME FROM WORKER MINUS SELECT NAME FROM WORKERSKILL; (REMOVING COMMON VALUES AND DISPLAY THE REMAINING VALUES FROM THE TABLE IN THE FIRST QUEREY) DISTINCT SELECT DISTINCT AGE FROM WORKER;

63

SUBQUERIES What is a subquery? A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

SQL> select * from books; TITLE YEAR PRICE ------------------------------ -------------------- --------64

sql dbms java c++ c# sql 6 rows selected.

2000 1998 1991 1990 2001 1999

600 900 450 750 200 450

SQL> select * from list; TITLE PUBLICATION AUTHOR ------------------------------ -------------------- ------------------c++ tmh balaguruswamy java oxford press herbert schildt dbms mit press john beck sql tmh v.k.jain c margoa m.l.khanna

65

WHERE CLAUSE (nested subquery) Subquery is given in where clause. A subquery in the WHERE clause of a SELECT statement is also called a nested subquery. You can nest up to 255 levels of subqueries in the WHERE clause. SQL> select title,year,price from books where books.price > (select avg 2 (price) from books); TITLE YEAR PRICE ------------------------------ -------------------- --------sql 2000 600 dbms 1998 900 c++ 1990 750

66

SELECT empno,ename,sal,sal*12 AS AnnSal FROM emp WHERE AnnSal > 30000 The above query will result in an error saying that AnnSal is an Invalid Identifier SELECT empno,ename,sal,AnnSal FROM (SELECT empno,ename,sal,sal*12 AS AnnSal FROM emp) WHERE AnnSal > 30000 The above statement is totally different from the previous one. Within the above statement, the outer query doesnt rely on any specific physical table. The output (or result set) of the inner query is considered as a table for the outer query! The inner query is very similar to that of a view which doesnt have any physical view name, and it gets created and destroyed on the fly. SQL> select * from books where price>(select avg(price) from books where title in (select title from list where publication='tmh'));
67

TITLE YEAR PRICE ------------------------------ -------------------- --------dbms 1998 900 c++ 1990 750

FROM CLAUSE (inline view) Subquery is given in from clause A subquery in the FROM clause of a SELECT statement is also called an inline view. Oracle Database imposes no limit on the number of subquery levels in the FROM clause of the top-level query. SQL> select list.author,sq1.total_price from list,(select title,sum(books.price)as total_price from books group by title)sq1 where list.title=sq1.title;

68

AUTHOR TOTAL_PRICE -------------------- ----------balaguruswamy 750 john beck 900 herbert schildt 450 v.k.jain 1050 SQL> select * from books,(select author from list where publication='tmh' and author in (select author from list)); TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------c# 2001 200 balaguruswamy c++ balaguruswamy dbms 1990 750

1998
69

900

balaguruswamy

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------java 1991 450 balaguruswamy sql balaguruswamy sql balaguruswamy 1999 450

2000

600

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------70

c# v.k.jain c++ v.k.jain dbms v.k.jain

2001

200

1990

750

1998

900

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------java 1991 450 v.k.jain sql v.k.jain sql v.k.jain 1999 450

2000

600

71

12 rows selected.

SQL> select * from books,(select author from list where publication='tmh' or author in(select author from list)); TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------sql 2000 600 balaguruswamy dbms balaguruswamy java balaguruswamy 1998 900

1991

450

72

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------c++ 1990 750 balaguruswamy c# balaguruswamy sql balaguruswamy 2001 200

1999

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------sql 2000 600 herbert schildt
73

dbms herbert schildt java herbert schildt

1998

900

1991

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------c++ 1990 750 herbert schildt c# herbert schildt sql herbert schildt 2001 200

1999

450

74

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------sql 2000 600 john beck dbms john beck java john beck 1998 900

1991

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------c++ 1990 750 john beck

75

c# john beck sql john beck

2001

200

1999

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------sql 2000 600 v.k.jain dbms v.k.jain java v.k.jain 1998 900

1991

450

TITLE PRICE
76

YEAR

------------------------------ -------------------- --------AUTHOR -------------------c++ 1990 750 v.k.jain c# v.k.jain sql v.k.jain 2001 200

1999

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------sql 2000 600 m.l.khanna dbms m.l.khanna 1998 900

77

java m.l.khanna

1991

450

TITLE YEAR PRICE ------------------------------ -------------------- --------AUTHOR -------------------c++ 1990 750 m.l.khanna c# m.l.khanna sql m.l.khanna 2001 200

1999

450

30 rows selected.

78

SQL> select * from books; TITLE YEAR PRICE ------------------------------ -------------------- --------sql 2000 600 dbms 1998 900 java 1991 450 c++ 1990 750 c# 2001 200 sql 1999 450 6 rows selected. SQL> select * from list; TITLE PUBLICATION AUTHOR ------------------------------ -------------------- ------------------c++ tmh balaguruswamy java oxford press herbert schildt
79

dbms sql c

mit press tmh margoa

john beck v.k.jain m.l.khanna

SELECT CLAUSE(SUBQUERY) Subquery is given in select clause. SQL> select books.price ,list.author,(select publication from list where books.title=list.title) from books,list; PRICE AUTHOR (SELECTPUBLICATIONFR ---------- -------------------- -------------------600 balaguruswamy tmh 900 balaguruswamy mit press 450 balaguruswamy oxford press 750 balaguruswamy tmh 200 balaguruswamy 600 herbert schildt tmh
80

900 herbert schildt 450 herbert schildt 750 herbert schildt 200 herbert schildt 600 john beck

mit press oxford press tmh tmh

PRICE AUTHOR (SELECTPUBLICATIONFR ---------- -------------------- -------------------900 john beck mit press 450 john beck oxford press 750 john beck tmh 200 john beck 600 v.k.jain tmh 900 v.k.jain mit press 450 v.k.jain oxford press 750 v.k.jain tmh 200 v.k.jain 600 m.l.khanna tmh 900 m.l.khanna mit press PRICE AUTHOR (SELECTPUBLICATIONFR ---------- -------------------- -------------------450 m.l.khanna oxford press
81

750 m.l.khanna 200 m.l.khanna

tmh

Correlated Subquery

A correlated subquery is a subquery that is evaluated once for each row of the outer query. You can reference the outer query inside the correlated subquery using an alias which makes it so handy to use. A correlated subquery answers a multiple-part question whose answer depends on the value in each row processed by the parent statement.

82

JOINS Used to combine the data spread across tables. CARTESIAN JOIN Joining two tables without any condition SQL> select * from pc, product_info;

Syntax: SELECT COLUMNS FROM TABLE1, TABLE2 WHERE LOGICAL EXPRESSION; Types Simple join Self join Outer join Simple Join It retrieves rows from two tables having a common column .

83

Equi join Non equi join

EQUI JOIN A join which is based on equalities. A comparison operator (=) is used in the where clause to perform this join. SQL> select * from worker; NAME AGE ------------------------------ ---------dick jones 33 william swing 30 bart sarjeant 32 suma ranganath 21 richard williams 29 bharat kumar 36 john pearson 28 jackson 34 meena kumari 29 adah talbot 27 10 rows selected.
84

SQL> select * from workerskill; NAME SKILL ------------------------------ ----------------------------CITY PHONE ------------------------------ ----------------------------DICK JONES SMITHY TRICHY 91-0437-77651 JOHN PEARSON DRIVER CHENNAI HELEN BRANDT DRIVER MADURAI COMBINE 91-0426-98721 COMBINE 91-0435-33333

NAME SKILL ------------------------------ ----------------------------CITY PHONE


85

------------------------------ ----------------------------JOHN PEARSON COMBINE DRIVER CHENNAI 91-0453-98765 JOHN PEARSON MADURAI VICTORIA LYNN SYDNEY SMITHY 91-0345-34565 SMITHY 91-0234-98723

NAME SKILL ------------------------------ ----------------------------CITY PHONE ------------------------------ ----------------------------ADAH TALBOT WORK THANJAVUR 91-0652-66544 ELBERT LOWELL DELHI DISCUS 91-0433-90875

86

WILFRED LOWELL SALEM

WORK 91-0213-98723

NAME SKILL ------------------------------ ----------------------------CITY PHONE ------------------------------ ----------------------------ANAND KUMAR PROGRAM ERODE 91-0441-98123 JACKSON HOSUR PROGRAM 91-0543-90873

11 rows selected.

EQUI JOIN EXAMPLE

87

SQL> SELECT W.NAME,SKILL FROM WORKER W, WORKERSKILL WS WHERE W.NAME=WS.NAME; NAME SKILL ------------------------------ ----------------------------ADAH TALBOT WORK DICK JONES SMITHY JACKSON PROGRAM JOHN PEARSON COMBINE DRIVER JOHN PEARSON COMBINE DRIVER JOHN PEARSON SMITHY 6 rows selected. Using Natural join: SQL> select * workerskill; NAME CITY
88

from worker natural join

AGE SKILL

-------------------- ---------- -------------------- ------------------PHONE ---------adah talbot 27 work thanjavur 9.1065E+10 dick jones 9.1044E+11 33 smithy trichy

NON EQUI JOIN Make use of relational operators other than =. EXAMPLE SQL> SELECT W.NAME, AGE,SKILL FROM WORKER W, WORKERSKILL WS WHERE AGE>30 AND W.NAME=WS.NAME; NAME AGE SKILL

89

------------------------------ ---------- ----------------------------DICK JONES 33 SMITHY JACKSON 34 PROGRAM SELF JOIN Joining of a table to itself. Used to compare each row of the table to itself and also with other rows of the same table. EXAMPLE SQL> SELECT * FROM EMPTAB1; EMPNO EMPNAME MGRNO ---------- -------------------- ---------101 RAJESH 501 102 SURESH 501 201 JAYA 601 202 VIJAY 601 501 RAM 1001 601 MAGESH 1001 1001 ARUN
90

7 rows selected. SQL> SELECT A.EMPNAME, B.EMPNAME FROM EMPTAB1 A, EMPTAB1 B 2 WHERE A.MGRNO = B.EMPNO; EMPNAME EMPNAME -------------------- -------------------RAJESH RAM SURESH RAM JAYA MAGESH VIJAY MAGESH RAM ARUN MAGESH ARUN

6 rows selected. INNER JOIN & ON(KEYWORD)

SQL> select w.name, w.age, ws.skill from worker w inner join workerskill ws on w.name=ws.name;
91

NAME AGE SKILL ------------------------------ ---------- ----------------------------ADAH TALBOT 27 WORK DICK JONES 33 SMITHY JACKSON 34 PROGRAM JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 SMITHY 6 rows selected.

INNER JOIN & USING (KEYWORD) SQL> select name, age, skill from worker inner join workerskill using(name); NAME AGE SKILL ------------------------------ ---------- ----------------------------92

ADAH TALBOT DICK JONES JACKSON JOHN PEARSON COMBINE DRIVER JOHN PEARSON COMBINE DRIVER JOHN PEARSON 6 rows selected.

27 WORK 33 SMITHY 34 PROGRAM 28 28 28 SMITHY

OUTER JOIN Extension of simple join Returns all the rows returned by simple join as well as those rows from one table that do not match any row from the other table. TYPES Left outer join
93

Right outer join Full outer join RIGHT OUTER JOIN(KEYWORD) SQL> select w.name,w.age,ws.skill from worker w right outer join workerskill ws on w.name=ws.name; NAME AGE SKILL ------------------------------ ---------- ----------------------------DICK JONES 33 SMITHY JOHN PEARSON 28 SMITHY JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 COMBINE DRIVER JACKSON 34 PROGRAM ADAH TALBOT 27 WORK PROGRAM DISCUS SMITHY WORK COMBINE DRIVER
94

11 rows selected. SQL>

RIGHT OUTER JOIN EXAMPLE

SQL> SELECT W.NAME,SKILL FROM WORKER W, WORKERSKILL WS WHERE W.NAME(+)=WS.NAME;

NAME SKILL ------------------------------ ----------------------------ADAH TALBOT WORK PROGRAM DICK JONES SMITHY DISCUS COMBINE DRIVER JACKSON PROGRAM

95

JOHN PEARSON DRIVER JOHN PEARSON DRIVER JOHN PEARSON SMITHY WORK 11 rows selected.

COMBINE COMBINE SMITHY

LEFT OUTER JOIN (KEYWORD) SQL> select w.name,w.age,ws.skill from worker w left outer join workerskill ws on w.name=ws.name; NAME AGE SKILL ------------------------------ ---------- ----------------------------DICK JONES 33 SMITHY JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 SMITHY
96

ADAH TALBOT JACKSON WILLIAM SWING RICHARD WILLIAMS BHARAT KUMAR SUMA RANGANATH BART SARJEANT

27 WORK 34 PROGRAM 30 29 36 21 32

NAME AGE SKILL ------------------------------ ---------- ----------------------------MEENA KUMARI 29 12 rows selected.

LEFT OUTER JOIN EXAMPLE

SQL> SELECT W.NAME,SKILL FROM WORKER W, WORKERSKILL WS WHERE W.NAME=WS.NAME(+);

97

NAME SKILL ------------------------------ ----------------------------ADAH TALBOT WORK BART SARJEANT BHARAT KUMAR DICK JONES SMITHY JACKSON PROGRAM JOHN PEARSON COMBINE DRIVER JOHN PEARSON COMBINE DRIVER JOHN PEARSON SMITHY MEENA KUMARI RICHARD WILLIAMS SUMA RANGANATH NAME SKILL ------------------------------ ----------------------------WILLIAM SWING 12 rows selected. FULL OUTER JOIN(KEYWORD)
98

SQL> select w.name,w.age,ws.skill from worker w full outer join workerskill ws on w.name =ws.name; NAME AGE SKILL ------------------------------ ---------- ----------------------------DICK JONES 33 SMITHY JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 COMBINE DRIVER JOHN PEARSON 28 SMITHY ADAH TALBOT 27 WORK JACKSON 34 PROGRAM WILLIAM SWING 30 RICHARD WILLIAMS 29 BHARAT KUMAR 36 SUMA RANGANATH 21 BART SARJEANT 32 NAME AGE SKILL

99

------------------------------ ---------- ----------------------------MEENA KUMARI 29 PROGRAM DISCUS SMITHY WORK COMBINE DRIVER 17 rows selected.

Nvl (Null Value) Used in the case where we want to consider NULL values as zero. Syntax Nvl(exp1, exp2) If exp1 is null, nvl will return exp2. If exp1 is not null, nvl will return exp1.

100

If exp1 and exp2 are of different datatypes, then exp2 is converted to the data type of exp1 compares it.

Example: SQL> select model_no, nvl(speed, 10) from pc;

Before using NVL function ------ ------------PC112 PC132 PC134 PC100 PC126 2 1 1 3

After using NVL function

101

MODEL_ NVL(SPEED,10) ------ ------------PC112 PC132 PC134 PC100 PC126 2 1 1 3 10

The Oracle DUAL table Dual is a table which is created by oracle along with the data dictionary. It consists of exactly one column whose name is dummy and one record. The value of that record is X. sql> desc dual Name Null? Type ----------------------- ------- ---------------102

DUMMY VARCHAR2(1) sql> select * from dual; D X The owner of dual is SYS but dual can be accessed by every user. As dual contains exactly one row (unless someone fiddled with it), it is guaranteed to return exactly one row in select statements. Therefor, dual is the prefered table to select a pseudo column (such as sysdate select sysdate from dual Although it is possible to delete the one record, or insert additional records, one really should not do that!.

103

Built In Functions Single row functions Group Functions Single row functions i) Date Functions ii) Numeric Functions iii) Character Functions iv) Conversion Functions v) Miscellaneous Functions DATE FUNCTIONS Add_months() SQL> ADD_MONTHS(SYSDATE,3) DUAL; ADD_MONTH --------18-NOV-08 SELECT FROM

104

Last_day() SQL> SELECT SYSDATE, LAST_DAY(SYSDATE) FROM DUAL; SYSDATE LAST_DAY( --------- --------18-AUG-08 31-AUG-08 Months_between() SQL> SELECT MONTHS_BETWEEN(TO_DATE('1-1-08', 'DD-MM-YYYY'), TO_DATE('1-7-08','DDMM-YYYY')) FROM DUAL; MONTHS_BETWEEN(TO_DATE('1-108','DD-MM-YYYY'),TO_DATE('1-7-08','DDMM-YYYY')) ----------------------------------------------------------------------------6

105

Next_day() SQL> SELECT NEXT_DAY(SYSDATE,'MONDAY') FROM DUAL; NEXT_DAY( --------25-AUG-08 To display first day of month SELECT TO_CHAR(TRUNC(SYSDATE, 'MM'), 'DD-MON-YYYY HH:MI:SS')FROM dual;

To display first day of year SELECT TO_CHAR(TRUNC(SYSDATE, 'yyyy'), 'DD-MON-YYYY HH:MI:SS')FROM dual;

106

LENGTH() Returns number of characters. SQL> select length(name) from worker;

LENGTH(NAME) -----------10 13 13 14 16 12

LOWER() Returns the column in lower case.


107

SQL> select lower(name) from worker;

LOWER(NAME) -----------------------------dick jones william swing bart sarjeant suma ranganath richard williams bharat kumar john pearson jackson meena kumari adah Talbot

108

UPPER() Returns the column in upper case. SQL> select upper(model_no) from pc;

UPPER(MODE ---------PC124 PC112 LPAD() LPAD(char1, n, [char2] ) Here n is the total number of characters after padding. Returns char1, left padded to length n with the sequence of characters in char2. SQL> select lpad(name, 25, '*') from worker;
109

LPAD(NAME,25,'*') ------------------------***************DICK JONES ************WILLIAM SWING ************BART SARJEANT ***********SUMA RANGANATH *********RICHARD WILLIAMS *************BHARAT KUMAR *************JOHN PEARSON ******************JACKSON *************MEENA KUMARI **************ADAH TALBOT

SQL> select lpad(name,20) from worker;

110

LPAD(NAME,20) -------------------DICK JONES WILLIAM SWING BART SARJEANT SUMA RANGANATH RICHARD WILLIAMS BHARAT KUMAR JOHN PEARSON

RPAD() RPAD(char1, n, [char2] ) Here n is the total number of characters after padding.

111

Returns char1, right padded to length n with the sequence of characters in char2. SQL> select rpad(name,20,'*') from workerskill;

RPAD(NAME,20,'*') -------------------DICK JONES********** JOHN PEARSON******** HELEN BRANDT******** JOHN PEARSON******** JOHN PEARSON******** VICTORIA LYNN******* LTRIM() LTRIM(char, [set] )

112

Removes characters from the left to char, with initial characters removed up to the first character not in set. SQL> select from dual; LTRIM( -----zzxyxy ltrim('xxxxyyyyxyzzxyxy','xy')

RTRIM() RTRIM(char, [set] ) Removes characters from the right to char, with final characters removed after the last character not in set. SQL> select rtrim('sastrasastrararara', 'ra') from dual;
113

RTRIM('SAS ---------sastrasast

SQL> select rtrim('sastrasastraaarrrraa','ra')from dual;

RTRIM('SAS ---------sastrasast

INSTR() INSTR(char1, char2, n)

114

Returns the location of char2 in char1 starting from n th position. SQL> select instr('xyzxyzxyz','z',4) from dual;

INSTR('XYZXYZXYZ','Z',4) -----------------------6 INITCAP() Returns the character with starting letter in uppercase. SQL> select initcap('sastra') from dual;

INITCA -----Sastra SUBSTR()

115

SUBSTR(char, n,m ) Returns m number of characters from char starting from n th position. SQL> select substr('sastra university', 5,2) from dual;

SU -ra

SOUNDEX() SOUNDEX(x) is used to get a string containing the phonetic representation of x. This lets you compare words that sound alike in English but are spelled differently. The following query retrieves the last_name column from the customers table where last_name sounds like whyte: (Pronouncing in same way but spelling different )
116

SELECT last_name FROM customers WHERE SOUNDEX(last_name) = SOUNDEX('whyte'); LAST_NAME ---------White The next query gets last names that sound like bloo: SELECT last_name FROM customers WHERE SOUNDEX(last_name) = SOUNDEX('bloo'); LAST_NAME ---------Blue Returns the value with sound alike but spelled differently.

117

SQL> SELECT CITY FROM WORKERSKILL WHERE SOUNDEX(CITY) = SOUNDEX('SIDNEY');

CITY ----------------SYDNEY

GROUP FUNCTIONS ** Numeric Functions MAX() Max (column_name) : Returns the maximum value of the column SQL> select max(price) from pc; MAX(PRICE) ---------118

50000 MIN() Min(column_name) : Returns the minimum value of the column. SQL> SELECT WORKER; MIN(AGE) ---------21 AVG() AVG(column_name) : Returns the average value of the column. SQL> SELECT AVG(CD) FROM PC; AVG(CD) ---------40 MIN(AGE) FROM

119

STDDEV() Returns the standard deviation of the column; SQL> select stddev(ram) from pc; STDDEV(RAM) ----------73.9008345 VARIANCE() Returns the variance value of the column. SQL> select variance(ram) from pc;

VARIANCE(RAM) ------------5461.33333

120

TRANSLATE () The syntax for the translate function is: translate( string1, string_to_replace, replacement_string ) string1 is the string to replace a sequence of characters with another set of characters. string_to_replace is the string that will be searched for in string1. replacement_string - All characters in the string_to_replace will be replaced with the corresponding character in the replacement_string. Eg: translate('1tech23', '123','456); would return '4tech56' would return '333tith'

translate('222tech, '2ec', '3it');

121

DECODE () The syntax for the decode function is: decode( expression , search , result [, search , result]... [, default] ) expression is the value to compare. search is the value that is compared against expression. result is the value returned, if expression is equal to search. default is optional. If no matches are found, the decode will return default. If default is omitted, then the decode statement will return null (if no matches are found). decode (expression, search_1, result_1) decode (expression, search_1, result_1, search_2, result_2)

122

decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n) decode (expression, search_1, result_1, default) decode (expression, search_1, result_1, search_2, result_2, default) decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n, default) Eg: select * from a where b = decode (x,1,2,2,4); REPLACE() REPLACE (string_expression,string_patter n,string_replacement) Arguments
123

string_expression Is the string expression to be searched. string_expression can be of a character or binary data type. string_pattern Is the substring to be found. string_pattern can be of a character or binary data type. string_pattern cannot be an empty string (''). string_replacement Is the replacement string. string_replacement can be of a character or binary data type. Return Types Returns nvarchar if one of the input arguments is of the nvarchar data type; otherwise, REPLACE returns varchar. Returns NULL if any one of the arguments is NULL.

124

Eg: Select replace(dick jones,ick,ean) from worker;

The ROUND() Function The ROUND() function is used to round a numeric field to the number of decimals specified. SQL ROUND() Syntax SELECT ROUND(column_name,decimals) FROM table_name The field to round. decimals Required. Specifies the number of decimals to be returned. SELECT ROUND(44.647, 2) AS POSIT IVE FROM Dual; POSITIVE ---------44.65

125

Specifying negative precision will round numbers on the left side of the decimal point, as shown here: SELECT ROUND(109.09 ,1) rounded from dual; ROUNDED ---------110 VIEW A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. Creating a VIEW The syntax for creating a VIEW is: CREATE VIEW view_name AS SELECT columns
126

FROM table WHERE predicates;

For example: CREATE VIEW sup_orders AS SELECT suppliers.supplier_id, orders.quantity, orders.price FROM suppliers, orders WHERE suppliers.supplier_id = orders.supplier_id and suppliers.supplier_name = 'IBM'; This would create a virtual table based on the result set of the select statement. You can now query the view as follows: SELECT * FROM sup_orders;

Updating a VIEW You can update a VIEW without dropping it by using the following syntax:

127

CREATE OR REPLACE VIEW view_name AS SELECT columns FROM table WHERE predicates;

For example: CREATE or REPLACE VIEW sup_orders AS SELECT suppliers.supplier_id, orders.quantity, orders.price FROM suppliers, orders WHERE suppliers.supplier_id = orders.supplier_id and suppliers.supplier_name = 'Microsoft'; Dropping a VIEW The syntax for dropping a VIEW is: DROP VIEW view_name; For example: DROP VIEW sup_orders;
128

129

DML Statements on a Join View A join view is a view based on a join. Special considerations apply when you issue a DML (INSERT, UPDATE, or DELETE) statement against a join view. Ever thought about what happens when you insert a row into a join viewwhich table does the row go into? And what happens when you delete a row from a join viewwhich table does it gets deleted from? This section deals with these questions. To be modifiable, a join view must not contain any of the following:

Hierarchical query clauses, such as START WITH or CONNECT BY GROUP BY or HAVING clauses Set operations, such as UNION, UNION ALL, INTERSECT, MINUS Aggregate functions, such as AVG, COUNT, MAX, MIN, SUM, and so forth The DISTINCT operator The ROWNUM pseudocolumn

A DML statement on a join view can modify only one base table of the view. Apart from
130

these rules, therefore, a join view must also have one key preserved table to be modified. 3.5.1 Key-Preserved Tables A key-preserved table is the most important requirement in order for a join view to be modifiable. In a join, a table is called a keypreserved table if its keys are preserved through the joinevery key of the table can also be a key of the resultant join result set. Every primary key or unique key value in the base table must also be unique in the result set of the join. Let's take an example to understand the concept of key preserved tables better. DESC EMPLOYEE Name Null? Type

-------------------------------------- ---EMP_ID NOT NULL NUMBER(4)


131

LNAME VARCHAR2(15) FNAME VARCHAR2(15) DEPT_ID NUMBER(2) MANAGER_EMP_ID NUMBER(4) SALARY NUMBER(7,2) HIRE_DATE DATE JOB_ID NUMBER(3)

DESC RETAILER Name


132

Null?

Type

-------------------------------------- ---RTLR_NBR NOT NULL NUMBER(6) NAME VARCHAR2(45) ADDRESS VARCHAR2(40) CITY VARCHAR2(30) STATE VARCHAR2(2) ZIP_CODE VARCHAR2(9) AREA_CODE NUMBER(3)
133

PHONE_NUMBER NUMBER(7) SALESPERSON_ID NUMBER(4) CREDIT_LIMIT NUMBER(9,2) COMMENTS LONG

CREATE VIEW V_RTLR_EMP AS SELECT C.RTLR_NBR, C.NAME, C.CITY, E.EMP_ID, E.LNAME SALES_REP FROM RETAILER C, EMPLOYEE E WHERE C.SALESPERSON_ID = E.EMP_ID;

134

View created.

SELECT * FROM V_RTLR_EMP;

RTLR_NBR NAME CITY EMP_

SALES_REP

----------- --------------------------- ----------------------------100 JOCKSPORTS BELMONT 7844 TURNER 101 TKB SPORT SHOP REDWOOD CITY 7521 WARD 102 VOLLYRITE BURLINGAME 7654 MARTIN 103 JUST TENNIS
135

BURLINGAME

7521 WARD

104 EVERY MOUNTAIN CUPERTINO 7499 ALLEN 105 K + T SPORTS SANTA CLARA 7844 TURNER 106 SHAPE UP PALO ALTO 7521 WARD 107 WOMENS SPORTS SUNNYVALE 7499 ALLEN 201 STADIUM SPORTS NEW YORK 7557 SHAW 202 HOOPS LEICESTER 7820 ROSS 203 REBOUND SPORTS NEW YORK 7557 SHAW DALLAS 204 THE POWER FORWARD 7560 DUNCAN
136

205 POINT GUARD YONKERS 7557 SHAW 206 THE COLISEUM SCARSDALE 7557 SHAW 207 FAST BREAK CONCORD 7820 ROSS AUSTIN 208 AL AND BOB'S SPORTS 7560 DUNCAN

211 AT BAT BROOKLINE 7820 ROSS 212 ALL SPORT BROOKLYN 7600 PORTER 213 GOOD SPORT SUNNYSIDE 7600 PORTER SPRING 214 AL'S PRO SHOP 7564 LANGE

215 BOB'S FAMILY SPORTS HOUSTON 7654 MARTIN


137

216 THE ALL AMERICAN CHELSEA 7820 ROSS 217 HIT, THROW, AND RUN GRAPEVINE 7564 LANGE 218 THE OUTFIELD FLUSHING 7820 ROSS 221 WHEELS AND DEALS HOUSTON 7789 WEST DALLAS MALDEN 222 JUST BIKES 7789 WEST 223 VELO SPORTS 7820 ROSS

224 JOE'S BIKE SHOP GRAND PRARIE 7789 WEST 225 BOB'S SWIM, CYCLE, AND RUN IRVING 7789 WEST
138

226 CENTURY SHOP HUNTINGTON 7555 PETERS 227 THE TOUR SOMERVILLE 7820 ROSS 228 FITNESS FIRST JACKSON HEIGHTS 7555 PETERS

32 rows selected. The view V_RTLR_EMP is a join of RETAILER and EMPLOYEE tables on the RETAILER.SALESPERSON_ID and EMPLOYEE.EMP_ID columns. Is there a keypreserved table in this join view? Which one or is it both? If you observe the relationship between the two tables and the join query, you will notice that RTLR_NBR is the key of the RETAILER table, as well as the key of the result of the join. This is because there is only one row in the RETAILER table for every row in the join view V_RTLR_EMP and every row in the view has a unique RTLR_NBR. Therefore, the table
139

RETAILER is a key-preserved table in this join view. How about the EMPLOYEE table? The key of the EMPLOYEE table is not preserved through the join because EMP_ID is not unique in the view, consequently EMP_ID can't be a key for the result of the join. Therefore, the table EMPLOYEE is not a key-preserved table in this view. You must remember the following important points regarding key-preserved tables:

Key-preservation is a property of the table inside the join view, not the table itself independently. A table may be keypreserved in one join view, and may not be key-preserved in another join view. For example, if we create a join view by joining the EMPLOYEE table with the DEPARTMENT table on the DEPT_ID column, then in the resulting view the EMPLOYEE table will be key-preserved, but the DEPARTMENT table will not be a key-preserved table. It is not necessary for the key column(s) of a table to be SELECTed in the join view for
140

the table to be key-preserved. For example, in the V_RTLR_EMP view discussed previously, the RETAILER table would have been the key-preserved table even if we had not included the RTLR_NBR column in the SELECT list. On the other hand, if we select the key column(s) of a table in the view definition, it doesn't make that table key-preserved. In the V_RTLR_EMP view, even though we have included EMP_ID in the SELECT list, the EMPLOYEE table is not key-preserved. The key-preserved property of a table in a join view doesn't depend on the data inside the table. It depends on the schema design and the relationship between the tables.

The following sections discuss how you can use INSERT, UPDATE, and DELETE statements on a join view. 3.5.2 INSERT Statements on a Join View Let's issue an INSERT statement against the join view V_RTLR_EMP that attempts to insert a record into the RETAILER table:
141

INSERT INTO V_RTLR_EMP (RTLR_NBR, NAME, SALESPERSON_ID) VALUES (345, 'X-MART STORES', 7820);

1 row created. That worked. Now let's try this INSERT statement, which also supplies a value for a column from the EMPLOYEE table: INSERT INTO V_RTLR_EMP (RTLR_NBR, NAME, SALESPERSON_ID, SALES_REP) VALUES (456, 'LEE PARK RECREATION CENTER', 7599, 'JAMES'); INSERT INTO V_RTLR_EMP (RTLR_NBR, NAME, SALESPERSON_ID, SALES_REP)

142

* ERROR at line 1: ORA-01776: cannot modify more than one base table through a join view This INSERT statement attempts to insert values into two tables (RETAILER and EMPLOYEE), which is not allowed. You can't refer to the columns of a non-key-preserved table in an INSERT statement. Moreover, INSERT statements are not allowed on a join view if the view is created using the WITH CHECK OPTION clause, even if you are attempting to insert into the key-preserved table only. For example: CREATE VIEW V_RTLR_EMP_WCO AS SELECT C.RTLR_NBR, C.NAME, C.CITY, C.SALESPERSON_ID, E.LNAME SALES_REP

143

FROM RETAILER C, EMPLOYEE E WHERE C.SALESPERSON_ID = E.EMP_ID WITH CHECK OPTION;

View created.

INSERT INTO V_RTLR_EMP_WCO (RTLR_NBR, NAME, SALESPERSON_ID) VALUES (345, 'X-MART STORES', 7820); INSERT INTO V_RTLR_EMP_WCO (RTLR_NBR, NAME, SALESPERSON_ID) * ERROR at line 1:
144

ORA-01733: virtual column not allowed here The error message "ORA-01733: virtual column not allowed here" may not be very clear, but it indicates that you are not allowed to insert into this join view. 3.5.3 DELETE Statements on a Join View DELETE operations can be performed on a join view if the join view has one and only one keypreserved table. The view V_RTLR_EMP discussed previously has only one key-preserved table, RETAILER; therefore, you can delete from this join view as in the following example: DELETE FROM V_RTLR_EMP WHERE RTLR_NBR = 214;

1 row deleted. Let's take another example where there is more than one key-preserved table. We will create a
145

view from the self join example we discussed earlier in this chapter and attempt to delete from the view. CREATE VIEW V_DEPT_TEAM AS SELECT D1.NAME TEAM1, D2.NAME TEAM2 FROM DEPARTMENT D1, DEPARTMENT D2 WHERE D1.DEPT_ID > D2.DEPT_ID;

View created.

DELETE FROM V_DEPT_TEAM WHERE TEAM1 = 'SALES'; DELETE FROM V_DEPT_TEAM

146

* ERROR at line 1: ORA-01752: cannot delete from view without exactly one keypreserved table 3.5.4 UPDATE Statements on a Join View An UPDATE operation can be performed on a join view if it attempts to update a column in the key-preserved table. For example: UPDATE V_RTLR_EMP SET NAME = 'PRO SPORTS' WHERE RTLR_NBR = 214;

1 row updated. This UPDATE is successful since it updated the NAME column of the RETAILER table, which is key-preserved. However, the following UPDATE statement will fail because it attempts
147

to modify the SALES_REP column that maps to the EMPLOYEE table, which is non-keypreserved: UPDATE V_RTLR_EMP SET SALES_REP = 'ANDREW' WHERE RTLR_NBR = 214; SET SALES_REP = 'ANDREW' * ERROR at line 2: ORA-01779: cannot modify a column which maps to a non keypreserved table The WITH CHECK OPTION further restricts the ability to modify a join view. If a join view is created using the WITH CHECK OPTION clause, you can't modify any of the join columns, nor any of the columns from the repeated tables:
148

UPDATE V_RTLR_EMP_WCO SET SALESPERSON_ID = 7784 WHERE RTLR_NBR = 214; SET SALESPERSON_ID = 7784 * ERROR at line 2: ORA-01733: virtual column not allowed here The error message "ORA-01733: virtual column not allowed here" indicates that you are not allowed to update the indicated column. 3.5.5 Data Dictionary Views to Find Updateable Columns Oracle provides the data dictionary view USER_UPDATABLE_COLUMNS that shows all modifiable columns in all tables and views in a user's schema. This can be helpful if you have a view that you wish to update, but aren't sure
149

whether it's updateable. USER_UPDATABLE_COLUMNS has the following definition: DESC USER_UPDATABLE_COLUMNS Name Null? Type

-------------- -------- -----------OWNER VARCHAR2(30) TABLE_NAME VARCHAR2(30) COLUMN_NAME VARCHAR2(30) UPDATABLE VARCHAR2(3) INSERTABLE VARCHAR2(3) NOT NULL NOT NULL NOT NULL

150

DELETABLE VARCHAR2(3) ALL_UPDATABLE_COLUMNS shows all views you can access (as opposed to just those you own), and DBA_UPDATABLE_COLUMNS (for DBAs only) shows all views in the database. The following example shows the view being queried for a list of updateable columns in the V_RTLR_EMP_WCO view: SELECT * FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME = 'V_RTLR_EMP_WCO';

OWNER TABLE_NAME COLUMN_NAME UPD INS DEL ------- ---------------- --------------- --- --- --151

DEMO V_RTLR_EMP_WCO RTLR_NBR YES YES YES DEMO V_RTLR_EMP_WCO YES YES YES DEMO V_RTLR_EMP_WCO YES YES YES DEMO V_RTLR_EMP_WCO SALESPERSON_ID NO NO DEMO V_RTLR_EMP_WCO SALES_REP NO NO NAME CITY

NO NO

Compare the updateable columns of the view V_RTLR_EMP_WCO with those of the view V_RTLR_EMP: SELECT * FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME = 'V_RTLR_EMP';

152

OWNER TABLE_NAME COLUMN_NAME UPD INS DEL ------- ------------- --------------- --- --DEMO V_RTLR_EMP YES YES YES DEMO V_RTLR_EMP YES YES YES DEMO V_RTLR_EMP YES YES YES RTLR_NBR NAME CITY

DEMO V_RTLR_EMP SALESPERSON_ID YES YES YES DEMO NO NO V_RTLR_EMP NO SALES_REP

Notice that the column SALESPERSON_ID is modifiable in V_RTLR_EMP, but not in V_RTLR_EMP_WCO.

153

INDEXES Use indexes to speed up queries. Indexes speeds up searching of information in tables. So create indexes on those columns which are oftenly used in WHERE conditions. Indexes are helpful if the operations return only small portion of data i.e. less than 15% of data is retrieved from tables. Follow these guidelines for creating indexes

Do not create indexes on small tables i.e. where number of rows are less. Do not create indexes on those columns which contain many null values.
154

Do not create BTree index on those columns which contain many repeated values in this case create BITMAP indexes on these columns. Limit the number of indexes on tables because, although they speed up queries, but at the same time DML operations becomes very slow as all the indexes have to updated whenever an Update, Delete or Insert takes place on tables.

Creating Indexes To create an Index give the create index command. For example the following statement creates an index on empno column of emp table. create index empno_ind on emp (empno); If two columns are oftenly used together in WHERE conditions then create a composite index on these columns. For example, suppose we use EMPNO and DEPTNO oftenly together
155

in WHERE condition. Then create a composite index on these column as given below create index empdept_ind on emp (empno,deptno);

BITMAP INDEX Create Bitmap indexes on those columns which contains many repeated values and when tables are large. City column in EMP table is a good canditate for Bitmap index because it contain many repeated values. To create a composite index give the following command. create bitmap index city_ind on emp (city); UNIQUE INDEX Indexes can be unique or non-unique. Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). Non-unique indexes do not impose this restriction on the column values.
156

Use the CREATE UNIQUE INDEX statement to create a unique index. The following example creates a unique index: CREATE UNIQUE dept_unique_index (dname) FUNCTION BASED INDEX Function-based indexes facilitate queries that qualify a value returned by a function or expression. The value of the function or expression is precomputed and stored in the index. In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes. The syntax for creating a function-based index is: CREATE [UNIQUE] INDEX index_name ON table_name (function1, function2, . function_n) [ COMPUTE STATISTICS ];
157

ON

INDEX dept

For example: CREATE INDEX supplier_idx ON supplier (UPPER(supplier_name)); In this example, we've created an index based on the uppercase evaluation of the supplier_name field. However, to be sure that the Oracle optimizer uses this index when executing your SQL statements, be sure that UPPER(supplier_name) does not evaluate to a NULL value. To ensure this, add UPPER(supplier_name) IS NOT NULL to your WHERE clause as follows: SELECT supplier_id, supplier_name, UPPER(supplier_name) FROM supplier WHERE UPPER(supplier_name) IS NOT NULL ORDER BY UPPER(supplier_name);
158

To illustrate a function-based index, consider the following statement that defines a functionbased index (area_index) defined on the function area(geo): CREATE INDEX area_index ON rivers (area(geo)); In the following SQL statement, when area(geo) is referenced in the WHERE clause, the optimizer considers using the index area_index. SELECT id, geo, area(geo), desc FROM rivers WHERE Area(geo) >5000; Table owners should have EXECUTE privileges on the functions used in function-based indexes. Because a function-based index depends upon any function it is using, it can be invalidated when a function changes. If the function is valid, you can use an ALTER INDEX...ENABLE
159

statement to enable a function-based index that has been disabled. The ALTER INDEX...DISABLE statement lets you disable the use of a function-based index. Consider doing this if you are working on the body of the function. Rename an Index The syntax for renaming an index is: ALTER INDEX index_name RENAME TO new_index_name;

For example: ALTER INDEX supplier_idx RENAME TO supplier_index_name; In this example, we're renaming the index called supplier_idx to supplier_index_name. Drop an Index The syntax for dropping an index is: DROP INDEX index_name;
160

For example: DROP INDEX supplier_idx; In this example, we're dropping an index called supplier_idx. SYNONYM A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects. Creating or replacing a synonym The syntax for creating a synonym is: create [or replace] [public] synonym [schema .] synonym_name for [schema .] object_name [@ dblink]; The or replace phrase allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command. The public phrase means that the synonym is a public synonym and is accessible to all users.
161

Remember though that the user must first have the appropriate privileges to the object to use the synonym. The schema phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema. The object_name phrase is the name of the object for which you are creating the synonym. It can be one of the following: table package materialized view view java class sequence schema object stored user-defined procedure object function synonym For example: create public synonym suppliers for app.suppliers;
162

This first example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. For example: select * from suppliers; If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows: create or replace public synonym suppliers for app.suppliers; Dropping a synonym It is also possible to drop a synonym. The syntax for dropping a synonym is: drop [public] synonym [schema .] synonym_name [force]; The public phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema.

163

The force phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.

For example: drop public synonym suppliers; This drop statement would drop the synonym called suppliers that we defined earlier. SEQUENCE A sequence is a database item that generates a sequence of integers. You typically use the integers generated by a sequence to populate a numeric primary key column. You create a sequence using the CREATE SEQUENCE statement, which has the following syntax: CREATE SEQUENCE sequence_name [START WITH start_num]
164

[INCREMENT BY increment_num] [ { MAXVALUE maximum_num | NOMAXVALUE } [ { MINVALUE minimum_num | NOMINVALUE } [ { CYCLE | NOCYCLE } ] [ { CACHE cache_num | NOCACHE } ] [ { ORDER | NOORDER } ]; where 1. The default start_num is 1. 2. The default increment number is 1. 3. The absolute value of increment_num must be less than the difference between maximum_num and minimum_num. 4. minimum_num must be less than or equal to start_num, and minimum_num must be less than maximum_num. 5. NOMINVALUE specifies the maximum is 1 for an ascending sequence or -10^26 for a descending sequence. 6. NOMINVALUE is the default. 7. maximum_num must be greater than or equal to start_num, and maximum_num must be greater than minimum_num.

165

8. NOMAXVALUE specifies the maximum is 10^27 for an ascending sequence or C1 for a descending sequence. 9. NOMAXVALUE is the default. 10. CYCLE specifies the sequence generates integers even after reaching its maximum or minimum value. 11. When an ascending sequence reaches its maximum value, the next value generated is the minimum. 12. When a descending sequence reaches its minimum value, the next value generated is the maximum. 13. NOCYCLE specifies the sequence cannot generate any more integers after reaching its maximum or minimum value. 14. NOCYCLE is the default. 15. CACHE cache_num specifies the number of integers to keep in memory. 16. The default number of integers to cache is 20. 17. The minimum number of integers that may be cached is 2. 18. The maximum integers that may be cached is determined by the formula
166

CEIL(maximum_num minimum_num)/ABS(increment_num). 19. NOCACHE specifies no integers are to be stored. 20. ORDER guarantees the integers are generated in the order of the request. 21. You typically use ORDER when using Real Application Clusters. 22. NOORDER doesn't guarantee the integers are generated in the order of the request. 23. NOORDER is the default. CREATE SEQUENCE test_seq; create sequence LOGICAL_ASSIGNME NT_ID_SEQ start with 1;

SQL> CREATE SEQUENCE test_seq; Sequence created.


167

SQL> SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------1 SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------2 SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------3

168

SQL> 2 5 3 4

CREATE SEQUENCE test_seq START WITH 10 INCREMENT BY MINVALUE 10 MAXVALUE 20 CYCLE CACHE 2 ORDER;

Sequence created. SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL ---------10 SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL ---------15

169

SQL> CREATE SEQUENCE test_seq; SELECT test_seq.nextval FROM dua l; NEXTVAL ---------1 SQL> SELECT test_seq.currval FRO M dual; CURRVAL ---------1 SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL ---------2
170

SQL> SQL> ALTER SEQUENCE test_seq 2 INCREMENT BY 2; Sequence altered. SQL> SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL ---------4 SQL> SELECT test_seq.currval FRO M dual; CURRVAL ---------4 SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL
171

---------6

SQL> CREATE TABLE test ( 2 record_id NUMBER(18, 0), 3 record_text VARCHAR2(1 0) 4 ); Table created. SQL> SQL> CREATE SEQUENCE test_seq; Sequence created. SQL> SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------172

1 SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------2 SQL> SELECT test_seq.nextval FRO M DUAL; NEXTVAL ---------3 SQL> SQL> SQL> INSERT INTO test VALUES ( 2 test_seq.nextval, 3 'Record A' 4 ); 1 row created. SQL>
173

SQL> INSERT INTO test VALUES ( 2 test_seq.nextval, 3 'Record B' 4 ); 1 row created. SQL> SQL> SELECT * FROM test; RECORD_ID ---------4 5 RECORD_TEX ---------Record A Record B

SQL> create sequence deptno_seq start with 50 increment by 10; Sequence created. SQL> SQL> select deptno_seq.nextval, deptno_seq.currval
174

from

dual;

NEXTVAL CURRVAL ---------- ---------50 50

PRIMARY KEY USING SEQUENCE SQL> CREATE TABLE myTable ( 2 id INTEGER CONSTRAINT pk PRIMARY KEY, 3 status VARCHAR2(10) 4 ); Table created. SQL> CREATE SEQUENCE my_seq NOCA CHE; Sequence created. SQL> SQL> INSERT INTO myTable (id, st
175

atus) VALUES (my_seq.nextval, 'P LACED'); 1 row created. SQL> INSERT INTO myTable (id, st atus) VALUES (my_seq.nextval, 'P ENDING'); 1 row created. SQL> SQL> select * from myTable; ID ---------1 2 STATUS ---------PLACED PENDING

MODIFYING A SEQUENCE

1. You modify a sequence using the ALTER SEQUENCE statement.


176

2. You cannot change the start value of a sequence. 3. The minimum value cannot be more than the current value of the sequence ( currval ). 4. The maximum value cannot be less than the current value of the sequence ( currval ). SQL> ALTER SEQUENCE test_seq MA XVALUE 10; Sequence altered.

GETTING SEQUENCE INFORMATION SQL> desc user_sequences; Name Null? -----------------SEQUENCE_NAME NOT NULL MIN_VALUE MAX_VALUE INCREMENT_BY NOT NULL CYCLE_FLAG ORDER_FLAG
177

Type

VARCHAR2(30) NUMBER NUMBER NUMBER VARCHAR2(1) VARCHAR2(1)

CACHE_SIZE LAST_NUMBER

NOT NULL NUMBER NOT NULL NUMBER

last_number:Last number that was generated or cached by the sequence. SQL> SQL> SQL> 2 3 4

CREATE SEQUENCE test_seq START WITH 10 INCREMENT BY -1 MINVALUE 1 MAXVALUE 10 CYCLE CACHE 5;

Sequence created. SQL> SQL> SQL> select * from user_sequences where

SEQUENCE_NAME MIN_VALUE MAX_VALUE ----------------- ---------- ---------TEST_SEQ 1 10

178

When you select currval , nextval remains unchanged; nextval only changes when you select nextval to get the next value. SQL> CREATE SEQUENCE test_seq; Sequence created. SQL> SQL> SELECT test_seq.nextval FRO M dual; NEXTVAL ---------1 SQL> SQL> SELECT test_seq.nextval, te st_seq.currval FROM dual; NEXTVAL CURRVAL ---------- ---------2 2
179

SQL> SQL> SELECT test_seq.nextval, te st_seq.currval FROM dual; NEXTVAL CURRVAL ---------- ---------3 3

QUERY CURRENT VALUE SQL> create sequence deptno_seq start with 50 increment by 10; Sequence created. SQL> SQL> select deptno_seq.currval 2 from dual; select deptno_seq.currval *
180

ERROR at line 1: ORA08002: sequence DEPTNO_SEQ.CURRV AL is not yet defined in this se ssion

DROPPING A SEQUENCE SQL> drop sequence my_seq;

181