Sei sulla pagina 1di 59

1.

Data Definition language (DDL) commands


AIM: To create, alter, rename, drop and truncate the table. DDL COMMANDS: CREATE ALTER RENAME DROP TRUNCATE

TO CREATE A TABLE WITH FIELD NAMES: SYNTAX: Create table tableName(fieldname1 datatype(size),........fieldname n datatype(size)); EXPLANATION: This query will create a table with the attributes specified. TO ALTER THE TABLE: SYNTAX: Alter table tablename modify/add(fieldname new datatype(size)); EXPLANATION: This query will alter the table with the new attributes specified. TO DROP THE TABLE: SYNTAX: Drop table tableName[WHERE conditions]; EXPLANATION: This query will drop the table along with the schema of the table. RENAME THE TABLE SYNTAX Rename <old table name> to <new table name> EXPLANATION: This query will change the name of the table. TRUNCATE SYNTAX TRUNC <tablename>; EXPLANATIONS: All the values in the table will be deleted without checking any conditions. Generally faster than delete since delete will delete the values row by row, and deleting particular tuples is not possible

www.sace-cse.com

Page 1

EXAMPLES: SQL> create table loan(loan_number varchar2(10),branch_name varchar2(10),amount number(10)); Table created. SQL> create table loan(loan_number varchar2(10) primary key,branch_name varchar2(10),amount number(10)); Table created. SQL> create table loan(loan_number varchar2(10) constraint lkey primary key,branch_name varchar2(10),amount number(10)); Table created. SQL> desc loan; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10) AMOUNT NUMBER(10) SQL> alter table loan add city varchar2(10); Table altered. SQL> desc loan; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10) AMOUNT NUMBER(10) CITY VARCHAR2(10) SQL> alter table loan modify(city varchar2(30)); Table altered. SQL> desc loan; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10) AMOUNT NUMBER(10) CITY VARCHAR2(30) SQL> alter table loan drop column city; Table altered. SQL> desc loan; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10)

www.sace-cse.com

Page 2

AMOUNT

NUMBER(10)

SQL> alter table loan disable primary key; Table altered. SQL> rename loan to loan1; Table renamed. SQL> desc loan1; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10) AMOUNT NUMBER(10) SQL> rename loan1 to loan; Table renamed. SQL> desc loan; Name Null? Type ----------------------------------------- -------- ---------------------------LOAN_NUMBER NOT NULL VARCHAR2(10) BRANCH_NAME VARCHAR2(10) AMOUNT NUMBER(10) SQL> drop table loan; Table dropped.

SQL> truncate table loan; Table truncated

www.sace-cse.com

Page 3

RESULT: Thus the DDL commands were used successfully.

www.sace-cse.com

Page 4

2.DML COMMANDS. AIM: To know and use the data manipulation commands. DML COMMANDS:

SELECT INSERT UPDATE DELETE

SYNTAX: Basic SELECT Statement

SELECT *|{[DISTINCT] column|expression [alias],...} FROM table; SELECT identifies what columns FROM identifies which table EXPLANATION In its simplest form, a SELECT statement must include the following: A SELECT clause, which specifies the columns to be displayed A FROM clause, which specifies the table containing the columns listed in the SELECT clause In the syntax: SELECT * DISTINCT column|expression alias FROM table s is a list of one or more columns selects all columns suppresses duplicates selects the named column or the expression gives selected columns different headings specifies the table containing the columns

SELECT WITH WHERE CLAUSE: Restrict the rows returned by using the WHERE clause. The WHERE clause follows the FROM clause. SYNTAX: www.sace-cse.com Page 5

SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)]; EXPLANATION Rows are restricted which is returned from the query by using the WHERE clause. A WHERE clause contains a condition that must be met, and it directly follows the FROM clause. If the condition is true, the row meeting the condition is returned. In the syntax: WHERE Condition restricts the query to rows that meet a condition is composed of column names, expressions,constants, & comparison operator The WHERE clause can compare values in columns, literal values, arithmetic expressions, or functions. It consists of three elements: Column name Comparison condition Column name, constant, or list of values Other Comparison Conditions Operator BETWEEN Meaning Between two values (inclusive),

