1

INTRODUCTION TO STRUCTURED QUERY LANGUAGE(SQL)

SQL often referred to as Structured Query Language, is a database computer language designed for managing data in relational database management systems (RDBMS), and originally based upon relational algebra and calculus. Its scope includes data , query, update and delete, schema creation and modification, and data access control. SQL was one of the first commercial languages for Edgar F. Codd's relational model, as described in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks". Despite not adhering to the relational model as described by Codd, it became the most widely used database language.

LANGUAGE ELEMENTS

The SQL language is sub-divided into several language elements, including:

 Clauses, which are constituent components of statements and queries. (In some cases, these are optional.)  Expressions, which can produce either scalar values or tables consisting of columns and rows of data.  Predicates, which specify conditions that can be evaluated to SQL three-valued logic (3VL) or Boolean (true/false/unknown) truth values and which are used to limit the effects of statements and queries, or to change program flow.  Queries, which retrieve the data based on specific criteria. This is the most important element of SQL.  Statements, which may have a persistent effect on schemata and data, or which may control transactions, program flow, connections, sessions, or diagnostics. o SQL statements also include the semicolon (";") statement terminator. Though not required on every platform, it is defined as a standard part of the SQL grammar.  Insignificant whitespace is generally ignored in SQL statements and queries, making it easier to format SQL code for readability.

Data types

Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the following datatypes.

Character strings

 CHARACTER(n) or CHAR(n) — fixed-width n-character string, padded with spaces as needed  CHARACTER VARYING(n) or VARCHAR(n) — variable-width string with a maximum size of n characters  NATIONAL CHARACTER(n) or NCHAR(n) — fixed width string supporting an international character set  NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) — variable-width NCHAR string

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 2

Bit strings

 BIT(n) — an array of n bits  BIT VARYING(n) — an array of up to n bits

Numbers

 INTEGER and SMALLINT  FLOAT, REAL and DOUBLE PRECISION  NUMERIC(precision, scale) or DECIMAL(precision, scale)

SQL provides a function to round numerics or dates, called TRUNC (in Informix, DB2, PostgreSQL, Oracle and MySQL) or ROUND (in Informix, Sybase, Oracle, PostgreSQL and Microsoft SQL Server)[19]

Date and time

 DATE — for date values (e.g., 2010-05-30)  TIME — for time values (e.g., 14:55:37). The granularity of the time value is usually a tick (100 nanoseconds).  TIME WITH TIME ZONE or TIMESTAMP — the same as TIME, but including details about the time zone in question.  TIMESTAMP — This is a DATE and a TIME put together in one variable (e.g., 2010- 05-30 14:55:37).  TIMESTAMP WITH TIME ZONE or TIMESTAMPTZ — the same as TIMESTAMP, but including details about the time zone in question.

Different types of commands in SQL: A).DDL commands: - To create a database objects B).DML commands: - To manipulate data of a database objects C).DQL command: - To retrieve the data from a database. D).DCL/DTL commands: - To control the data of a database…

THE ORACLE TABLE – DUAL DUAL is the table owned by SYS.SYS owns the data dictionary and DUAL is a part of the data dictionary.DUAL is a small oracle worktable, which consists of only one row and one column, and contains the value x in that column .Besides arithmetic calculations it also supports date retrieval and it’s formatting

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 3

ORACLE FUNCTIONS Oracle functions serve the purpose of manipulating data items and returning a result Functions are also capable of accepting user supplied variables or constants and operating on them Such variables or constants are called arguments. Any number of arguments (or no arguments at all) can be passed to a function in the following format: Function_name(argument1,argument2,………..) Oracle Functions can be clubbed together depending upon whether they operate on a single row or a group of rows retrieved from a table.Accordingly, functions an be classified as follows: Group Functions(Aggregate Functions) Functions that act on a set of values are called Group functions.For example, SUM is a function which calculates the total set of numbers.A group function returns a single result row for a group of queried rows. Scalar Functions(Single Row Functions) Functions that act on only one value at a time are called Scalar functions.For example ,Length relates to the String Data type .Functions can be classified corresponding to different data types as: String Functions : For String data type Numeric Functions : For Number data type Conversion Functions : For Conversion data type to another Date Functions : For Date data type

Additional Exercise-I Queries to facilitate acquaintance of Built-In Functions : Aggregate functions

 AGGREGATE FUNCTIONS

1. AVG:Returns an average value of ‘n’, ignoring values in a column.

Syntax: AVG ([| ] )

Example: SELECT AVG(CURBAL) “Average balance” FROM ACCT_MSTR;

2.MIN:Returns a minimum value of expr

Syntax: MIN([| ] )

Example : SELECT MIN(CURBAL) “Minimum balance” FROM ACCT_MSTR;

3.MAX:Returns a maximum value of expr.

Syntax: MAX([| ] )

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 4

Example: SELECT MAX(CURBAL) “Maximum balance” FROM ACCT_MSTR;

4.COUNT: Returns the number of rows where expr is not null.

Syntax: COUNT ([| ] )

