Database CS-229T All - LABs
Database CS-229T All - LABs
Database CS-229T All - LABs
• By using truncate command data will be removed permanently & will not get back where
as by using delete command data will be removed temporally & get back by using roll back
command.
• By using delete command data will be removed based on the condition whereas by using
truncate command there is no condition.
• Truncate is a DDL command & delete is a DML command.
INSERT INTO: This is used to add records into a relation. These are three type of INSERT
INTO queries which are as UPDATE: This is used to update the content of a record in a relation.
DELETE-FROM: This is used to delete all the records of a relation but it will retain the structure
of that relation.
3. DATA RETRIEVAL LANGUAGE (DRL): Retrieves data from one or more tables.
SELECT FROM: To display all fields for all records. SELECT - FROM -WHERE: This query is
used to display a selected set of fields for a selected set of records of a relation. SELECT -
FROM -GROUP BY: This query is used to group to all the records in a relation together for each
and every value of a specific key(s) and then display them for a selected set of fields the relation.
SELECT - FROM -ORDER BY: This query is used to display a selected set of fields from a
relation in an ordered manner base on some field. JOIN using SELECT - FROM - ORDER BY:
This query is used to display a set of fields from two relations by matching a common field in
them in an ordered manner based on some fields.
JOIN using SELECT - FROM - GROUP BY: This query is used to display a set of fields from
two relations by matching a common field in them and also group the corresponding records for
each and every value of a specified key(s) while displaying. UNION: This query is used to
display the combined rows of two different queries, which are having the same structure, without
COMMIT: This command is used to end a transaction only with the help of the commit
command transaction changes can be made permanent to the database. SAVE POINT: Save
points are like marks to divide a very lengthy transaction to smaller once. They are used to
identify a point in a transaction to which we can latter role back. Thus, save point is used in
conjunction with roll back. ROLE BACK: A role back command is used to undo the current
transactions. We can roll back the entire transaction so that all changes made by SQL statements
are undo (or) role back a transaction to a save point so that the SQL statements after the save
point are roll back.
GRANT: The GRANT command allows granting various privileges to other users and allowing
them to perform operations with in their privileges REVOKE: To with draw the privileges that
has been GRANTED to a uses, we use the REVOKE command.
TASK:
Visit the below link for the Installation of Microsoft SQL Server 2008.
https://www.youtube.com/watch?v=4WEFTQ3VJNg
https://www.youtube.com/watch?v=WKWZZcrin5I
Syntax: Create table tablename (column_name1 data_ type constraints, column_name2 data_
type constraints ...) Example: Create table dept (deptno NUMBER (2), dname VARCHAR2
(14),loc VARCHAR2(13));
DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the
records in the table. Example: drop table prog20; here prog20 is table name
TRUNCATE: This command will remove the data permanently. But structure will not be
removed. Syntax: TRUNCATE TABLE <TABLE NAME>;
CONSTRAINTS:
In SQL, we have the following constraints:
Example:
Create table emp(empno NUMBER (4), ename VARCHAR2 (10), deptno NUMBER (7,2) NOT
NULL, constraint EMP_EMPNO_PK PRIMARY KEY (empno));
Create table emp (empno NUMBER(4), ename VARCHAR2 (10) NOT NULL,deptno NUMBER
(7,2) NOT NUL,........., CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
REFERENCES dept (deptno));
Create table emp (empno NUMBER(4), ename VARCHAR2 (10) NOT NULL,deptno NUMBER
(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 And 99));
TASKS:
DML commands:
1. INSERT Only one row is inserted at a line with this command, optionally list the columns in
the insert clauses. List values in the default order of the columns in the table.
Insert into emp(empno, ename, job, sal, comm, deptno) values (7890,'jinks','clerk',1.2e3,null,40);
2. UPDATE Using update command, we can modify each row in the table
If we don’t use the where condition, all the rows in the table will be updated.
Update emp set job = ‘manager', sal = sal +1000, deptno = 20 where ename=’JONES’;
If the WHERE condition is omitted, all rows in the table will be deleted.
TASK2:
SYNTAX Select < Column Names > From < Table Name >.
EXAMPLES The following statement selects rows from the employee table. Select * from emp;
The following statement selects the name, job, salary and department from Emp. Select ename,
job, sal, and deptno from emp; The following statement selects all records from Dept. Select *
from dept;
COLUMN ALIAS Provides a different name for the column expression and causes the alias to
be used in the column heading. The AS keyword is optional. The alias effectively renames the
select list item for the duration of the query.
Example: The following Example assigning a temporary column and rename it with Bonus.
Select empno, ename, job, sal, sal * 2 “ bonus “ from emp;
CONDITIONS If you ever want to find a particular item or group of items in your database, you
need one or more conditions. Conditions are contained in the WHERE clause. In the preceding
example, the condition is
Select from and where are the three most frequently used clauses in SQL. Where simply causes
your queries to be more selective. Without the WHERE clause, the most useful thing you could
do with a query is display all records in the selected table(s).
Examples:
The following statement selects rows from the employee table with the department number of
40.
The following statement selects rows from the employee table with the department number of
40.
Select empno, ename, job, sal from EMP where sal < 3000;
Operators are the elements you use inside an expression to articulate how you want specified
conditions to retrieve data.
There are 4 different classes of operators used in SQL, they are
ARITHMETIC OPERATORS These are the arithmetic operators available in SQL. You may
use arithmetic operators in any clause of a SQL statement except the FROM clause.
+ Add
- Subtract
* Multiply
/ Divide
Examples
COMPARISON OPERATORS
= Equal to
Examples
● Select empno, ename from emp where sal=800;
● Select empno, sal from emp where ename=’Smith’;
● Select * from emp where sal > 1500;
● Select empno, sal, hiredate from emp where sal >=1600;
● Select * from emp where sal < 1500;
● Select * from emp where sal <= 1600;
● Select * from emp where comm*3 < sal;
● Select empno, ename, hiredate from emp where ename =’ALLEN’;
● Select empno, sal, comm from emp where sal! = 1600;
● Select ename, sal, hiredate from emp where sal + comm >=1600;
● Select empno, ename from emp where comm < sal;
SQL OPERATORS There are four SQL operators that operate with all data types:
LOGICAL OPERATOR
AND If both component conditions return TRUE then the result is TRUE
Examples
ASSIGNMENTS
1. List all rows of the table emp.
2. List all rows of the dept.
3. List all employees’ number from emp.
4. List all employees name from emp.
5. List all departments’ number from emp.
6. Find all employees whose salaries are between 500 and 1500.
7. Find all employees whose salaries are between 1500 and 2500.
8. Find all employees whose salaries are between 2600 and 5000.
9. Find all employees whose salaries are less than 2000.
10. Find all employees whose salaries are greater than 2000.
One of the most powerful features of SQL is its capability to gather and manipulate data from
across several tables. Without this feature you would have to store all the data elements necessary
for each application in one table. Without common tables you would need to store the same data
in several tables. Imagine having to redesign, rebuild, and repopulate your tables and databases
every time your user needed a query with a new piece of information. The JOIN statement of SQL
enables you to design smaller, more specific tables that are easier to maintain than larger tables.
SQL JOIN (INNER JOIN) An SQL JOIN clause is used to combine rows from two or more
tables, based on a common field between them. The most common type of join is:
SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
Examples:
SQL LEFT JOIN Keyword :The LEFT JOIN keyword returns all rows from the left table
(table1), with the matching rows in the right table (table2). The result is NULL on the right side
when there is no match.
SQL RIGHT JOIN Keyword The RIGHT JOIN keyword returns all rows from the right table
(table2), with the matching rows in the left table (table1). The result is NULL in the left side
when there is no match.
SQL FULL OUTER JOIN Keyword The FULL OUTER JOIN keyword returns all rows
from the left table (table1) and from the right table (table2). The FULL OUTER JOIN
keyword combines the result of both LEFT and RIGHT joins.
TASKS:
Lab #06
Single Row Functions & Aggregating Data Using Group Function
ORDER BY CLAUSE
SYNTAX: Select column from table [Where condition] [Order by column] By default rows are
sorted by ascending order. By using the Order by clause, we can override this. Two options can
be used with the Order_By clause Ascending (Asc, if not mentioned results are sorted in
ascending order) Descending (desc, results are sorted, starting with the lowest value)
Examples
● Select ename, job, deptno, and hiredate from emp order by hire date desc;
● Select ename, deptno, and sal from emp order by deptno asc, sal desc;
CHARACTER FUNCTION
LOWER(col): Converts alpha character values to lowercase.
UPPER(col): Converts alpha character values to upper
CONCAT(col1,col2) Concatenates the first character value to the second
character value. Equivalent to concatenate operator(||)
SUBSTRING(col m[n]) Returns specified character from character value starting at character
position m,n character long. If m is negative, the count starts from the end of the character value.
LEN(col) Returns the number of character in value
CHARINDEX(‘alphabet’ , col): Searches an expression in a string expression and returns its
NUMBER FUNCTION
ROUND(column\ expression, n) Rounds the col expression or value to n decimal places. If n is
omitted no decimal place. If n is negative ,numbers to the left of the decimal point are rounded
POWER To raise one number to the power of another, use Power. In this function the first
argument is raised to the power of the second:
CEILING AND FLOOR Ceil returns the smallest integer greater than or equal to its argument.
Floor does just the reverse, returning the largest integer equal to or less than its argument.
CONVERSIONS SYNTAX:
DATEDIFF(datepart,startdate,enddate)
SELECT DATEDIFF(day,'1980-12-17','1982-01-23') AS DiffDate
SELECT GETDATE() AS CurrentDateTime
SELECT DATEPART(yyyy,hiredate) AS OrderYear,
DATEPART(mm,hiredate) AS OrderMonth,
DATEPART(dd,hiredate) AS OrderDay FROM emp
AGGREGATES FUNCTION
COUNT Counts the number of records
SUM Sum of definite column value
AVG Average of specified column value
MAX,MIN To find maximum and minimum values of a column
Examples
● Select COUNT (*) from employees;
● Select SUM (SALARY) from employees;
GROUP BY Aggregate functions are normally used in conjunction with a GROUP BY clause.
The GROUP BY clause enables you to use aggregate functions to answer more complex
managerial questions such as:
Group by function establishes data groups based on columns and aggregates the information
within a group only. The grouping criterion is defined by the columns specified in GROUP BY
clause. Following this hierarchy, data is first organized in the groups and then WHERE clause
restricts the rows in each group.
Examples
SELECT deptno, job, SUM(Salary) as total_salary FROM emp GROUP BY deptno, Job;
TASKS
1. Group the employees by their salaries.
2. List hiredates in descending order.
3. List hiredates in ascending order
4. List all employees and add 20 rupees in each salary.
5. List all 'manager' and add 100 rupees in each salary.
6. List all 'salesman and add 500 rupees in each salary.
7. List all 'clerk' and add 50 rupees in each salary.
8. Find eight percent of salesmen salary.
9. Find the annual salary of each employee.
10. Find the six-month salary of each employee.
11. Find the two-month salary of each manager.
12. Make a query in which all the arithmetic expressions will include all the result
will be remain same.
13. Find the daily wages of each employee.
TASK :
SUBQUERIES
Main Query
“Which employees have a salary greater than Jones’ Salary?”
Sub-query
“What is Jones’ salary?”
Sub-query
A sub-query is a SELECT statement that is embedded in a clause of another SELECT statement.
They can be very useful when we need to select rows from a table with a condition that depends
on the data in the table itself. The sub-query generally executes first and its output is used to
complete the query condition for the main or outer query.
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
Note: In the syntax, operator means comparison operator. Comparison operators fall into two
For example, to display the names of all employees who earn more than
employee with empno 7566.
SELECT ename FROM emp WHERE sal > (SELECT sal FROM emp WHERE empno = 7566);
Single-row subquery: Query that returns only one row from the inner SELECT statement.
Multiple-row subquery: Query that returns more than one row form the inner SELECT
statement.
Single-Row SubQuery
Examples
1. To display the employees whose job title is the same as that of employee 7369
SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE empno =
7369);
SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE empno =
7369) AND sal > (SELECT sal FROM emp WHERE empno = 7876);
3. To display the employee name, job title and salary of all employees
whose salary is equal to the minimum salary.
SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp);
Multiple-Row
Subqueries
Operator Meaning
Note: The NOT operator can be used with IN, ANY, and ALL operators.
Examples
1. Find the employees who earn the same salary as the minimum salary for departments.
SELECT ename, sal, deptno FROM emp WHERE sal IN (SELECT MIN(sal) FROM emp GROUP
BY deptno);
2. To display employees whose salary is less than any clerk and who are not
clerks.
SELECT empno, ename, job FROM emp WHERE sal < ANY (SELECT sal FROM emp WHERE
job = ‘CLERK’);
SELECT empno, ename, job FROM emp WHERE sal > ALL (SELECT avg(sal) FROM emp
GROUP BY deptno);
If we want to compare two or more columns, we must write a compound WHERE clause using
logical operators. Multiple column subqueries enable us to combine duplicate WHERE
conditions into a single WHERE clause.
For example, to display the name of all employees who have done their present
SELECT ENAME FROM EMP WHERE (EMPNO, JOB) IN (SELECT EMPNO, JOB FROM
JOB_HISTORY);
COMPOUND QUERIES
In SQL, we can use the normal set operators of Union, Intersection and
Set Difference to combine the results of two or more component queries
into a single result table. Queries containing SET operators are called
compound queries. The following table shows the different set operators
provided in Oracle SQL.
Operator Returns
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
SELECT statement and that are not selected in the
second SELECT statement
There are restrictions on the tables that can be combined using the set operations, the most
important one being that the two tables have to be union-compatible; that is, they have the same
structure. This implies that the two tables must contain the same number of columns, and that their
corresponding columns contain the same data types and lengths. It is the user’s responsibility to
ensure that values in corresponding columns come from the same domain. For example, it would
not be sensible to combine a column containing the age of staff with the number of rooms in a
property, even though both columns may have the same data type i.e. NUMBER.
The UNION Operator
The UNION operator returns rows from both queries after eliminating duplicates. By default, the
output is sorted in ascending order of the first column of the SELECT clause.
For example to display all the jobs that each employee has performed, the following query will be
given. (NOTE: If an employee has performed a job multiple times, it will be shown only once)
SELECT EMPNO, JOB FROM JOB_HISTORY UNION
TASK:
1. Write a query to display the employee name and hiredate for all employees in the same
department as Blake. Exclude Blake.
2. Create a query to display the employee number and name for all employees who earn more
than the average salary.
3. Write a query to display the employee number and name for all employees who work in a
department with any employee whose name contains a T.
4. Display the employee name, department number, and job title for all employees whose
department location is Dallas.
5. Display the employee name and salary of all employees who report to King.
6. Write a query to display the employee name, salary, deptno and job for all employees in
the same job as empno 7369.
7. Display the employee number, name and salary for all employees who earn more than
the average salary and who work in department with any employee with a T in their name.
Lab #09
Retrieving Data from Multiple Tables, Mapping of shared data SQL:
Cartesian product.
A Cartesian Product results when all rows in the first table are joined to all rows in the
second table. A Cartesian product is formed under following conditions:-
i. When a join condition is omitted
ii. When a join condition is invalid
In the above example, if EMP table has 14 rows and DEPT table has 4 rows, then their
Cartesian product would generate 14 x 4 = 56 rows.
In fact, the ISO standard provides a special format of the SELECT statement for the
Cartesian product:-
A Cartesian product tends to generate a large number of rows and its result is rarely
useful. It is always necessary to include a valid join condition in a WHERE clause.
Hence a join is always a subset of a Cartesian product.
Types of Joins
There are various forms of join operation, each with subtle differences, some more useful
than others. The Oracle 9i database offers join syntax that is SQL 1999 compliant. Prior
to release 9i, the join syntax was different from the ANSI standard. However, the new
syntax does not offer any performance benefits over the Oracle proprietary join syntax
that existed in prior releases.
Inner-Join/Equi-Join
If the join contains an equality condition, it is called equi-join.
Examples
To retrieve the employee name, their job and department name, we need to extract data from
two tables, EMP and DEPT. This type of join is called equijoin-that is, values in the DEPTNO
column on both tables must be equal. Equijoin is also called simple join or inner join.
The SQL-1999 standard provides the following alternative ways to specify this join:-
SELECT ENAME, JOB, DNAME
FROM EMP NATURAL JOIN DEPT;
Outer-Join
A join between two tables that returns the results of the inner join as well as unmatched
rows in the left or right tables is a left or right outer join respectively. A full outer join is
a join between two tables that returns the results of a left and right join.
NOTE: The outer join operator appears on only that side that has information missing.
The SQL-1999 standard provides the following alternative way to specify this join:-
The SQL-1999 standard provides the following alternative way to specify this join:-
SELECT E.ENAME, D.DEPTNO, D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO);
NOTE: In the equi-join condition of EMP and DEPT tables, department OPERATIONS
does not appear because no one works in that department. In the outer join condition,
the OPERATIONS department also appears.
Non-Equijoin
If the join contains inequality condition, it is called non-equijoin. E.g. to retrieve
employee name, salary and their grades using non-equijoins, we need to extract data
from two tables, EMP and SALGRADE.
TASK:
• To display the employee name, department name, and location of all employees who earn a
commission.
• To display all the employee’s name (including KING who has no manager) and their
manager name
• Create a unique listing of all jobs that in department 30. Include the location of department
30 in the Output.
• Write a query to display the name, job, department number and department name for all
employees who work in New York
• Display the employee name and employee number along with their manager’s name
Manager Number. Label the columns Employee, Emp#, Manager, and Manager#,
respectively.
LAB # 10
CREATING SEQUENCES AND INDEXES
SEQUENCE
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database
systems to produce unique values on demand.
● A sequence is a user defined schema bound object that generates a sequence of numeric
values.
● Sequences are frequently used in many databases because many applications require each
row in a table to contain a unique value and sequences provides an easy way to generate
them.
● The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
● One can select the NEXTVAL and CURRVAL from a sequence. Selecting the NEXTVAL
will automatically increment the sequence.
Syntax:
CREATE SEQUENCE sequence_name
CYCLE| NOCYCLE ;
Output:
ID NAME
1 ali
2 salman
The following table illustrates the main differences between sequences and identity columns:
You use a sequence object instead of an identity column in the following cases:
● The application requires a number before inserting values into the table.
● The application requires sharing a sequence of numbers across multiple tables or multiple
columns within the same table.
● The application requires to restart the number when a specified value is reached.
● The application requires multiple numbers to be assigned at the same time. Note that you
can call the stored procedure sp_sequence_get_range to retrieve several numbers in a
sequence at once.
● The application needs to change the specification of the sequence like maximum value.
An index is a schema object that can speed up the retrieval of rows by using a pointer. Indexes
can be created explicitly or automatically. An index provides direct and fast access to rows in a
table. Its purpose is to reduce the necessity of disk I/O by using an indexed path to locate data
quickly. The index is used and maintained automatically by the Oracle Server. Once an index is
created, no direct activity is required by the user.
Indexes are logically and physically independent of the table they index. Therefore, they can be
created or dropped at any time and have no effect on the base tables or other indexes.
Types of indexes
Oracle maintains the indexes automatically: when new rows are added to the table, updated, or
deleted, Oracle updates the corresponding indexes. We can create the following indexes:-
Bitmap index
A bitmap index does not repeatedly store the index column values. Each value is treated as a key,
and for the corresponding ROWIDs a bit is set. Bitmap indexes are suitable for columns with low
cardinality, such as the GENDER column in the EMP table, where the possible values are M or F.
The cardinality is the number of distinct column values in a column. In the EMP table column, the
cardinality of the GENDER column is 2.
B-tree index
This is the default. The index is created using the b-tree algorithm. The b-tree includes nodes with
the index column values and the ROWID of the row. The ROWIDs are used to identify the rows
in the table.
The following are the types of b-tree indexes:-
▪ Unique Index: The Oracle server automatically creates this index when a column in a
table is defined to be a PRIMARY KEY or UNIQUE key contraint.
▪ NonUnique Index: Users can create nonunique indexes on columns to speed up access
time to the rows. For example, we can create a FOREIGN KEY column index for a
join in a query to improve retrieval speed.
▪ Function-based index: The function-based index can be created on columns with
expressions. For example, creating an index on the SUBSTR(EMPID, 1, 2) can speed
up the queries using the SUBSTR(EMPID, 1, 2) in the WHERE clause.
Creating an Index
To create an index (b-tree) on first 5 characters of JOB column in the EMP table.
To create a bitmap index, we must specify the keyword BITMAP immediately after CREATE.
Bitmap indexes cannot be unique. For example:
Confirming Indexes
We can confirm the existence of indexes from the USER_INDEXES data dictionary view. It
contains the name of the index and its uniqueness.
SELECT INDEX_NAME, TABLE_NAME, TABLE_OWNER, UNIQUENESS FROM
USER_INDEXES;
Removing an Index
It is not possible to modify an index. To change it, we must drop it first and then re-create it.
Remove an index definition from the data dictionary by issuing the DROP INDEX statement. To
drop an index, one must be the owner of the index or have the DROP ANY INDEX privilege.
For example, remove the EMP_ENAME_IDX index from the data dictionary.
DROP INDEX emp_ename_idx;
Tables can be created at any time, even while users are using the database.
We do not need to specify the size of any table. The size is ultimately defined by the
amount of space allocated to the database as a whole.
Table structure can be modified online.
Naming Conventions
▪ Name database tables and columns according to the standard rules for naming
any database object.
▪ Table names and column names must begin with a letter and can be 1-30
characters long.
▪ Names must contain only the characters A-Z, a-z, 0-9, _(underscore), $, and
# (legal characters, but their use is discouraged).
▪ Names must not duplicate the name of another object owned by the same
Server user.
▪ Names must not be a Server reserved word.
For example,
… hiredate DATE DEFAULT SYSDATE, …
Example
The following example creates the DEPT table mentioned in the lab. session 01.
Since creating a table is a DDL statement, an automatic commit takes place when this
statement is executed.
SQL Data Types
Datatype Description
VARCHAR2(size) Variable-length character data (A maximum size must be
specified.
Default and minimum size is 1; maximum size is 4000)
CHAR(size) Fixed-length character data of length size bytes (Default and
minimum
size is 1; maximum size is 2000)
NUMBER(p, s) Number having precision p and scale s (The precision is the total
number of decimal digits and the scale is the number of digits to
the right of the decimal point. The precision can range from 1 to 38
and the
scale can range from -84 to 127.)
DATE Date and time values between January 1, 4712 B.C. and
December 31, 9999 A.D.
LONG Variable length character data up to 2 gigabytes
CLOB, BLOB and BFILE are the large object data types and can store blocks of
unstructured data (such as text, graphics images, video clips and sound wave forms up to
4 gigabytes in size.) LOBs also support random access to data.
Dropping a Table
The DROP TABLE statement removes the definition of an Oracle table. The database
loses all the data in the table and all the indexes associated with it.
The DROP TABLE statement, once executed, is irreversible. The Oracle Server does not
question the action when the statement is issued and the table is immediately dropped. All
DDL statements issue a commit, therefore, making the transaction permanent.
To drop the table DEPT30,
DROP TABLE DEPT30;
Constraint Description
NOT NULL Specifies that this column may not contain a null value
UNIQUE Specifies a column or combination of columns whose values must be
unique for all rows in the table
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes and enforces a foreign key relationship between the
column
and a column of the referenced table
CHECK Specifies a condition that must be true
What is a View?
A view is a logical table based on other tables or another view. A view contains no data of its own
but is like a window through which data from tables can be viewed or changed. The tables in which
a view is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
The following SQL creates a view that shows all customers from Brazil:
TASKS
EMPLOYEE
Empno (eg 6712) Name
Designation (e.g. Database Developer) Qualification
Joindate PROJECT PID (eg P812)
Title Client
Duration (in weeks)
Status (New, In Progress, Complete) EMP_PROJECT
Empno PID
Performance (Excellent, Good, Fair, Bad, Poor)
GRADE
Designation Grade (1-20) TotalPosts
PostsAvailable (<= TotalPosts)
TRAINING
Tcode (eg T902) Title
StartDate EndDate
EMP_TRAINING
Sir Syed University of Engineering and Technology 11 | P a g e
(Department of Computer Science and Information Technology)
Empno Tcode
Attendance (%)
1. Develop a script file EMPLOYEE.SQL to create tables for the above schema. Implement all
necessary integrity constraints including primary and foreign keys. (NOTE: All check constraints
should be at table level)
Controlling database access and resource limits are important aspects of the DBA’s function. Profiles
are used to manage the database and system resources and to manage database passwords and
password verification. Database access is controlled using privileges.
Roles are created to manage the privileges.
PROFILES
In Oracle, a profile is a named set of password and resource limits. In essence, they are
used for two major purposes:-
i. Profiles are used to control the database and system resource usage. They restrict users from
performing some operations that require heavy use of resources. Resource management limits can
be enforced at the session level, the call level or both. Oracle provides a set of predefined
resource parameters that can be used to monitor and control database resource usage. The DBA
can define limits for each resource by using a database profile.
ii. Profiles are also used for password management to provide greater control over database
security. e.g. to force a user to change password after a specified time.
It is possible to create various profiles for different user communities and assign a profile
to each user. When the database is created, Oracle creates a profile named DEFAULT, and
if we do not specify a profile for the user, the DEFAULT profile is assigned.
Oracle lets us control the following types of resource usage (both at session level and call
level) through profiles:-
▪ Concurrent sessions per user
▪ Elapsed and idle time connected to the database
▪ CPU time used (per session and per call)
▪ Logical reads performed (per session and per call)
Oracle lets us control the following password management features through profiles:-
▪ Password aging and expiration
▪ Password history
▪ Password complexity verification
▪ Account Locking
ALTER SYSTEM
SET RESOURCE_LIMIT = TRUE;
Most resource limits are set at the session level; a session is created when a user connects
to the database. Certain limits can be controlled at the statement level (but not at the
transaction level).
If a user exceeds a resource limit, Oracle aborts the current operation, rolls back the
changes made by the statement, and returns an error. The user has the option of
committing or rolling back the transaction, because the statements issued earlier in the
transaction are not aborted. No other operation is permitted when a session level limit is
reached. The user can disconnect, in which case the transaction is committed. In contrast to
resource limits, password limits are always enforced.
Some of the parameters that are used to control resources are as follows:-
▪ SESSIONS_PER_USER
▪ CPU_PER_SESSION
▪ CPU_PER_CALL
▪ LOGICAL_READS_PER_SESSION
▪ LOGICAL_READS_PER_CALL
▪ CONNECT_TIME
▪ IDLE_TIME
Some of the parameters that are used for password management are as follows:-
▪ FAILED_LOGIN_ATTEMPTS
▪ PASSWORD_LOCK_TIME
▪ PASSWORD_LIFE_TIME
▪ PASSWORD_GRACE_TIME
▪ PASSWORD_REUSE_TIME
▪ PASSWORD_REUSE_MAX
Creating Profiles
Let’s create a profile to manage passwords and resources for the accounting department
users. The users are required to change their password every 60 days and they cannot reuse
a given password for 90 days. However a given password can be reused any number of
times throughout life. The grace period for password change is 5 days. They are allowed to
IDLE_TIME 30
FAILED_LOGIN_ATTEMPTS 4
PASSWORD_LOCK_TIME UNLIMITED
PASSWORD_LIFE_TIME 60
PASSWORD_GRACE_TIME 5
PASSWORD_REUSE_TIME 90
PASSWORD_REUSE_MAX UNLIMITED;
Dropping profiles
Profiles are dropped using the DROP PROFILE command. If any user is assigned the
profile you wish to drop, Oracle returns an error. You can drop such profiles by
specifying CASCADE, in which case the users who have that profile will be assigned the
DEFAULT profile.
DROP PROFILE ACCOUNTING_USER CASCADE;
Assigning Profiles
Profiles can be assigned to users by using the CREATE USER or ALTER USER
command. Following example assigns the ACCOUNTING_USER profile to an existing
user named SCOTT:-
ALTER USER SCOTT
PROFILE ACCOUNTING_USER;
Querying Password and Resource Limits Information
Information about password and resource limits can be obtained by querying the
following data dictionary views:-
▪ DBA_USERS
▪ DBA_PROFILES
The database’s data is stored logically in tablespaces and physically in the data files
corresponding to the tablespaces. The logical storage management is independent of the
physical storage of the data files. A tablespace can have more than one data file associated
with it whereas one data file belongs to only one tablespace.
A database can have one or more tablespaces.
Figure 10.2 below shows the relationship between the database, tablespace, data files and
Any object (such as a table, an index, etc.) created in the database is stored in a single
table space. But the object’s physical storage can be on multiple data files belonging to
that table space.
The idea of table spaces allows managing space for users in an efficient way. We can
group application-related data (e.g. accounts) together so that when maintenance is
required for the application’s table space, only that table space need to be taken offline
and the rest of the database will be available for other users. Moreover, we can back up
the database one table space at a time as well as make part of the database read-only.
The size of the table space is the total size of all the data files belonging to the table space.
The size of the database is the total size of all table spaces in the database, which is the total
size of all data files in the database.
Changing the size of the data files belonging to a table space can change the size of that
table space. More space can be added to a table space by adding more data files to the
table space or increasing the size of the existing data files.
Database
Data file 1
Datafile 2 Data file 3
A Database can have multiple table spaces and a table space can have multiple data files
AUTOEXTEND ON enables the automatic extension of the data file. NEXT specifies the
disk space to allocate to the data file when more space is needed. MAXSIZE specifies the
maximum disk space allowed for allocation to the data file. If MAXSIZE is specified
unlimited then this indicates that there is no limit on allocating disk space to the data file.
Altering Table space
We can add more space to a table space by adding more data files to it or by changing the
size of the existing data files.
We can increase or decrease the size of a data file by using the RESIZE clause of the ALTER
DATABASE DATAFILE command.
ALTER DATABASE
DATAFILE ‘d:\oradata\db01\appl_data01.dbf’
RESIZE 200M;
MANAGING USERS
The following statement will create a user AHMED identified by password GREEN,
having profile ACCOUNTING_USER. All the user’s objects will be created in the
USERS table space in which the user AHMED will have a quota of 2MB. The user’s
account will be initially locked.
Object privileges are granted on a specific object. The owner of the object has all the
privileges on the object. The privileges can be on data (to read, modify, delete, add, or
reference), on a program (to execute), or to modify an object (to change the structure).
System privileges are the privileges that enable the user to perform an action on any
schema in the database. They do not specify an object, but are granted at the database
level. Like object privileges, system privileges also can be granted to a user. They are
usually granted by DBA. Both system privileges and object privileges can be granted to a
role.
PUBLIC is a user group defined in the database; it is not a database user or a role. Every
user in the database belongs to this group. So if privileges are granted to PUBLIC, they
are available to all users of the database.
Granting Object Privileges
Suppose user AHMED owns tables CUSTOMER (Customer_ID, Name, Address) and
ORDER (Order_ID, Date, Customer_ID). AHMED wants to grant read and update
privileges on CUSTOMER table to user YASIR. When multiple privileges are specified,
they are separated by comma.
The WITH GRANT OPTION clause allows YASIR to grant the privileges to others.
Granting System Privileges
Like object privileges, system privileges also can be granted to a user, role, or PUBLIC.
There are many system privileges in Oracle. The CREATE, ALTER, and DROP privileges
provide the ability to create, modify, and drop the object specified in the user’s schema.
When a privilege is specified with ANY, it authorizes the user to perform the action on any
schema in the database.
For example, to grant create session, create table and create index privilege to
AHMED:- GRANT CREATE SESSION, CREATE TABLE,
The following statement allows AHMED to create and select a table in any schema as
well as selecting any sequence,
GRANT CREATE ANY TABLE, SELECT ANY
TABLE, SELECT ANY SEQUENCE TO AHMED;
Revoking privileges
Object privileges and system privileges can be revoked from a user by using the
REVOKE statement. To revoke the UPDATE privilege granted to YASIR from AHMED
on AHMED’s CUSTOMER table:-
REVOKE UPDATE
ON CUSTOMER
FROM YASIR;
ROLES
A role is a named group of related privileges that can be granted to the user. This
method makes it easier to revoke and maintain privileges.
A user can have access to several roles and several users can be assigned the same role.
Roles are typically created for a database application.
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just
call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the
parameter value(s) that is passed.
EXEC procedure_name;
The following SQL statement creates a stored procedure named "SelectAllCustomers" that selects all records from
the "Customers" table:
EXEC SelectAllCustomers;
The following SQL statement creates a stored procedure that selects Customers from a particular City from the
"Customers" table:
Setting up multiple parameters is very easy. Just list each parameter and the data type separated by a comma as
shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular City with a
particular PostalCode from the "Customers" table:
Theory:
A transaction is a logical unit of work. All changes made to the database can be referred to as a transaction.
Transaction changes can be made permanent to the database only if they are committed a transaction begins with an
executable SQL statement & ends explicitly with either rollback or commit statement.
COMMIT: This command is used to end a transaction only with the help of the commit command transaction
changes can be made permanent to the database.
Syntax: SQL> COMMIT;
Example: SQL> COMMIT;
SAVE POINT:
Save points are like marks to divide a very lengthy transaction to smaller once. They are used to identify a point in
a transaction to which we can latter role back. Thus, save point is used in conjunction with role back.
Syntax: SQL> SAVE POINT ID;
Example: SQL> SAVE POINT xy
ROLLBACK:
A role back command is used to undo the current transactions. We can role back the entire transaction so that all
changes made by SQL statements are undo (or) role 38 back a transaction to a save point so that the SQL
statements after the save point are role back.
Syntax: ROLLBACK (current transaction can be role back) ROLLBACK to save point ID;
Example: SQL> ROLLBACK; SQL> ROLLBACK TO SAVE POINT xyz;
TASK:
1. Write a query to implement the save point.
2. Write a query to implement the rollback.
3. Write a query to implement the commit.
Open Discussion