...AND... IN(set LIKE Match any of a list of values Match a character pattern

IS NULL INSERT: SYNTAX:

Is a null value

INSERT INTO table [(column [, column...])] VALUES (value [, value...]); EXPLANATION In the syntax: www.sace-cse.com Page 6

Table column value UPDATE: SYNTAX: UPDATE table

is the name of the table is the name of the column in the table to populate is the corresponding value for the column

SET column = value [, column = value, ...] [WHERE condition]; EXPLANATION Modify existing rows with the UPDATE statement. Update more than one row at a time, if required. Specific row or rows are modified if you specify the WHERE clause. In the syntax: table column value condition is the name of the table is the name of the column in the table to populate is the corresponding value or subquery for the column identifies the rows to be updated and is composed of column names expressions, constants, subqueries, and comparison operators. DELETE: SYNTAX: DELETE FROM table [WHERE condition(s)]; EXPLANATION Delete command deletes the tuple values from a particular table, only limited tuples can be deleted by using the WHERE clause. In the syntax: WHERE Condition restricts the query to rows that meet a condition is composed of column names, expressions,constants, & comparison operator The WHERE clause can compare values in columns, literal values, arithmetic expressions, or functions. www.sace-cse.com Page 7

1. SELECT ALL ATTRIBUTES FROM A RELATION. SQL> SELECT * FROM ACCOUNT; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-101 500 downtown A-215 1200 Mianus A-102 396 perryridge A-305 346.5 roundhill A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton 7 rows selected. 2.SELECTING A PARTICULAR ATTRIBUTE FROM THE TABLE. SQL> SELECT ACCOUNTNUMBER FROM ACCOUNT; ACCOUNTNUMBER -------------------A-101 A-215 A-102 A-305 A-201 A-222 A-217 7 rows selected. 3. SELECTING AN ATTRIBUTE FROM TWO TABLES. SQL->SELECT ACCOUNTNUMBER FROM ACCOUNT,DEPOSITER; ACCOUNTNUMBER -------------------A-101 A-215 A-102 A-305 A-201 A-222 www.sace-cse.com Page 8

A-217 4. SELECTING AN EXPRESSION FROM A TABLE. SQL> SELECT BALANCE*0.5 FROM ACCOUNT; BALANCE*0.5 ----------250 600

198 173.25 600 600 600 7 rows selected. 5. SELECTING ATTRIBUTES USING WHERE CONDITIONS ARE =,<,>,<=,>=,AND,OR,IN,NOT IN,BETWEEN,LIKE,NOT LIKE. A) SQL> SELECT * FROM ACCOUNT WHERE BALANCE>1000; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton B) SQL> SELECT * FROM ACCOUNT WHERE BALANCE = 1000; no rows selected C)SQL> SELECT * FROM ACCOUNT WHERE BALANCE <1000; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-101 500 downtown A-102 396 perryridge A-305 346.5 roundhill D)SQL> SELECT * FROM ACCOUNT WHERE BALANCE <=1000; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------www.sace-cse.com Page 9

A-101 A-102 A-305

500 downtown 396 perryridge 346.5 roundhill

E)SQL> SELECT * FROM ACCOUNT WHERE BALANCE >=1000; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton F) SQL> SELECT * FROM ACCOUNT WHERE BALANCE=1200 AND ACCOUNT='A215'; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus G)SQL> SELECT * FROM ACCOUNT WHERE BALANCE=1200 OR ACCOUNT='A222'; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton H) SQL> SELECT * FROM ACCOUNT WHERE BALANCE IN(100,1200); ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton I) SQL> SELECT * FROM ACCOUNT WHERE BALANCE NOT IN(100,1200); ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-101 500 downtown A-102 396 perryridge A-305 346.5 roundhill J) SQL> SELECT * FROM ACCOUNT WHERE BALANCE BETWEEN 1000 AND 5000; www.sace-cse.com Page 10

ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton K) SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE 'b%'; ACCOUNT BALANCE -------------------- ---------A-201 1200 A-217 1200 BRANCHNAME -------------------brighton brighton

L) SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE '%n'; ACCOUNT -------------------A-101 A-201 A-217 BALANCE BRANCHNAME ----------------------------500 downtown 1200 brighton 1200 brighton

M) SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE 'b%n'; ACCOUNT BALANCE BRANCHNAME -------------------- ----------------------------A-201 1200 brighton A-217 1200 brighton N) SQL> select * from account where branchname not like 'b%n'; ACCOUNT -------------------A-101 A-215 A-102 A-305 A-222 BALANCE ---------500 1200 396 346.5 1200 BRANCHNAME -------------------downtown Mianus perryridge roundhill redwood

6. SELECT ALL THE ATTRIBUTES AND ORDER THEM. SELECT * FROM ACCOUNT WHERE BRANCHNAME ORDER BY ASC;

7. INSERTING VALUES INTO THE TABLE. www.sace-cse.com Page 11

SQL> insert into account values('A-107','Redwood',490); 1 row created.

8. INSERTING VALUES INTO A PARTICULAR COLUMN.


SQL> insert into account(account_number,balance) values('A-108',890); 1 row created.

9.UPDATING VALUES IN THE TABLE. SQL> update account set balance=1000 where balance>500; 4 rows updated.

10.TRUNCATE. SQL> truncate table loan; Table truncated. .

11.DELETE THE RELATION.


SQL> delete from account;

12.DELETE USING WHERE CLASS.


SQL> delete from account where balance=175; 1 row deleted;

www.sace-cse.com

Page 12

RESULT: Thus the DML commands are executed.

www.sace-cse.com

Page 13

3.FUNCTIONS AIM: To manipulate the data using SQL functions FUNCTIONS SINGLE ROW AGGREGATE

SQL Functions Functions are a very powerful feature of SQL and can be used to do the following: Perform calculations on data Modify individual data items Manipulate output for groups of rows Format dates and numbers for display Convert column data types SQL functions sometimes take arguments and always return a value. SINGLE ROW FUNCTIONS

www.sace-cse.com

Page 14

SYNTAX function_name [(arg1, arg2,...)] EXPLANATION Single-row functions are used to manipulate data items. They accept one or more arguments and return one value for each row returned by the query. An argument can be one of the following: User-supplied constant Variable value Column name Expression Features of single-row functions include: Acting on each row returned in the query Returning one result per row Possibly returning a data value of a different type than that referenced Possibly expecting one or more arguments Can be used in SELECT, WHERE, and ORDER BY clauses; can be nested In the syntax: function_name arg1, arg2 is the name of the function. is any argument to be used by the function. This can represented by a column name or expression. Character functions___Accept character input and can return both character and number values Number functions__Accept numeric input and return numeric values Date functions__Operate on values of the DATE data type (All date functions return a value of DATE data type except the MONTHS_BETWEEN function, which returns a number.) Conversion functions__Convert a value from one data type to another General functions: NVL NVL2 NULLIF COALSECE CASE DECODE