Example : SELECT COUNT(ACCT_NO) “No of accounts” FROM ACCT_MSTR;

5.COUNT(*):Returns the number of rows in the table , including duplicates and those with nulls.

Syntax: COUNT(*)

Example: SELECT COUNT(*) “No of records” FROM ACCT_MSTR;

6. SUM:Returns the sum of the values of ‘n’.

Syntax: SUM([| ] )

Example: SELECT SUM(CURBAL) “Total Balance” FROM ACCT_MSTR;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 5

Exercise-I Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric Functions, Date Functions and Conversion Functions.

A.NUMERIC FUNCTIONS 1.ABS:Returns the absolute value of ‘n’.

Syntax: ABS(n)

Example : SELECT ABS(-15) “Absolute” FROM DUAL;

2.POWER:Returns m raised to the n th power .n must be an integer, else an error is returned.

Syntax: POWER(m,n)

Example: SELECT POWER(3,2) “Raised” FROM DUAL;

3.ROUND:Returns n, rounded to m places to the right of a decimal point. If m is omitted, n is rounded to 0 places.m can be negative to round off digits to the left of the decimal point.m must be an integer.

Syntax:ROUND(n[,m])

Example: SELECT ROUND(15.19,1) “ROUND” FROM DUAL;

4.SQRT:Returns square root of n.If n<0, NULL.SQL reurns a real result.

Syntax: SQRT(n)

Example : SELECT SQRT(25) “Square Root” FROM DUAL;

5.EXP:Returns e raised to the n th power, where e=2.71828183.

Syntax: EXP(n) Example SELECT EXP(5) “Exponent” FROM DUAL;

6.GREATEST : Returns the greatest value in a list of expressions.

Syntax:

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 6

GREATEST(expr1,expr2,………….,expr_n) Where the expr1,expr2,………….,expr_n are expressions that are evaluated by the greatest function.

Example SELECT GREATEST (5,6,17) “num” FROM DUAL;

7.LEAST : Returns the LEAST value in a list of expressions.

Syntax: LEAST(expr1,expr2,………….,expr_n) Where the expr1,expr2,………….,expr_n are expressions that are evaluated by the LEAST function.

Example: SELECT LEAST (5,6,17) “num” FROM DUAL;

8.MOD:Returns the remainder of the first number divided by the second number passed a parameter . If the second number is zero , the result is the same as the first number.

Syntax: MOD(m,n)

Example : SELECT MOD(15,7) “RESULT” FROM DUAL;

9.FLOOR:Returns the largest integer value that is equal to or less than a number.

Syntax: FLOOR(n)

Example: SELECT FLOOR(24.8) “FLOOR” FROM DUAL;

10. CEIL: Returns the SMALLEST integer value that is equal to or greater than a number.

Syntax: CEIL(n)

Example: SELECT CEIL(24.8) “CEIL” FROM DUAL;  STRING FUNCTIONS 1.LOWER:Returns char, with all letters in lowercase.

Syntax: LOWER(char)

Example:SELECT LOWER (‘DHANEKULA’) “Lower” FROM DUAL;

2.UPPER:Returns char, with all letters in uppercase.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 7

Syntax:UPPER(char)

Example:SELECT UPPER (‘dhanekula’) “Upper” FROM DUAL;

3.SUBSTR:Returns a portion of characters, beginning at character m, and going upto character n. If n is omitted, the result returned is upto the last character in the string.The first position of the char is 1.

Syntax: SUBSTR(,,[]) Where < string> is the source string. is the position for extraction. The first position in the string is always 1. is the number of characters to extract.

Example SELECT SUBSTR(‘SECURE’,3,4) “Substring” FROM DUAL;

4. INSTR:Returns the location of a substring in a string. Syntax: INSTR(,(, [],[]) Where , is the string to search. is the substring to search for in string1. is the position in string1 where the search will start. If omitted , it defaults to 1. The first position in the string is 1. nth_appearance is the nth appearance of string2 .If omitted, it defaults to 1.

Example: SELECT INSTR(‘SCT on the net’,’t’) “instr” FROM DUAL;

5. LENGTH:Returns the length of a word.

Syntax: LENGTH(word)

Example: SELECT LENGTH(‘DHANEKULA’) “Length” FROM DUAL;

6. LTRIM:Removes characters from the left of char with initial characters removed upto the first character not in set.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 8

Syntax: LTRIM(char,[set])

Example: SELECT LTRIM(‘NISHA’,’N’) “LTRIM” FROM DUAL;

7. RTRIM:Returns char, with final characters removed after the last character not in the set. ‘set’ is optional it defaults to spaces

Syntax: RTRIM(char,[set])

Example: SELECT RTRIM(‘SUNILA’,’A’) “RTRIM” FROM DUAL;

8. TRIM:Removes all specified characters either from the beginning or the ending of a string .

Syntax: Trim([leading|Trailing|both[ from ]] ) Where Leading – remove trim_string from the front of string1 Trailing – remove trim_string from the end of string1 Both – remove trim_string from the front and end string1 If none of the above option is chosen , it takes ‘Both’ Option.

Example: SELECT TRIM (‘ Hansel’) “Trim both sides” FROM DUAL

9. LPAD: Returns char1, left-padded to length n with the sequence of characters specified in CHAR2. if CHAR2 is not specified Oracle uses blanks by default.

Syntax: LPAD(char1, n,[,char2])

Example : SELECT LPAD(‘page 1’,10,’*’)”LPAD” from dual

10. RPAD: Returns char1, right-padded to length n with the characters specified in CHAR2. if CHAR2 is not specified Oracle uses blanks by default.

Syntax: RPAD(char1, n,[,char2])

Example: SELECT RPAD(‘page 1’,10,’*’) “RPAD” from dual  DATE FUNCTIONS 1.ADD_MONTHS:Returns date after adding the number of months specified in the function

Syntax: ADD_MONTHS(d,n)

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 9

Example : SELECT ADD_MONTHS(SYSDATE,4) “Add months” FROM DUAL;

2.LAST_DAY: Returns the last date of the month specified with the function.

Syntax: LAST_DAY(d)

Example : SELECT SYSDATE,LAST_DAY(SYSDATE) “LAST DAY” FROM DUAL;

3.MONTHS_BETWEEN:Returns number of months between d1 and d2.

Syntax: MONTHS_BETWEEN (d1,d2)

Example: SELECT MONTHS_BETWEEN (’02-FEB-92’,’02-JAN-92’) “MONTHS” FROM DUAL;

4.NEXT_DAY:Returns the date of the first weekday named by char that is after the date named by date. char must be a day of the week. Syntax: NEXT_DAY (date,char) Example: SELECT NEXT_DAY(’06-JULY-02’,’Saturday’) “NEXT DAY” FROM DUAL;  Conversion Functions 1.TO_NUMBER: Converts char, a CHARACTER value expressing a number, to a NUMBER data type.

Syntax: TO_NUMBER(char) Example: update acct_mstr set curbal=curbal + to_number(substr(‘$100’,2,3));

2. TO_CHAR(number conversion) : Converts a value of a NUMBER datatype to a character datatyp, using the optional format string. TO_CHAR() accepts a number (n) and a numeric format(fmt) in which the number has to appear. If fmt is omitted, n is converted to a char value exactly long enough to hold all significant igits.

Syntax: TO_CHAR(n[,fmt]) Example: to_char(dt,’month dd,yyyy’) “new date format” from trans_mstr where trans_no=’t1’;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 10

3.TO_DATE: Converts a character field to a date field Syntax : TO_DATE(char,[,fmt]) Example: insert into cust_mstr(cust_no,fname,mname,lname,dob_inc) Values(“c1’,’ivan’,’nelson’,’bayross’,to_date(’25-jun-1952 10:55 a.m.’,’dd- mon-hh:mi a.m’));

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 11

Exercise-II Queries using operators in SQL A. Arithmetic Operators Arithmetic operators manipulate numeric operands. The '-' operator is also used in date arithmetic. Supported arithmetic operators are listed in Table Operator Description Example + (unary) Makes operand positive SELECT +3 FROM DUAL; - (unary) Negates operand SELECT -4 FROM DUAL; / Division (numbers and dates) SELECT SAL / 10 FROM EMP; * Multiplication SELECT SAL * 5 FROM EMP; + Addition (numbers and dates) SELECT SAL + 200 FROM EMP; - Subtraction (numbers and SELECT SAL - 100 FROM dates) EMP;

B. Character Operators Character operators used in expressions to manipulate character strings are listed in Table Operator Description Example || Concatenates character SELECT 'The Name of the employee is: ' || ENAME strings FROM EMP;

C.Comparision operators Comparison operators used in conditions that compare one expression with another are listed in Table 2-4. The result of a comparison can be TRUE, FALSE, or UNKNOWN. Operator Description Example = Equality test. SELECT ENAME "Employee" FROM EMP WHERE SAL = 1500; !=, ^=, <> Inequality test. SELECT ENAME FROM EMP WHERE SAL ^= 5000; > Greater than test. SELECT ENAME "Employee", JOB "Title" FROM EMP WHERE SAL > 3000; < Less than test. SELECT * FROM PRICE WHERE MINPRICE < 30; >= Greater than or equal to test. SELECT * FROM PRICE WHERE MINPRICE >= 20; <= Less than or equal to test. SELECT ENAME FROM EMP WHERE SAL <= 1500; IN "Equivalent to any member of" test. Equivalent SELECT * FROM EMP to "=ANY". WHERE ENAME IN ('SMITH', 'WARD');

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 12

ANY/ Compares a value to each value in a list or SELECT * FROM DEPT SOME returned by a query. Must be preceded by =, !=, WHERE LOC = SOME >, <, <= or >=. Evaluates to FASLE if the query ('NEW YORK','DALLAS'); returns no rows. NOT IN Equivalent to "!=ANY". Evaluates to FALSE if SELECT * FROM DEPT any member of the set is NULL. WHERE LOC NOT IN ('NEW YORK', 'DALLAS'); ALL Compares a value with every value in a list or SELECT * FROM emp returned by a query. Must be preceded by =, !=, WHERE sal >= ALL (1400, >, <, <= or >=. Evaluates to TRUE if the query 3000); returns no rows. EXISTS TRUE if a sub-query returns at least one row. SELECT * FROM EMP WHERE EXISTS (SELECT ENAME FROM EMP WHERE MGR IS NULL);

D. Set Oriented Operations

Set operators which combine the results of two queries into a single result are listed in Table Operator Description Example UNION Returns all distinct rows selected SELECT * FROM by either query. (SELECT ENAME FROM EMP WHERE JOB = 'CLERK' UNION SELECT ENAME FROM EMP WHERE JOB = 'ANALYST'); UNION ALL Returns all rows selected by SELECT * FROM either query, including all (SELECT SAL FROM EMP WHERE JOB = duplicates. 'CLERK' UNION SELECT SAL FROM EMP WHERE JOB = 'ANALYST'); INTERSECT Returns all distinct rows selected SELECT * FROM orders_list1 and INTERS by both queries. INTERSECT ECT ALL SELECT * FROM orders_list2 MINUS Returns all distinct rows selected SELECT * FROM (SELECT SAL FROM by the first query but not the EMP WHERE JOB = 'PRESIDENT' second. MINUS SELECT SAL FROM EMP WHERE JOB = 'MANAGER');

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 13

E.Logical operators(AND,OR and NOT)

Operator Description Example NOT Returns TRUE if the following SELECT * FROM EMP WHERE NOT condition is FALSE. (job IS NULL) Returns FALSE if it is TRUE. If it SELECT * FROM EMP WHERE NOT is UNKNOWN, it (sal BETWEEN 1000 AND 2000) remains UNKNOWN. AND Returns TRUE if both component SELECT * FROM EMP WHERE conditions are TRUE. job='CLERK' AND deptno=10 Returns FALSE if either is FALSE; otherwise returns UNKNOWN. OR Returns TRUE if either component SELECT * FROM emp WHERE condition is TRUE. Returns FALSE if job='CLERK' OR deptno=10 both are FALSE. Otherwise, returns UNKNOWN.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 14

Exercise-III Queries to Retrieve and Change Data: Select, Insert, Delete, and Update A. . Viewing data in the tables Once data has been inserted into a table, the next most logical operation would be to view what has been inserted. a) all rows and all columns Syntax: Select to from tablename; or Select * from tablename; Example: select * from branch_mstr;