www.sace-cse.com

Page 15

CHARACTER FUNCTIONS LOWER(column|expression) UPPER(column|expression) INITCAP(column|expression) Converts alpha character values to lowercase Converts alpha character values to uppercase Converts alpha character values to uppercase for the first letter of each word, all other letters in lowercase CONCAT(column1|expression1 column2|expression2) Concatenates the first character value to the second character value; equivalent to concatenation operator (||) SUBSTR(column|expression,m[,n]) Returns specified characters from character value starting at character position m, n characters long (If m is negative, the count starts from the end of the character value. If n is omitted, all characters to the end of the string are returned.)

NUMBER FUNCTIONS Number functions accept numeric input and return numeric values. This section describes some of the number functions. Number Functions ROUND: Rounds value to specified decimal ROUND(45.926, 2) 45.93 TRUNC: Truncates value to specified decimal TRUNC(45.926, 2) 45.92 MOD: Returns remainder of division MOD(1600, 300) 100 Function Purpose ROUND(column|expression, n) Rounds the column, expression, or value to n decimal places, or, if n is omitted, no decimal places. (If n is negative, numbers to left of the decimal point are rounded.) TRUNC(column|expression,n) Truncates the column, expression, or value to n decimal places, or, if n is omitted, then n defaults to zero MOD(m,n) Returns the remainder of m divided by n www.sace-cse.com Page 16

Date Functions MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC EXPLANATION: Date functions operate on Oracle dates. All date functions return a value of DATE data type except MONTHS_BETWEEN, which returns a numeric value. MONTHS_BETWEEN(date1, date2)Finds the number of months between date1 and date2. The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative.The noninteger part of the result represents a portion of the month. ADD_MONTHS(date, n)Adds n number of calendar months to date. The value of n must be an integer and can be negative. NEXT_DAY(date, 'char')Finds the date of the next specified day of the week ('char') following date. The value of char may be a number representing a day or a character string. LAST_DAY(date)Finds the date of the last day of the month that contains date. ROUND(date[,'fmt'])Returns date rounded to the unit specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest day. TRUNC(date[, 'fmt'])Returns date with the time portion of the day truncated to the unit specified by the format model fmt. If the format model fmt is omitted, date is truncated to the nearest day. Explicit Data Type Conversion NUMBER CHARACTER TO_CHAR TO_NUMBER DATE TO_CHAR TO_DATE Number of months between two dates Add calendar months to date Next day of the date specified Last day of the month Round date Truncate date

Function Purpose TO_CHAR(number|date,[ fmt],[nlsparams]) Date Conversion: The nlsparams parameter specifies the language in which month and day names www.sace-cse.com Page 17

and abbreviations are returned. If this parameter is omitted, this function uses the default date languages for the session. TO_NUMBER(char,[fmt], [nlsparams]) Converts a character string containing digits to a number in the format specified by the optional format model fmt. The nlsparams parameter has the same purpose in this function as in the TO_CHAR function for number conversion. TO_DATE(char,[fmt],[nlsparams]) Converts a character string representing a date to a date value according to the fmt specified. If fmt is omitted, the format is DD-MON-YY. The nlsparams parameter has the same purpose in this function as in the TO_CHAR function for date conversion. LENGTH(column|expression) Returns the number of characters in the expression INSTR(column|expression,string, [,m], [n] ) Returns the numeric position of a named string. Optionally,you can provide a position m to start searching, and the occurrence n of the string. m and n default to 1, meaning start the search at the beginning of the search and report the first occurrence.

AGGREGATE FUNCTIONS: Group functions operate on sets of rows to give one result per group. Syntax SELECT [column,] group_function(column), ... FROM table [WHERE condition] [GROUP BY column] [ORDER BY column]; EXPLANATIONS DISTINCT makes the function consider only nonduplicate values; ALL makes it consider every value including duplicates. The default is ALL and therefore does not need to be specified. The data types for the functions with an expr argument may be CHAR, VARCHAR2, NUMBER, or DATE. All group functions ignore null values. To substitute a value for null values, use the NVL, NVL2, or COALESCE functions. The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY clause. To override this default ordering, DESC can be used in an ORDER BY clause. www.sace-cse.com Page 18

Types of Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE

Function Description AVG([DISTINCT|ALL]n) Average value of n, ignoring null values

COUNT({*|[DISTINCT|ALL]expr}) Number of rows, where expr evaluates to something other than null (count all selected rows using *, including duplicates and rows with nulls) MAX([DISTINCT|ALL]expr) MIN([DISTINCT|ALL]expr) STDDEV([DISTINCT|ALL]x) SUM([DISTINCT|ALL]n) VARIANCE([DISTINCT|ALL]x) Maximum value of expr, ignoring null values Minimum value of expr, ignoring null values Standard deviation of n, ignoring null values Sum values of n, ignoring null values Variance of n, ignoring null values

Creating Groups of Data: The GROUP BY Clause Syntax SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column];

EXPLANATION Divide rows in a table into smaller groups by using the GROUP BY clause.
group_by_expression specifies columns whose values determine the basis for grouping rows

www.sace-cse.com

Page 19