b) Filtering table data While viewing data from a table, it is rare that all the data from table will be required each time. Hence, must give us a method of filtering out data that is not required data. i) Selected columns and all rows: The retrieval of specific columns from the table can be done as shown below Syntax: select , from ; Example: select branch_no from branch_mstr;

ii ) selected rows and all columns: Oracle provides the option of using WHERE Clause in an SQL query to apply a filter on the rows retrieved Syntax: select * from where ; Example: select * from branch_mstr where branch_no='501';

iii) selected columns and selected rows The retrieval of specific columns and specific rows from the table can be done as shown below Syntax: select , from where; Example: select name from branch_mstr where branch_no='501';

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 15

B. Inserting data into tables Once the table is created , the most natural thing to do is load this table with data to be manipulated later. When inserting a single row of data into the table, the insert operation :  Creates a new row in the database table  Loads the values passed into the columns specified Syntax: INSERT INTO (,) VALUES(,);

Example: Insert into cust_mstr(cno,name) values(10,”raj”); C. DELETE OPERATIONS The DELETE command deletes rows from the table that satisfies the condition provided by its where clause, and returns the number of records deleted. The verb delete in SQL is used to remove either: 1. All the rows from a table. Or 2. A set of rows from a table a.Removal of All Rows Syntax: DELETE FROM ; Example: delete from branch_mstr ; b.Removal Of Specific Rows Syntax: DELETE FROM Where ; Example:

delete from branch_mstr where branch_no='501'; D. Updating the contents of the table The UPDATE command is used to change or modify data values in a table.The verb update in SQL is used to either update: 1. All the rows from a table. Or 2.A select set of rows from a table 1. Updating all Rows The UPDATE statement updates columns in the existing table’s rows with new values. The SET clause indicates which column data should be modified and

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 16

the new values that they should hold. The WHERE clause, if given , specifies which rows should be updated .Otherwise, all table rows are updated.

Syntax: UPDATE SET =,=; Example: update branch_mstr set name = 'ashoknagar'; 2.Updating Records Conditionally Syntax: UPDATE SET =,= WHERE ; Example: update branch_mstr set name = 'ashoknagar' where name='patamata';

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 17

Exercise-IV