1.SINGLE FUNCTIONS. SQL> select sysdate from dual; SYSDATE -------------22-AUG-06 SQL> select user from dual; USER -------ITR63 SQL> select userenv('terminal') from dual; USERENV('TERMINAL) -------------------------------IT2 SQL> select loan_number,round(amount,0) from loan; LOAN_NUMBER ---------------------L-11 L-14 L-15 L-16 L-17 L-23 L-93 ROUND(AMOUNT,0) --------------------------900 1500 1500 1300 1000 2000 500

SQL> select round(7643.5461,-3) from dual; ROUND(7643.5461,-3) ---------------------------8000 SQL> select upper(customer_name) from customer; UPPER (CUSTOMER_NAME) -------------------------------------ADAMS BROOKS CURRY GLENN GREEN www.sace-cse.com Page 20

5 rows selected. SQL> select lower(customer_name) from customer; LOWER(CUSTOMER_NAME) --------------------------------------adams brooks curry glenn green 5 rows selected. SQL> select initcap(customer_name) from customer; INITCAP(CUSTOMER_NAME) ---------------------------------------Adams Brooks Curry Glenn Green 5 rows selected. SQL> select trunc(4646.787878,2) from dual; TRUNC (4646.787878,2) -----------------------------4646.78 SQL> select customer_name,length(customer_name) as namelength from customer where length(customer_name)>6; CUSTOMER_NAME -------------------------Johnson Lindsay Williams NAMELENGTH --------------------7 7

www.sace-cse.com

Page 21

2.AGGREGATE FUNCTIONS. SQL> select avg(balance) from account where branch_name='Brighton'; AVG(BALANCE) ---------------------826 SQL> select branch_name,min(balance) from account group by branch_name having avg(balance)>1000; BRANCH_NAME ---------------------Pbridge RoundHill MIN (BALANCE) --------------------1600 1400

SQL> select count (*) from account; COUNT(*) ------------7 SQL> select sum(assets) from branch where branch_name='Redwood'; SUM(ASSETS) ------------------2100000

www.sace-cse.com

Page 22

RESULT: Thus the datas are manipulated using SQL functions .

www.sace-cse.com

Page 23

4. SET OPERATIONS,JOINS AND NESTED QUERIES.

AIM: To you learn how to write queries by using SET operators, obtain data from more than one table and to write subqueries in the WHERE clause of another SQL statement to obtain values based on an unknown conditional value.

SET OPERATIONS:
The SET Operators: SYNTAX: Subquery setoperator subquery EXPLANATION: The SET operators combine the results of two or more component queries into one result. Queries containing SET operators are called compound queries. All SET operators have equal precedence. If a SQL statement contains multiple SET operators, the UNION All distinct rows selected by either query

UNION ALL All rows selected by either query, including all duplicates INTERSECT All distinct rows selected by both queries MINUS All distinct rows that are selected by the first SELECTstatement and not selected in the second SELECT statement JOINS: Join Syntax Use a join to query data from more than one table. Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table. SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;

www.sace-cse.com

Page 24

EXPLANATION When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. To display data from two or more related tables, write a simple join condition in the WHERE clause. In the syntax: table1.column d table1.column1 table2.column2 When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name. To join n tables together, you need a minimum of n-1 join conditions.For eg,to join four tables, a minimum of three joins is required.This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row. enotes the table and column from which data is retrieved = is the condition that joins (or relates) the tables together

Outer Joins Syntax You use an outer join to also see rows that do not meet the join condition. The Outer join operator is the plus sign (+). SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+);

Using Outer Joins to Return Records with No Direct Match The missing rows can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the side of the join that is

www.sace-cse.com

Page 25

deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the nondeficient table can be joined. In the syntax: table1.column = table2.column (+) WHERE is the condition that joins (or relates) the tables together. is the outer join symbol, which can be placed on either side of the clause condition, but not on both sides. (Place the outerjoin symbol

following the name of the column in the table withoutthe matching rows. Outer Join Restrictions The outer join operator can appear on only one side of the expressionthe side that has information missing. It returns those rows from one table that have no direct match in the other table. A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator.. NESTED SUBQUERY Subquery Syntax The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); EXPLANATION: A subquery must be enclosed in parentheses. Place the subquery on the right side of the comparison condition for readability. Two classes of comparison conditions are used in subqueries: single-row operators and multiplerow operators. Types of Subqueries Single-row subqueries: Queries that return only one row from the inner SELECT statement Multiple-row subqueries: Queries that return more than one row from the inner SELECT statement

www.sace-cse.com

Page 26

SET OPERATIONS:
1. UNION: SQL> select account from account union select loanno from loan; ACCOUNT -------------------A-101 A-102 A-201 A-215-217 A-222 A-305 L-11 L-14 L-15 L-16 ACCOUNT -------------------L-17 L-23 L-93 14 rows selected. 2. UNION ALL: SQL> select account from account union all select loanno from loan; ACCOUNT -------------------A-101 A-215 A-102 A-305 A-201 A-222 A-217 L-17

L-23 L-15 L-14

www.sace-cse.com

Page 27

ACCOUNT -------------------L-93 L-11 L-16 14 rows selected. 3. SET DIFFERENCE: SQL> select customername from depositer minus select customername from borrower; CUSTOMERNAME -------------------johnson lindoay turner 4. SET INTERSECTION: SQL> select customername from depositer intersect select customername from borrower; CUSTOMERNAME -------------------hayes jones smith JOINS: 1. INNER JOIN: SQL> select *from loan inner join borrower on loan.loanno=borrower.loanno; LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO --------------------

L-11 L-11 L-14 L-14 L-15 L-15

roundhill

500 williams

downtown

1500 jackson

perryridge

1500 hayes Page 28

www.sace-cse.com

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-16 perryridge 1300 adams L-16 L-17 L-17 L-17 L-17 Downtown 1000 jones

Downtown

1000 smith

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-23 redwood 2000 smith L-23 L-93 L-93 mianus 500 curry

8 rows selected. 2. LEFT OUTER JOIN: SQL> select * from loan left outer join borrower on loan.loanno=borrower.loanno; LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-17 Downtown 1000 jones L-17

L-23 L-23 L-15 L-15

redwood

2000 smith

perryridge

1500 hayes

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------www.sace-cse.com Page 29

L-14 L-14 L-93 L-93 L-17 L-17

downtown

1500 jackson

mianus

500 curry

Downtown

1000 smith

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-11 roundhill 500 williams L-11 L-16 L-16 perryridge 1300 adams

8 rows selected. 3. RIGHT OUTER JOIN: SQL> select * from loan right outer join borrower on loan.loanno=borrower.loanno; LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-17 Downtown 1000 smith L-17 L-17 L-17 L-23 L-23 Downtown 1000 jones

redwood

2000 smith

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-15 perryridge 1500 hayes L-15 L-14 L-14 downtown 1500 jackson

www.sace-cse.com

Page 30

L-93 L-93

mianus

500 curry

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-11 roundhill 500 williams L-11 L-16 L-16 perryridge 1300 adams

8 rows selected. 4. FULL OUTER JOIN: SQL> select * from loan full outer join borrower on loan.loanno=borrower.loanno; LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-17 Downtown 1000 jones L-17 L-23 L-23 L-15 L-15 redwood 2000 smith

perryridge

1500 hayes

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------LOANNO -------------------L-14 downtown 1500 jackson L-14 L-93 L-93 L-17 L-17 mianus 500 curry

Downtown

1000 smith

LOANNO BRANCHNAME AMOUNT CUSTOMERNAME -------------------- -------------------- ---------- -------------------www.sace-cse.com Page 31

LOANNO -------------------L-11 roundhill L-11 L-16 L-16 perryridge

500 williams

1300 adams

8 rows selected. NESTED QUERIES: 1. SQL> select * from account where balance > (select avg(balance) from account); ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-222 1200 redwood A-217 1200 brighton 2. SQL> select * from account where branchname not in(select distinct branchname from branch)order by branchname; ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-217 1200 brighton 3. SQL> select * from account where(branchname,balance) in (select branchname,max(balance)from account group by branchname); ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-217 1200 brighton A-101 500 downtown A-102 396 perryridge A-222 1200 redwood A-305 346.5 roundhill 7 rows selected. 4. SQL> select * from account where balance>(select avg(balance) from account where account.account=account) order by branchname; www.sace-cse.com Page 32

ACCOUNT BALANCE BRANCHNAME -------------------- ---------- -------------------A-215 1200 Mianus A-201 1200 brighton A-217 1200 brighton A-222 1200 redwood 5. SQL> select distinct customername from customer where customername in (select customername from borrower); CUSTOMERNAME -------------------curry hayes jones smith williams

www.sace-cse.com

Page 33

RESULT: Thus SQL statements using set operations, joins and nested sub queries are executed.

www.sace-cse.com

Page 34

5.CURSORS
AIM: To create a cursor and to retrieve the details from the account and the depositer tables.

PACKAGE USED: ORACLE

ALGORITHM: 1.Start the program. 2.Create the cursors for the account, depositer tables. 3.Display the required details. 4.Close the cursors. 5.End of the program. SQL>DECLARE 2 var number; 3 CURSOR c1 is 4 SELECT balance FROM account; 5 BEGIN 6 dbms_output.put_line('BALANCE'); 7 OPEN c1; 8 LOOP 9 FETCH c1 INTO var; 10 dbms_output.put_line(var); 11 EXIT WHEN c1% notfound; 12 END LOOP; 13 CLOSE c1; 14 END; 15 / PL/SQL procedure successfully completed. SQL>set serverout ON; SQL>DECLARE 2 var number; 3 CURSOR c1 is 4 SELECT balance FROM account; 5 BEGIN 6 dbms_output.put_line('BALANCE'); 7 OPEN c1; 8 LOOP www.sace-cse.com Page 35

9 FETCH c1 INTO var; 10 dbms_output.put_line(var); 11 EXIT WHEN c1% notfound; 12 END LOOP; 13 CLOSE c1; 14 END; 15 / BALANCE -------------500 1600 900 700 752 700 1400 PL/SQL procedure successfully completed. (SAVE IT TO S.SQL IN C:\ORACLE\ORA90\BIN) SQL>@ s.sql; BALANCE -------------500 1600 900 700 752 700 1400 1400 PL/SQL procedure successfully completed. SQL>DECLARE 2 dacno depositer.account_number%type; 3 aacno account.account_number%type; 4 bal account.balance%type; 5 cname depositer.customer_name%type; 6 CURSOR c is SELECT customer_name,account_number FROM depositer; 7 CURSOR c1 is SELECT balance,account_number FROM account; 8 BEGIN 9 OPEN c; 10 OPEN c1; 11 FETCH c INTO cname,dacno; 12 FETCH c1 INTO bal,aacno; 13 LOOP 14 LOOP 15 IF (dacno=aacno) THEN www.sace-cse.com Page 36

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33*