Queries using Group By, Order By, and Having Clauses GROUP BY AND HAVING CLAUSES GROUP BY Clause: The GROUP BY clause is another section of the select statement .This optional clause tells Oracle to group rows based on distinct values that exist for specified columns The GROUP BY clause creates a data set, containing several sets of records grouped together based on a condition. Syntax: Select , aggregate _function() from where group by ,,; Having Clause: The HAVING clause can be used in conjunction with the GROUP BY clause . HAVING imposes a condition on the GROUP BY clause, which further filters the groups created by the GROUP BY clause. Each column specification specified in the HAVING clause must occur within a statistical function or must occur in the list of columns named in the GROUP BY clause Syntax: Select , aggregate _function() from where group by ,, having ; Example: SELECT COUNT(Id), Country FROM Customer GROUP BY Country HAVING COUNT(Id) > 10

Sorting Data In A Table. Oracle allows data from a table to be viewed in a sorted order. The rows retrieved from the table will be sorted in either ascending or descending order depending on the condition specified in the select sentence. Syntax: SELECT * FROM ORDER BY , <[SORTORDER]>; Example: select * from branch_mstr order by branch_no;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 18

Exercise-V

Queries on Controlling Data: Commit, Rollback, and Save point

Transaction Processing Using Commit ,Rollback and Savepoint Commit Save changes (transactional). Syntax: COMMIT [WORK] [COMMENT 'comment_text'] COMMIT [WORK] [FORCE 'force_text' [,int] ] FORCE - will manually commit an in-doubt distributed transaction force_text - transaction identifier (see the DBA_2PC_PENDING view) int - sets a specific SCN. If a network or machine failure prevents a distributed transaction from committing properly, Oracle will store any commit comment in the data dictionary along with the transaction ID. INPUT: SQL>commit; RESULT: Commit complete. Rollback Undo work done (transactional). Syntax: ROLLBACK [WORK] [TO [SAVEPOINT]'savepoint_text_identifier']; ROLLBACK [WORK] [FORCE 'force_text']; FORCE - will manually rollback an in-doubt distributed transaction INPUT: SQL>rollback; RESULT:Rollback complete. Savepoint Save changes to a point (transactional). Syntax: SAVEPOINT text_identifier Example: UPDATE employees SET salary = 95000 WHERE last_name = 'Smith'; SAVEPOINT justsmith; UPDATE employees SET salary = 1000000; SAVEPOINT everyone; SELECT SUM(salary) FROM employees;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 19

ROLLBACK TO SAVEPOINT justsmith; COMMIT; SQL> select * from emp1;

OUTPUT:- EID ENAME ESAL EBRANCH ------1 scotty 6000 a 2 wayne 10000 b 3 david 7000 c 4 max 8000 b 5 mark 7000 a 6 jeff 12000 a 7 matt 10000 b 8 steve 7000 c

8 rows selected

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 20

Exercise-VI Queries to Build Report in SQL *PLUS

The Steps in Report Writing 1. Formulate your query 2. Format the columns – 3.Add page headers/footers 4. Format the page 5. Print it 6. If more advanced: • Add page and line breaks • Add totals and subtotals Example: SELECT E.EMPLOYEE_NAME, P.PROJECT_NAME, SUM(PH.HOURS_LOGGED) , SUM(PH.DOLLARS_CHARGED) FROM EMPLOYEE E, PROJECT P, PROJECT_HOURS PH WHERE E.EMPLOYEE_ID = PH.EMPLOYEE_ID AND P.PROJECT_ID = PH.PROJECT_ID GROUP BY E.EMPLOYEE_ID, E.EMPLOYEE_NAME, P.PROJECT_ID, P.PROJECT_NAME;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 21

Exercise-VII Queries for Creating, Dropping, and Altering Tables, Views, and Constraints

A. Create Table Command: - it defines each column of the table uniquely. Each column has minimum of three attributes, a name , data type and size.

Rules For Creating Tables: 1. A name can have maximum upto 30 characters 2. Alphabets from A-Z,a-z and numbers from 0-9 are allowed 3. A name should begin with an alphabet 4. The use of the special character like _ is allowed and also recommended 5. SQL reserved words not allowed. For example : create,select, and so on.

Syntax: Create table

( (), )); Example: create table emp(empno number(4) primary key, ename char(10));

B. Types of data constraints. a) not null constraint at column level. Syntax:

(size) not null

b) unique constraint at column level Syntax:

(size) unique; c) unique constraint at table level: Syntax: Create table tablename(col=format,col=format,unique(,);

d) primary key constraint at column level Syntax:

(size)primary key;

e) primary key constraint at table level. Syntax: Create table tablename(col=format,col=format primary key(col1>,);

f) foreign key constraint at column level. Syntax:

(size>) references [];

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 22

g) foreign key constraint at table level Syntax: foreign key(

[,]) references [(,)

h) check constraint at column level. Syntax:

(size) check()