dbms_output.put_line('CUSTOMER NAME'); dbms_output.put_line(cname); dbms_output.put_line('BALANCE'); dbms_output.put_line(bal); FETCH c INTO cname,dacno; ELSE FETCH c INTO cname,dacno; END IF; EXIT WHEN c%notfound; END LOOP; CLOSE c; OPEN c; EXIT WHEN c1%notfound; FETCH c1 INTO bal,aacno; END LOOP; CLOSE c; CLOSE c1; END;

CUSTOMER NAME Johnson BALANCE 500 CUSTOMER NAME Hayes BALANCE 1600 CUSTOMER NAME Johnson BALANCE 900 CUSTOMER NAME Smith BALANCE 700 CUSTOMER NAME Jones BALANCE 752 CUSTOMER NAME Lindsay BALANCE 700 CUSTOMER NAME Lindsay BALANCE 700 PL/SQL procedure successfully completed. www.sace-cse.com Page 37

2. FIND THE NUMBER OF CUSTOMERS AT A GIVEN BRANCH. PROGRAM: SQL > create or replace function counting(bn varchar2) 2 return number 3 is a number; 4 cursor c is select count(accountnumber) from account where branchname=bn; 5 begin 6 open c; 7 fetch c into a;

8 return(a); 9 close c; 10 end; / Function created. OUTPUT: SQL> select counting('brighton') from dual; COUNTING('BRIGHTON') -------------------2 SQL> select counting('perryridge') from dual; COUNTING('PERRYRIDGE') ---------------------1

www.sace-cse.com

Page 38

RESULT: Thus the cursor is created, executed and the output is verified. www.sace-cse.com Page 39

6. FUNCTIONS
AIM:

To create a recursive function to find the factorial of a given number using SQL commands. ALGORITHM:

Step 1:Start the program. Step 2:Get the input number. Step 3:If the number is 0 or 1 then , return 1. Step 4:Else calculate the factorial using the recursive function. Step 5:Return the factorial value. Step 6:End the program. SYNTAX: create [or replace] function <function name> (parameter1,parameter2,) return <data type> is [constant/variable declaration] begin executable statements return <return values> exception[exception handling statements] return <return values> end;

www.sace-cse.com

Page 40

SQL COMMAND: SQL> CREATE OR REPLACE FUNCTION fact(no number) 2 RETURN number 3 IS 4 a number; 5 BEGIN 6 IF(no=0 or no=1) 7 THEN 8 RETURN(1); 9 ELSE 10 a:=no*fact(no-1); 11 RETURN(a); 12 END IF; 13 END; 14 / Function created. OUTPUT: SQL> select fact (5) from dual; FACT (5) ------------120 2. FIND THE NUMBER OF CUSTOMERS AT A GIVEN BRANCH. PROGRAM: SQL > create or replace function counting(bn varchar2) 2 return number 3 is a number; 4 cursor c is select count(accountnumber) from account where branchname=bn; 5 begin 6 open c; 7 fetch c into a; 8 return(a); 9 close c; 10 end; / Function created.

www.sace-cse.com

Page 41

OUTPUT: SQL> select counting('brighton') from dual; COUNTING('BRIGHTON') -------------------2 SQL> select counting('perryridge') from dual; COUNTING('PERRYRIDGE') ---------------------1

7. PROCEDURES

AIM: To create a procedure using SQL commands. PACKAGE USED: ORACLE

ALGORITHM: 1.Start the program. 2.Create cursor for the table account. 3.If the balance is less than 5000 print that the balance is low. 4.Else update the account table with the given interest. 5.End of the program.

SYNTAX: CREATE [OR REPLACE] procedure procedure name [(parameter1,parameter2,)] IS [CONSTANT/ variable declarations] BEGIN Exception statements [Exception handling statements] www.sace-cse.com Page 42

End [procedure name]; PROGRAM: SQL> CREATE OR REPLACE PROCEDURE interest(iR1 real,ir2 real) 2 IS old_bal number(9); 3 c_id account.account_number%type; 4 CURSOR a IS SELECT balance,account_number FROM account; 5 BEGIN 6 OPEN a; 7 LOOP 8 FETCH a INTO old_bal,c_id; 9 EXIT WHEN a% NOTFOUND; 10 IF old_bal<5000 11 THEN 12 DBMS_OUTPUT.PUT_LINE('BAL LESS THAN MIN'||c_id); 13 ELSIF old_bal BETWEEN 5000 AND 10000 14 THEN 15 UPDATE account SET balance=old_bal+(old_bal*ir1) where account_number=c_id; 16 ELSE 17 UPDATE account SET balance=old_bal+(old_bal*iR2) where account_number=c_id; 18 END IF; 19 END LOOP; 20 CLOSE a; 21* END; SQL> / Procedure created. SQL> select * from account; ACCOUNT_NU BRANCH_NAM ---------- ---------- ---------A-101 Downtown 2846 A-102 Pbridge 9094 A-201 Brighton 5108 A-215 Mianus 3982 A-217 Brighton 4272 A-222 Redwood 3982 A-305 RoundHill 7949 7 rows selected. BALANCE

SQL> set serverout on; SQL> call interest(.05,.1); BAL LESS THAN MINA-101 BAL LESS THAN MINA-215 www.sace-cse.com Page 43