i) check constraint constraint at table level. Syntax: check(

Example: . Write a query to create branch_mstr described as below: Column name Data type Size Default Attributes

Branch_no Varchar2 10 Primary key

Name Varchar2 30

create table branch_mstr(branch_no varchar2(10) primary key,name varchar2(30)); B.Destroying tables: Some times tables within a particular database become obsolete and need to be discarded in such situation using the DROP TABLE statement with the table name can destroy a specific table

Syntax: Drop table ;

Example: drop table branch_mstr;

C. Modifying the structure of tables. The structure of a table can be modified by using the ALTER TABLE command . This command allows changing the structure of an existing table.With this command it is possible to add or delete columns, create or destroy indexes,change the data type of existing columns, or renme columns or table itself

a) Add new columns

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 23

Syntax: Alter table add(datatype(size));

Example: Alter table emp add(sal number(7,2));

b) Dropping a column from a table. Syntax: Alter table drop column

;

Example: Alter table emp drop column sal;

c) Modifying existing columns. Syntax: Alter table modify(

());

Example: Alter table emp modify(ename varchar2(15)); d) Renaming The Attributes We can rename the attributes in oracle

Syntax ALTER TABLE RENAME COLUMN OLD_COLUMN_NAME TO NEW_COLUMN_NAME;

Example ALTER TABLE CUST_TABLE RENAME COLUMN CUST_SEX TO CUST_GENDER;

D.Views I. Creating Views After a table is created and populated with data , it becomes necessary to prevent all users from accessing all columns of a table ,for data security reasons.. This would mean creating several tables having the appropriate number of columns and assigning specific users to each table, as required.This will Answer data security requirements very well but give rise to a great deal of redundant data being resident in tables, in the database.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 24

To reduce redundant data to the minimum possible, Oracle allows the creation of an object called a View Syntax: CREATE VIEW AS SELECT , FROM

;

Example: Create view cust_vw as select name, gender from cust_mstr;

II. Drop a view The DROP VIEW command is used to remove a view from the database Syntax: DROP VIEW < VIEWNAME> Example: DROP VIEW CUST_VW;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 25

Exercise-VIII Queries on Joins and Correlated Sub-Queries Simple joins( no INNER JOIN):

Combining tables to derive a new table is called a .Joins help us to derive a single table that contains all of the desired data.Using the WHERE clause we can join two tables

Inner-joins :

INNER JOIN takes two tables and a join specification describing how the two tables should be joined.The join specification may be specified as a condition.The condition follows the keyword ON. .In short, the INNER JOIN returns all rows from both the tables where there is a match.

Syntax:

SELECT ,, FROM INNER JOIN ON

,=, WHERE ORDER BY ,, Where

o ColumnName1 in TableName1 is usually that table’s Primary key o ColumnName2 in TableName2 is a foreign key in that table o ColumnName1 and ColumnName2 must have the same data type and for certain data types, the same size. NOTE:

It is common to join tables over attributes with the same name .Thus SQL provides a shorthand for this type of join.The USING clause lists those attributes common to both tables that must have the same value to be in the resultHere USING is identical to the equijoin..Note that INNER may be omitted. Because it is the default type of join. Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; Inner-recursive joins(joining to itself)

In some situations, we need to connect a table to itself..SQL handles this situation by allowing two copies of the same table to appear in the FROM clause.The only

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 26 requirement is that each copy of the table must be given a different alias to distinguish between the copies of the table.

Syntax:

SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition; Example: SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City FROM Customers A, Customers B WHERE A.CustomerID <> B.CustomerID AND A.City = B.City ORDER BY A.City; Outer joins:

Outer joins are similar to inner joins, but give a bit more flexibility when selecting data from related tables.This type of join can be used in situation where it is desired, to select all rows from the table on the left(or right, or both) regardless of whether the other table has values in common and usually enter NULL where data is missing.

Syntax:

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name; Example: SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; \

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 27

Exercise-IX

Queries on Working with Index, Sequence, Synonym, Controlling Access, and Locking Rows for Update, Creating Password and Security features A.Creating index The CREATE INDEX statement is used to create indexes in tables.Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just used to speed up searches/queries. Syntax Creates an index on a table. Duplicate values are allowed: CREATE INDEX index_name ON table_name (column1, column2, ...);

DROP INDEX The DROP INDEX statement is used to delete an index in a table. Syntax

DROP INDEX index_name;

B.Creating sequence Oracle provides an object called a sequence that can generate numeric values. The value generated can have a maximum of 38 digits .A sequence can be defined to:

o Generate numbers in ascending or descending order o Provide intervals between numbers o Caching of sequence numbers in memory to speed up their availability The minimum information required fro generating numbers using a sequence is :

o The starting number o The maximum number that can be generated by a sequence o The increment value for generating the next number This information is provided to Oracle at the time of the sequence creation

Syntax:

CREATE SEQUENCE [INCREMENT BY START WITH MAXVALUE / NOMAXVALUE MINVALUE / NOMINVALUE CYCLE / NOCYCLE CACHE / NOCACHE ORDER / NO ORDER]

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 28

Eg: create a sequence by the name ADDR_SEQ which will generate numbers from 1 upto 999 in ascending order with an interval of 1.The sequence must restart from the number 1 after generating the number 999

SQL>CREATE SEQUENCE ADDR_SEQ INCREMENT BY 1 START WITH 1 MINIMUM VALUE 1 MAXVALUE 999 CYCLE; C.Working with synonyms Aliasing Tables-Full/Partial Name Qualification

It becomes tiresome and error prone to prefix attributes with the full table name every time .Fortunately, SQL allows aliases for the table names.Using the AS clause we can give an alias name to an already existing table

For eg: ingredients AS i

Now ingredients and i refer to the same table.

D.Controlling access

Privilege Management Through The Grant And Revoke Commands

Granting privileges using the GRANT Statement:

Objects that are created by a user are owned and controlled by that user,If a user wishes to access any of the objects belonging to another user,the owner of the object will have to give permissions for such access.This is called Granting of privileges.

Syntax:

GRANT ON

TO [WITH GRANT OPTION];

The list of object privileges is as follows:

1. ALTER 2. DELETE 3. INDEX 4. INSERT 5. SELECT 6. UPDATE The WITH GRANT OPTION allows the grantee to in turn grant privileges to other users.

Revoking Privileges Given:

Privileges once given can be denied to a user using the REVOKE command. The object owner can revoke privileges granted to another user.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 29

A user of an object who is not the owner, but has been granted the GRANT privilege, has the power to REVOKE the privileges from a grantee

Syntax:

REVOKE ON

FROM

E. Locking Rows for Update In Oracle, adding a FOR UPDATE clause to a SELECT statement lets you lock the selected rows. Other users cannot lock or update those rows until you end your transaction. Things to know about row locking in Oracle: 1. SELECT…FOR UPDATE will not be able to lock rows if they are already locked by another transaction. By default, the session will wait for the locks to be released by the other transaction. 2. You can instruct Oracle to not wait for the locks to be released, by adding a NOWAIT to SELECT…FOR UPDATE. 3. To release the locked rows, a COMMIT or ROLLBACK must be issued in the session holding the lock. 4. SELECT…FOR UPDATE is restricted from use in with the DISTINCT operator, set operators, CURSOR expression, GROUP BY or aggregate functions. 5. Nested table rows are not locked when the parent table rows are locked. You must lock nested table rows explicitly if needed. 6. In a SQL with joins of multiple tables, if you want to lock rows from only a particular table, specify the OF … column clause to indicate which table to lock. Without this clause, Oracle locks the selected rows from all the tables in the join. 7. When selecting multiple rows for update, you can add the SKIP LOCKED clause to lock rows if not already locked by another transaction, else skip rows if they are already locked. [Note: Oracle recommends that you use the Oracle Streams Advanced Queuing APIsinstead of the SKIP LOCKED functionality.]

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 30

F. Creating Password and Security features

SQL>CONNECT SYSTEM/MANAGER; SQL>CREATE USER "USERNAME" IDENTIFIED BY "PASSWORD" SQL>GRANT DBA TO "USERNAME" SQL>CONNECT "USERNAME"/"PASSWORD"; EXAMPLE CREATING A USER SQL>CONNECT SYSTEM/MANAGER; SQL>CREATE USER CSE2 IDENTIFIED BY CSECSE; SQL>GRANT DBA TO CSE2; SQL>CONNECT CSE2/CSECSE; SQL>REVOKE DBA FROM CSE2;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 31

Exercise-X Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of Assignment Operation

INTRODUCTION TO PL/SQL As the name suggests, PL/SQL is a superset of SQL.PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements.PL/SQL bridges the gap between database technology and procedural programming languages.

ADVANTAGES OF PL/SQL 1. PL/SQL is development tool that not only supports SQL data manipulation but also provides facilities of conditional checking,branching and looping. 2. PL/SQL sends an entire block of SQL statements to the oracle engine all in one go. 3. PL/SQL also permits dealing with errors as required , and facilitates displaying user-friendly messages,when errors are encountered. 4.PL/SQL allows declaration and use of variables in blocks of code. 5.Applications written in PL/SQL are portable to any computer hardware and operating system, where oracle is operational.

THE GENERIC PL/SQL BLOCK Every programming environment allows the creation of structured,logical blocks of code that describe processes, which have to be applied to data. Once these blocks are passed to the environment ,the processes described are applied to data ,suitable data manipulation takes place, and useful output is obtained. A PL/SQL block has a definite structure , which can be divided into sections.The sections of a PL/S1QL block are: o The Declare section o The Master Begin and End section that also (optionally) contains an Exception section