BAL LESS THAN MINA-217 BAL LESS THAN MINA-222 Call completed. SQL> select * from account; ACCOUNT_NU BRANCH_NAM ---------- ---------- ---------A-101 Downtown 2846 A-102 Pbridge 9549 A-201 Brighton 5363 A-215 Mianus 3982 A-217 Brighton 4272 A-222 Redwood 3982 A-305 RoundHill 8346 7 rows selected. BALANCE

www.sace-cse.com

Page 44

RESULT: www.sace-cse.com Page 45

Thus the procedure is created,executed and the output is verified.

8.TRIGGERS
AIM: To create triggers using SQL commands.

PACKAGE USED: Oracle.

TRIGGERS: A database trigger, known simply as a trigger, is a PL/SQL block. It is stored in the database and is called implicitly when a triggering event occurs. A user does not call a trigger explicitly.

SYNTAX: CREATE [OR REPLACE] TRIGGER <trigger_name> BEFORE/AFTER triggering event ON <table_name> [FOR EACH ROW] [WHEN condition] DECLARE Declaration statements; BEGIN Executable statements; EXCEPTION Exception handling statements; END;

www.sace-cse.com

Page 46

Example: SQL> create table stu(name varchar2(15),roll_no number(5) primary key, sem varchar2(5),dep varchar2(5)); Table created. SQL> create table stu1 as(select * from stu); Table created. SQL>1 create or replace trigger database after insert on stu 2 for each row 3 begin 4 insert into stu1 values(:new.name,:new.roll_no,:new.sem,:new.dep); 5 DBMS_OUTPUT.PUT_LINE('STU1 ALSO UPDATED BY TRIGGER'); 6 end; Trigger created. SQL> insert into stu values('&name',&roll_no,'&sem','&dep'); Enter value for name: Latha Enter value for roll_no: 27 Enter value for sem: fifth Enter value for dep: IT old 1: insert into stu values('&name',&roll_no,'&sem','&dep') new 1: insert into stu values('Latha',27,'fifth',' IT') 1 row created. SQL> / Enter value for name: Revathi Enter value for roll_no: 43 Enter value for sem: sixth Enter value for dep: CSE old 1: insert into stu values('&name',&roll_no,'&sem','&dep') new 1: insert into stu values('Revathi',43,'sixth','CSE') 1 row created. SQL> select * from stu; NAME ROLL_NO SEM DEP -------- ----------------- ----Latha 27 fifth IT Revathi 43 sixth CSE Mahe 28 Sixth EEE Moni 32 third ECE

SQL> select * from stu1; www.sace-cse.com Page 47

NAME ROLL_NO SEM DEP -------- ----------------- ----Latha 27 fifth IT Revathi 43 sixth CSE Mahe 28 Sixth EEE Moni 32 third ECE SQL> 1 create or replace trigger database before delete on stu 2 for each row 3 begin 4 delete from stu1 where stu1.roll_no=:old.roll_no; 5 DBMS_OUTPUT.PUT_LINE('STU1 ALSO UPDATED BY TRIGGER'); 6 end; 7 / Trigger created. SQL> delete from stu where roll_no=43; 1 row deleted. SQL> select * from stu; NAME ROLL_NO SEM DEP -------- ----------------- ----Latha 27 fifth IT Mahe 28 Sixth EEE Moni 32 third ECE SQL> select * from stu1; NAME ROLL_NO SEM -------- ----------------Latha 27 fifth Mahe 28 Sixth Moni 32 third DEP ----IT EEE ECE

2.CREATE A TRIGGER TO DELETE AN ACCOUNT FROM DEPOSITER WHEN DELETED IN ACCOUNT PROGRAM: SQL> 1 create or replace trigger datbase before delete on account 2 for each row 3 begin 4 delete from depositer where depositer.accountnumber=:old.accountnumber; 5 end; 6 / www.sace-cse.com Page 48

Trigger created. OUTPUT: SQL> delete from account where accountnumber='A-101'; 1 row deleted.

SQL> select * from account; ACCOUNTNUMBER -------------------A-215 A-102 A-305 A-201 A-222 A-217 6 rows selected. BRANCHNAME -------------------mianus perryridge roundhill brighton redwood brighton BALANCE ---------1389.15 396 346.5 1389.15 1389.15 1389.15

SQL> select * from depositer; CUSTOMERNAME -------------------smith hayes turner johnson jones lindsay 6 rows selected. ACCOUNTNUMBER -------------------A-215 A-102 A-305 A-201 A-217 A-222

www.sace-cse.com

Page 49

RESULT: www.sace-cse.com Page 50

Thus the trigger is created by using SQL commands and it is being executed and output is verified.

9.TRANSACTION CONTROL: AIM:


To learn and use the transaction control statements. EXPLICIT TRANSCATION CONTROL STATEMENTS: COMMIT ROLLBACK SAVEPOINT EXPLANATION With COMMIT and ROLLBACK statements, you can: Ensure data consistency Preview data changes before making changespermanent Group logically related operations statements. Statement Description COMMIT SAVEPOINT ROLLBACK Ends the current transaction by making all pending data changes permanent name Marks a savepoint within the current transaction ends the current transaction by discarding all pending data changes

ROLLBACK TO SAVEPOINT name ROLLBACK TO SAVEPOINT rolls back the current transaction tothe specified savepoint, thereby discarding any changes and orsavepoints created after the savepoint to which you are rolling back. If you omit the TO SAVEPOINT clause, the ROLLBACK statement rolls back the entire transaction. As savepoints are logical, there is no way to list the savepoints you have created. Rolling Back Changes to a Marker Create a marker in a current transaction by using the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. UPDATE... SAVEPOINT update_done; Savepoint created. INSERT... www.sace-cse.com Page 51