PL/SQL BLOCK DECLARE --Declarations of memory variables,constants,cursors etc.,in PL/SQL BEGIN --SQL executable statements --PL/SQL executable statements EXCEPTION /*SQL or PL/SQL code to handle errors that may arise during the execution of the code block between BEGIN and EXCEPTION section END; The Declare Section

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 32

Code blocks start with a declaration section, in which, memory variables and other Oracle objects can be declared, and if required initialized. Once declared , they can be used in SQL statements for data manipulation. The Begin Section It consists of a set of SQL and PL/SQL statements, which describe processes that have to be applied to table of data.Actual data manipulation, retrieval,looping and branching constructs are specified in this section. The Exception Section This section deals with handling of errors that arise during execution of the data manipilation statements, which make up the PL/SQL code block.Errors can arise due to syntax, logic and/or validation rule violation. The End Section This marks the end of a PL/SQL block.

Creation of simple PL/SQL program which includes declaration section, executable section and exception –Handling section declare sno marks.sid%type; m1 marks.s1%type; m2 marks.s2%type; m3 marks.s3%type; p number(10,4); begin sno:='&sno'; select sid,cd,dc,dbms into sno,m1,m2,m3 from marks where sid=sno; p:=(m1+m2+m3)/3; if(p>70) then dbms_output.put_line('first class'); elsif( p>50 and p<60) then dbms_output.put_line('second class'); elsif(p>40 and p<50) then dbms_output.put_line('third class'); else dbms_output.put_line('fail'); end if; exception when no_data_found then dbms_output.put_line('student does not exists'); end; /

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 33

Output:

SQL> @ marks Enter value for sno: 66 old 8: sno:='&sno'; new 8: sno:='66'; first class PL/SQL procedure successfully completed.

SQL> @ marks Enter value for sno: 22 old 8: sno:='&sno'; new 8: sno:='22'; student does not exists

PL/SQL procedure successfully completed.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 34

Exercise-XI Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL

Referencing Bind Variables

You reference bind variables in PL/SQL by typing a colon (:) followed immediately by the name of the variable. For example

:ret_val := 1;

To change this bind variable in SQL*Plus, you must enter a PL/SQL block. For example

SQL> begin 2 :ret_val:=4; 3 end; 4 /

PL/SQL procedure successfully completed.

This command assigns a value to the bind variable named ret_val.

Displaying Bind Variables

To display the value of a bind variable in SQL*Plus, you use the SQL*Plus PRINT command. For example

SQL> print ret_val

RET_VAL ------4 Substitution Variables

Inserting rows into a table is a very tedious task. In real-life tables, we are talking about thousands of rows per table!

There are screen designers, form creators, and so on. An SQL statement does not have those fancy controls or buttons. The SQL language does have substitution variables, which enable you to create interactive

SQL> INSERT INTO dept (DeptId, DeptName, Location, EmployeeId) VALUES (&dept,_id,'&dept,_namef,'&location', &emp__.,id); Enter value for dept~_id: 70 Enter value for dept~_name: Testing Enter value for location: Miami

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 35

Enter value for emp__.,id: NULL

1 row created.

SQL script. When you execute the script, Oracle prompts you to enter a value for the substitution variable. 'Ihe ampersand (&) character is used before the substitution variable in the query. The substitution variables for character and date type columns are enclosed within a pair of single quotation marks. Figure 5-1 shows the use of substitution variables and the interactive prompts displayed by Oracle.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 36

Exercise-XII Write a PL/SQL block using SQL and Control Structures in PL/SQL a.FOR LOOP In Oracle, the FOR LOOP allows you to execute code repeatedly for a fixed number of times.

Syntax The syntax for the FOR Loop in Oracle/PLSQL is: FOR loop_counter IN [REVERSE] lowest_number..highest_number LOOP {...statements...} END LOOP; Where the parameters are loop_counter The loop counter variable. REVERSE Optional. If specified, the loop counter will count in reverse. lowest_number The starting value for loop_counter. highest_number The ending value for loop_counter. statements The statements of code to execute each pass through the loop.

c.In Oracle, we use a WHILE LOOP when we are not sure how many times we will execute the loop body and the loop body may not execute even once.

Syntax The syntax for the WHILE Loop in Oracle/PLSQL is:

WHILE condition LOOP {...statements...}

END LOOP;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 37

Where the Parameters or Arguments condition

The condition is test each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated. statements

The statements of code to execute each pass through the loop.

 The syntax for a nested FOR LOOP statement in PL/SQL is as follows:

FOR counter1 IN initial_value1 .. final_value1 LOOP sequence_of_statements1 FOR counter2 IN initial_value2 .. final_value2 LOOP sequence_of_statements2 END LOOP; END LOOP;  The syntax for a nested WHILE LOOP statement in Pascal is as follows:

WHILE condition1 LOOP sequence_of_statements1 WHILE condition2 LOOP sequence_of_statements2 END LOOP; END LOOP;

Program illustrating for loop declare i number(5); n number(2); s number(3); a number(5); begin n:=&n; s:=0;

for i in 1..n loop a:=&a; s:=s+a; end loop; dbms_output.put_line('sum is'||s); end;

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 38

/ output: SQL> @ sun Enter value for n: 3 old 7: n:=&n; new 7: n:=3; Enter value for a: 2 old 11: a:=&a; new 11: a:=2; sum is6

PL/SQL procedure successfully completed.

DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 39

Exercise-XIII Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types Cursors :. A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. There are two types of cursors in PL/SQL: Implicit cursors These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. Explicit cursors They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row. Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

A cursor must be opened before processing and closed after processing. (Similar to how files are opened and closed in a C program).

Syntax to define a cursor: CURSOR IS