ROLLBACK TO update_done; Rollback complete.

SAVE POINT:
SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-17 Downtown 1000 L-23 redwood 2000 L-15 perryridge 1500 L-14 downtown 1500 L-93 mianus 500 L-11 roundhill 500 L-16 perryridge 1300 7 rows selected. SQL> save b; Created file b.sql SQL> delete from loan where loanno='L-17'; 1 row deleted. SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-23 redwood 2000 L-15 perryridge 1500 L-14 downtown 1500 L-93 mianus 500 L-11 roundhill 500 L-16 perryridge 1300 6 rows selected.

ROLLBACK:
www.sace-cse.com Page 52

SQL> rollback; Rollback complete. SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-17 Downtown 1000 L-23 redwood 2000 L-15 perryridge 1500 L-14 downtown 1500 L-93 mianus 500 L-11 roundhill 500 L-16 perryridge 1300 7 rows selected.

COMMIT:
SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-23 redwood 2000 L-15 perryridge 1500 L-14 downtown 1500 L-93 mianus 500 L-11 roundhill 500 L-16 perryridge 1300 L-17 downtown 1000 7 rows selected. SQL> save d; Created file d.sql SQL> delete from loan where loanno='L-17'; 1 row deleted.

SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-23 redwood 2000 www.sace-cse.com Page 53

L-15 L-14 L-93 L-11 L-16

perryridge downtown mianus roundhill perryridge

1500 1500 500 500 1300

6 rows selected.

COMMIT:
SQL> commit; Commit complete. SQL> select * from loan; LOANNO BRANCHNAME LOAANAMOUNT -------------------- -------------------- ----------L-23 redwood 2000 L-15 perryridge 1500 L-14 downtown 1500 L-93 mianus 500 L-11 roundhill 500 L-16 perryridge 1300 6 rows selected.

RESULT: Thus the Transaction control statements are known and used.

www.sace-cse.com

Page 54

10.DCL COMMANDS AIM To learn how to control database access to specific objects and add new users with
different levels of access privileges and execute..

DCL COMMANDS: GRANT REVOKE CREATE USER SYNTAX: CREATE USER user IDENTIFIED BY password; GRANT: SYNTAX: GRANT privilege [, privilege...] TO user [, user| role, PUBLIC...]; REVOKE {privilege [, privilege...]|ALL} ON object FROM {user[, user...]|role|PUBLIC} [CASCADE CONSTRAINTS]; EXPLANATION: object_priv ALL columns ON TO PUBLIC is an object privilege to be granted specifies all object privileges specifies the column from a table or view on which privileges are granted object is the object on which the privileges are granted identifies to whom the privilege is granted grants object privileges to all users

WITH GRANT OPTION allows the grantee to grant the object privileges to other users and roles REVOKE: SYNTAX: REVOKE {privilege [, privilege...]|ALL} ON object FROM {user[, user...]|role|PUBLIC} [CASCADE CONSTRAINTS]; EXPLANATION: www.sace-cse.com Page 55

CASCADE is required to remove any referential integrity constraints made to the CONSTRAINTS object by means of the REFERENCES privilege

1.SYSTEM PRIVILIGES:
A.CREATE USER CREATE USER scott IDENTIFIED BY tiger; User created. B. GRANT: 1. SQL> grant create table to it5; Grant succeeded. 2. SQL> create user it100 identified by deepa; User created.

3. SQL> grant all privilege to it5; Grant succeeded. C. REVOKE: 1. SQL> revoke create table from it5; Revoke succeeded. 2. SQL> revoke all privilege from it5; Revoke succeeded.

2. OBJECT PRIVILEGES: A. GRANT:


1. SQL> grant select on loan to it1; Grant succeeded. www.sace-cse.com Page 56

2. SQL> grant update on loan to it3; Grant succeeded. 3. SQL> grant delete on loan to it3; Grant succeeded.

B. REVOKE:
1. SQL> revoke select on loan from it1; Revoke succeeded. 2. SQL> revoke update on loan from it3; Revoke succeeded. 3. SQL> revoke delete on loan from it3; Revoke succeeded.

RESULT: www.sace-cse.com Page 57

Thus the DCL commands are executed .

11 Design and implementation of Banking System. AIM


To develop an effective software system for the banking enterprise.

SYSTEM REQUIREMENTS: SOFTWARE REQUIREMENTS: Front end: Microsoft Visual basic 6.0 Back end:MS Acess. MODULES USED: Adding a new client. Update Search Delete TABLE DESIGN ACCOUNT ATTRIBUTES Acno Name Balance Address Phonenumber LOAN ATTRIBUTES Loan number Account number Amount Address Phone number www.sace-cse.com DATATYPE string string currency string string Page 58 DATATYPE string string currency string string

SOFTWARE REQUIREMENT SPECIFICATION ABSTRACT This is the requirement document for the banking management system. The system to be developed is for banking based on inputs such as name, accno and balance of different users. SPECIFIC REQUIREMENTS: The system has input file and produces output. INPUT The input includes the person name accno and the balance . OUTPUT The output includes the balance for a specified accno,deposit amount and balance after deposit, and withdraw the balance will be displayed the updates and inserts will be stored in the database.

www.sace-cse.com

Page 59

Potrebbero piacerti anche