You are on page 1of 61

DDL and DML commands

Practical No: Date:

Aim: Study of DDL-create and DML-insert commands.

Theory

What is Data Base Management system?


A database can be defined as a collection of coherent, meaningful data.
Data is one of the most important assets of a company. It is very important to make sure data
is stored and maintained accurately and quickly. DBMS (Database Management System) is a
system that is used to store and manage data.
A DBMS is a set of programs that is used to store and manipulation data. Manipulation of data
includes the following:
• Adding new data, for example adding details of new student.
• Deleting unwanted data, for example deleting the details of students who have
completed course.
• Changing existing data, for example modifying the fee paid by the student.
A DBMS provides various functions like data security, data integrity, data sharing, data
concurrence, data independence, data recovery etc. However, all database management
systems that are now available in the market like Sybase, Oracle, and MS-Access do not
provide the same set of functions, though all are meant for data management.
Database managements systems like Oracle, DB2 are more powerful and meant for bigger
companies. Whereas, database management systems like MS-Access are meant for small
companies. So one has to choose the DBMS depending upon the requirement.

What is Relational DBMS (RDBMS)?


A RDBMS is a database management system that is based on the relational model as
introduced by Dr.Edger.F.Codd.(Dr.E.F.Codd). A RDBMS stores the data in the form of
related tables. A table is a two dimensional array containing rows and columns. Each row
contains data related to an entity such as a student. Each column contains the data related to a
single attribute of the entity such as student name.
Popular commercial RDBMS for large databases include Oracle, Microsoft SQL Server,
Sybase, SQL Server, IBM’s DB2, MySQL,PostgreSQL.
Figure 1 shows how data is represented in relational model and what are the terms used to refer
to various components of a table. The following are the terms used in relational model.
Tuple / Row: A single row in the table is called as tuple. Each row represents the data of asingle
entity.
Attribute / Column: A column stores an attribute of the entity. For example, if details of
students are stored then student name is an attribute; course is another attribute and so on.
Column Name: Each column in the table is given a name. This name is used to refer to value
in thecolumn.
Fig 1: A table in Relational Model.
DR.E.F. CODD 12 Rules:
Dr.E.F.Codd is an IBM researcher who first developed the relational data model in 1970. In
1985, Dr.E.F.Codd published a list of 12 rules that define an ideal relational database and has
provided a guideline for the design of all relational database system.
Rule 1. Information Rule: All information in the database should be represented in one and
only one way - as values in a table.
Rule 2. Guaranteed Access Rule: Each and every datum (atomic value) is guaranteed to be
logically accessible by resorting to a combination of table name, primary key value
and column name.
Rule 3. Systematic Treatment of Null Values: Null values (distinct from empty character
string or a string of blank characters and distinct from zero or any other number)
are supported in the fully relational DBMS for representing missing information in
a systematic way, independent of data type.
Rule 4. Dynamic On-line Catalog Based on the Relational Model: The database description
is represented at the logical level in the same way as ordinary data, so authorized
users can apply the same relational language to its interrogation as they apply to
regular data.
Rule 5. Comprehensive Data Sublanguage Rule: A relational system may support several
languages and various modes of terminal use. However, there must be at least one
language whose statements are expressible, per some well-defined syntax, as
character strings and whose ability to support all of the following is
comprehensible:
• data definition
• view definition
• data manipulation (interactive and by program)
• integrity constraints
• authorization
• Transaction boundaries (begin, commit, and rollback).
Rule 6. View Updating Rule: All views that are theoretically updateable are also updateable
by the system.
Rule 7. High-level Insert, Update, and Delete: The capability neither of handling a base
relation or a derived relation as a single operand applies nor only to the retrieval of
data but also to the insertion, update, and deletion of data.
Rule 8. Physical Data Independence: Application programs and terminal activities remain
logically unimpaired whenever any changes are made in either storage
representation or access methods.

3130703 DBMS
Rule 9. Logical Data Independence: how data is viewed should not be changed when the
logical structure (Table’s Structure) of database changes. this rule is particularly
difficult to satisfy. Or Application programs and terminal activities remain logically
unimpaired when information preserving changes of any kind that theoretically
permit impairment are made to the base tables.
Rule 10. Integrity Independence: Integrity constraints specific to a particular relational
database must be definable in the relational data sublanguage and storable in the
catalog, not in the application programs.
Rule 11. Distribution Independence: The data manipulation sublanguage of a relational
DBMS must enable application programs and terminal activities to remain logically
unimpaired whether and whenever data are physically centralized or distributed.
Rule 12. Non subversion Rule: If a relational system has or supports a low-level (single-
record-at-a-time) language, that low-level language cannot be used to subvert or
bypass the integrity rules or constraints expressed in the higher-level (multiple-
records-at-a-time) relational language.
Table 1: Comparison of DBMS v/s RDBMS
DBMS RDBMS
In DBMS relationship between two tables In RDBMS relationship between two tables
or files are maintained programmatically. or files can be specified at the time of table
creation
DBMS does not support client/server Most of RDBMS support client/server
architecture. architecture.
DBMS does not support Distributed Most of RDBMS support Distributed
Database. Database.
In DBMS there is no security of Data. In RDBMS there are multiple levels of
Security. Logging in at OS level, Command
level, Object level.
DBMS may satisfy less than 7 or 8 rules of RDBMS may satisfy more than 7 or 8 rules
Dr.E.F.Codd. of Dr.E.F.Codd.
It support single user only It supports multiple user.
FoxPro, IMS are Examples SQL-Server, Oracle are examples
Introduction to SQL
SQL is a language that provides an interface to relational database systems. The language
developed by IBM in 1970 to manipulate the data stores within codd’s model was originally
called structured English Query Language (SEQUEL) with the word English later begin
dropped in favourStructured Query Language (SQL).

In almost all relational databases, data is accessed through SQL. SQL allows you to
SELECT your data, INSERT new records, UPDATE existing records and DELETE records
you want to get rid of. SQL can be embedded in other languages or you can run scripts of SQL
directly against the database.
Features of SQL:
• SQL can be used by a range of users, including those with little or no programming
experience.
• It is a non-procedural language.
• It reduces the amount of time required for creating and maintaining systems.
• It is English like language.
Features of SQL * PLUS:
• SQL *PLUS is an oracle tool that recognizes and submit statement to oracle server for
execution.
• It accepts ad hoc entry of statements.
• It accepts SQL input from files.
• It provides line editor for modifying SQL statement.
• It controls environment settings.
• It formats query results into basic reports.
• It accesses local and remote databases.
Table 2: Comparison of SQL v/s SQL*PLUS
SQL SQL * PLUS
It is a language for communicating with the It recognizes SQL statement and send them to
oracle server to access data. the server.
It is based on American National standards It is the oracle proprietary interface for
Institute (ANSI) standard SQL. executing SQL statements.
SQL manipulate data and table definition in It does not allow manipulation of values in the
the database. database.
SQL is entered into SQL buffer on one or SQL * PLUS is entered one line at a time, not
more lines stored in SQL buffer.
SQL does not have a continuation character. SQL * PLUS uses a dash (-) as a continuation
character if the command is longer than one
line.
SQL uses a termination character to execute It does not require termination characters;
commands immediately. executing commands immediately.

SQL Data Type


• VARCHAR2 (size): Variable-length character data (A maximum size must be
specified: minimum size is 1; maximum size is 4,000.)
• CHAR [(size)]: Fixed-length character data of length size bytes (Default and minimum
size is 1; maximum size is 2,000.)
• 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 to the nearest second between January 1, 4712 B.C., and
December 31, 9999 A.D.
• LONG: Variable-length character data (up to 2 GB)
• CLOB: Character data (up to 4 GB)
• RAW (size): Raw binary data of length size (A maximum size must be specified:
maximum size is 2,000.)
• LONG RAW: Raw binary data of variable length (up to 2 GB)
• BLOB: Binary data (up to 4 GB)
• BFILE: Binary data stored in an external file (up to 4 GB)
• ROWID: A base-64 number system representing the unique address of a row in its
table

Components of SQL
• DDL (Data Definition Language): CREATE, ALTER, DROP, TRUNCATE,
COMMENT, GRANT, REVOKE
• DML (Data Manipulation Language): INSERT, UPDATE, DELETE, CALL,
EXPLAIN PLAN, LOCK
• DCL (Data Control Language): COMMIT, SAVEPOINT, ROLLBACK, SET
TRANSACTION, GRANT/REVOKE
• DQL (Data Query Language): SELECT
DDL: it is a set of SQL commands used to create, modify and delete database structure but not
data.

3130703 DBMS
DML: It is the area of SQL that allows changing data within the database.
DCL: it is component of SQL statement that control access to data and to the database.
DQL: it is the component of SQL statement that allows getting data from the database and
imposing ordering upon it.
Database Objects
An Oracle Database can contain multiple data structures. Each structure should be outlined in
the database design so that it can be created during the build stage of database development.
• Table: Stores data
• View: Subset of data from one or more tables
• Sequence: Generates numeric values
• Index: Improves the performance of some queries
• Synonym: Gives alternative names to objects
Naming Rules for table name
• Table names and column names must begin with a letter and 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 Oracle server
user.
• Names must not be an Oracle server-reserved word.

Note: Names are case-insensitive. For example, EMPLOYEES is treated as the same
name as eMPloyees or eMpLOYEES.

• CREATE TABLE statement: It clears your Screen


Syntax: CREATE TABLE <Table_Name> (<column_name><Data_Type>(<size>),
(<column_name><Data_Type>(<size>) );
Description: You create tables to store data by executing the SQL CREATE TABLE
statement. This statement is one of the DDL statements
• DEFAULT Option: It gives Default values to table
Syntax: CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT
SYSDATE);
Description: When you define a table, you can specify that a column be given a default value
by using the DEFAULT option. The default value can be a literal, an expression, or a SQL
function (such as SYSDATE or USER).
• INSERT INTO Statement: Inserting data into a table from another table
Syntax: INSERT INTO <Table_Name> (<column_name1>, <Column_name2>)
values (<value1>, <value2>);
OR
INSERT INTO <table_name> SELECT <column_name1>,
<Column_name2> from <table_name>;
OR
INSERT INTO <table_name> SELECT <column_name1>,
<Column_name2> from <table_name> WHERE <condition>;
Example: INSERT INTO department department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);

Update employee 114’s job and salary to match that of employee 205.
UPDATE employees SET job_id = (SELECT job_id FROM employees
WHERE employee_id = 205),salary= (SELECT salary FROM employees
WHERE employee_id = 205) WHERE employee_id = 114;
• SELECT: It selects data from table.
Syntax: SELECT * from <table_name>;
Or
SELECT <column_name1>, <Column_name2> from <table_name>;
Or
SELECT * from <table_name> where <condition>
Description: selects data and displays on screen. If * is used, all data from whole table
will be displayed. If specific attribute (Column name) is used only that attribute values will
be displayed.
• DISTINCT: Removes duplicate values.
Syntax: SELECT DISTINCT <column_name1>, <Column_name2> from <table_name>;
Or
SELECT DISTINCT * from <table_name>;
Description: Eliminate duplicate rows when using a select statement
• ORDER BY: It Sorts the data .
Syntax: SELECT * FROM <table_name> ORDER BY <column_name1>,
<Column_name2><sort_order>;
Description: rows retrieved from table will be sorted in either ascending or
descending order.
• DESCRIBE: It displays table structure .
Syntax: DESCRIBE <table_name>;

Exercises:
1. Create tables according to the following definition.
a) CREATE TABLE DEPOSIT (ACTNO VARCHAR2(5) ,CNAME
VARCHAR2(18) , BNAME VARCHAR2(18) , AMOUNT
NUMBER(8,2) ,ADATE DATE);
b) CREATE TABLE BRANCH(BNAME VARCHAR2(18),CITY
VARCHAR2(18));
c) CREATE TABLE CUSTOMERS(CNAME VARCHAR2(19) ,CITY
VARCHAR2(18));
2. Insert the data as shown below.
Table 1. Deposite
ACTNO CNAME BNAME AMOUNT ADATE
100 Anil Vrce 1000.00 1-MAR-95
101 Sunil Ajni 5000.00 4-JAN-96
102 Mehul Karolbagh 3500.00 17-NOV-95
104 Madhuri Chandi 1200.00 17-DEC-95
105 Prmod M.G.Road 3000.00 27-MAR-96
106 Sandip Andheri 2000.00 31-MAR-96
107 Shivani Virar 1000.00 5-SEP-95
108 Kranti Nehru Place 5000.00 2-JUL-95
109 Minu Powai 7000.00 10-AUG-95

3130703 DBMS
Table 2. Branch
BNAME CITY
Vrce Nagpur
Ajni Nagpur
Karolbagh Delhi
Chandi Delhi
Dharampeth Nagpur
M.G.Road Banglore
Andheri Bombay
Virar Bombay
Nehru Place Delhi
Powai Bombay
Table 3. Customers
CNAME CITY
Anil Calcutta
Sunil Delhi
Mehul Baroda
Mandar Patna
Madhuri Nagpur
Pramod Nagpur
Sandip Surat
Shivani Bombay
Kranti Bombay
Naren Bombay
Table 4. Borrow
LOANNO CNAME BNAME AMOUNT
201 Anil Vrce 1000.00
206 Mehul Ajni 5000.00
311 Sunil Dharampeth 3000.00
321 Madhuri Andheri 2000.00
375 Prmod Virar 8000.00
481 Kranti Nehru Place 3000.00
3. From the above given tables perform the following queries:
a) Describe deposit, branch.
b) Describe borrow, customers.
c) List all data from table DEPOSIT.
d) List all data from table BORROW.
e) List all data from table CUSTOMERS.
f) List all data from table BRANCH.
g) Give account no and amount of depositors.
h) Give name of depositors having amount greater than 4000.
i) Give name of customers who opened account after date '1-12-96'.

Review Questions:
1. What is the role of DDL and DML.
2. Difference between DDL, DML and DCL commands?
3. What are various DML commands in SQL? Give brief description of their purposes.
[This page is intentionally left blank]

3130703 DBMS
SQL concepts

Practical No: Date:

Aim: Develop programs to learn different types of SQL concept (Alias, conditional
operation, like).

Theory
RETRIEVING DATA USING THE SQL SELECT STATEMENT
Capabilities of SQL SELECT Statements
A SELECT statement retrieves information from the database. With a SELECT statement, you
can use the following capabilities:
• Projection: Choose the columns in a table that are returned by a query. Choose as few or
as many of the columns as needed.
• Selection: Choose the rows in a table that are returned by a query. Various criteria can be
used to restrict the rows that are retrieved.
• Joining: Bring together data that is stored in different tables by specifying the link
between them. SQL joins are covered in more detail in the lesson titled “Displaying Data
from Multiple Tables.”

• Selecting All Columns: It display all columns of data in a table by following the.
Syntax: SELECT * FROM departments;
• Selecting Specific Columns: It display specific columns of data in a table
Syntax: SELECT department_id, location_id FROM departments;
Desciption: You can use the SELECT statement to display specific columns of the
Table by specifying the column names, separated by commas
ARITHMETIC EXPRESSIONS
You may need to modify the way in which data is displayed, or you may want to perform
calculations or look at what-if scenarios. These are all possible using arithmetic expressions.
An arithmetic expression can contain column names, constant numeric values, and the
arithmetic operators.
Table 1: Basic arithmetic operators.
Operator Description
+ Add
- Subtract
* Multiply
/ divide

Example:
SELECT last_name, salary, salary + 300 FROM employees;
SELECT last_name, salary,12*salary+100 FROM employees;
SELECT last_name, salary,12*(salary+100) FROM employees;
• Null Values: Arithmetic expressions containing a null value evaluate to null.
Description: If a row lacks a data value for a particular column, that value is said to be null
or to contain a null. A null is a value that is unavailable, unassigned, unknown, or inapplicable.
A null is not the same as a zero or a space. Zero is a number, and a space is a character.
Columns of any data type can contain nulls.
Example: SELECT last_name, 12*salary*commission_pct FROM employees;
DEFINING A COLUMN ALIAS
• COLUMN ALIAS: Renames a column heading
Description: Is useful with calculations. Immediately follows the column name (There can also
be the optional AS keyword between the column name and alias.). If the alias contains spaces
or special characters (such as # or $), or if it is case-sensitive, enclose the alias in doublequotation
marks (" ").
Example: SELECT last_name AS name, commission_pctcommFROM employees;
Output:

Example: SELECT last_name "Name”, salary*12 "Annual Salary"FROM employees;


Output:

CONCATENATION OPERATOR
• CONCATENATION: Links columns or character strings to other columns
Description: Is represented by two vertical bars (||). Creates a resultant column that is a
character expression
Example: SELECT last_name || job_id AS "Employees" FROMemployees;

Values with the Concatenation Operator: If you concatenate a null value with a character
string, the result is a character string. LAST_NAME || NULL results in LAST_NAME.
• Literal Character Strings: A literal is a character, a number, or a date that is included
in the SELECT statement
Description: Date and character literal values must be enclosed by single quotation marks.
Each character string is output once for each row returned.
Example: SELECT last_name || ' is a ' || job_id AS "Employee Details"
FROM employees;
Output:

Example: SELECT last_name || ': 1 Month salary = ' || salaryMonthly FROM


employees;

3130703 DBMS
Output:

LIMITING THE ROWS THAT ARE SELECTED


• WHERE CLAUSE: It restrict the rows that are returned.
Syntax: SELECT *|{[DISTINCT] column|expression [alias],...}FROM table
[WHERE condition(s)];
Description: You can restrict the rows that are 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.
Example: SELECT employee_id, last_name, job_id, department_id
FROM employees WHERE department_id = 90;
• Character Strings and Dates:
• Character strings and date values are enclosed in single quotation marks.
• Character values are case sensitive, and date values are format sensitive.
• The default date format is DD-MON-RR.
Table 2: COMPARISON CONDITIONS
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<>,!=, ^= Not equal to
BETWEEN
Between two values (inclusive)
...AND...
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
Comparison conditions are used in conditions that compare one expression to another value or
expression. They are used in the WHERE clause in the following format:
Syntax: WHERE expr operator value
Example: WHERE hire_date = '01-JAN-95'
WHERE salary >= 6000
WHERE last_name = 'Smith'

Note: An alias cannot be used in the WHERE clause.


In the following example, the SELECT statement retrieves the last name and salary from the
EMPLOYEES table for any employee whose salary is less than or equal to $3,000. Note that
there is an explicit value supplied to the WHERE clause.

Example: SELECT last_name, salary FROM employees WHERE salary <= 3000;

• BETWEEN Condition: It display rows based on a range of values


Description: Use the BETWEEN condition to display rows based on a range of values. Values
that are specified with the BETWEEN condition are inclusive. You must specify the lower
limit first. You can also use the BETWEEN condition on character values:
Example: SELECT last_name, salary FROM employees WHERE salary
BETWEEN 2500 AND 3500;
Output: The SELECT statement in the slide returns rows from the EMPLOYEES table for
any employee whose salary is between $2,500 and $3,500.
Example: SELECT last_name FROM employees WHERE last_name
BETWEEN 'King' AND 'Smith';
Output: The SELECT statement in the slide returns rows from the EMPLOYEES table for
any employee whose last name is King or Smith.
• IN Condition: It test values in a specified set of values
Description: The IN condition is also known as the membership condition.
Example: SELECT employee_id, last_name, salary, manager_id FROM employees
WHERE manager_id IN (100, 101, 201);
Output:

The IN condition can be used with any data type.


Example: SELECT employee_id, manager_id, department_id FROM employees
WHERE last_name IN ('Hartstein', 'Vargas');
Output: The above example returns a row from the EMPLOYEES table for any employee
whose last name is included in the list of names in the WHERE clause

Note: If characters or dates are used in the list, they must be enclosed in single quotation
marks ('').
• LIKE Condition: It perform wildcard searches of valid search string values
Description: Search conditions can contain either literal characters or numbers:
% Denotes zero or many characters.
_ Denotes one character.
Example: SELECT first_name FROM employees WHERE first_name LIKE S%';
Output: The SELECT statement in the above example returns the employee first name from the
EMPLOYEES table for any employee whose first name begins with the letter S.
Note: the uppercase S. Names beginning with an s are not returned.

Description: The LIKE condition can be used as a shortcut for some BETWEEN comparisons.
Example: SELECT last_name, hire_date FROM employees WHERE hire_date LIKE '%95' ;
Output: Example displays the last names and hire dates of all employees who joined between
January 1995 and December 1995

3130703 DBMS
Description: You can combine pattern-matching characters
Example: SELECT last_name FROM employees WHERE last_name LIKE '_o%';
Output: The following example displays the names of all employees whose last names have
the letter o as the second character.

• ESCAPE: It gives an exact match for the actual % and _ characters.


Description: The ESCAPE option identifies the backslash (\) as the escape character. In the
pattern, the escape character precedes the underscore (_). This causes the Oracle Server to
interpret the underscore literally. If you want to search for strings that contain SA_, you can
use the following SQL statement:
Example: SELECT employee_id, last_name, job_id FROM employees WHERE
job_id LIKE '%SA\_%' ESCAPE '\';
Output:

• NULL Conditions: It tests for nulls.


Description: The NULL conditions include the IS NULL condition and the IS NOT NULL
condition. A null value means the value is unavailable, unassigned, unknown, or inapplicable.
Therefore, you cannot test with = because a null cannot be equal or unequal to any value.
Example: SELECT last_name, manager_id FROM employees WHERE manager_id
IS NULL;
Output: The above example retrieves the last names and managers of all employees who do
not have a manager.
To display last name, job ID, and commission for all employees who are not entitled to receive
a commission, use the following SQL statement:
Example: SELECT last_name, job_id, commission_pct FROM employees WHERE
commission_pct IS NULL;
Output:

Exercises:
1. Create the below given table and insert the data accordingly.

Table 1. Create Table Job (job_id, job_title, min_sal, max_sal)


Column Name Data Type
job_id Varchar2(15)
job_title Varchar2(30)
min_sal Number(7,2)
max_sal Number(7,2)
Table 2. Create table Employee (emp_no, emp_name, emp_sal, emp_comm,
dept_no
Column Name Data Type
emp_no Number(3)
emp_name Varchar2(30)
emp_sal Number(8,2)
emp_comm Number(6,1)
dept_no Number(3)
Table 3. Create table deposit(a_no,cname,bname,amount,a_date).
Column Name Data Type
a_no Varchar2(5)
Cname Varchar2(15)
Bname Varchar2(10)
Amount Number(7,2)
a_date Date
Table 4. Create table borrow(loanno,cname,bname,amount)
Column Name Data Type
Loanno Varchar2(5)
Cname Varchar2(15)
Bname Varchar2(10)
Amount Varchar2(7,2)

2. Insert following values in the table


Table 1 Job
job_id job_name min_sal max_sal
IT_PROG Programmer 4000 10000
MK_MGR Marketing manager 9000 15000
FI_MGR Finance manager 8200 12000
FI_ACC Account 4200 9000
LEC Lecturer 6000 17000
COMP_OP Computer Operator 1500 3000
Table 2 Employee
emp_n emp_name emp_sal emp_comm dept _no
101 Smith 800 20
102 Snehal 1600 300 25
103 Adama 1100 0 20
104 Aman 3000 15
105 Anita 5000 50,000 10
106 Sneha 2450 24,500 10
107 Anamika 2975 30
Table 3 Deposit
A_no Cname Bname Amount date
101 Anil Andheri 7000 01-Jan-06
102 Sunil Virar 5000 15-Jul-06
103 Jay villeparle 6500 12-Mar-06
104 Vijay Andheri 8000 17-Sep-06
105 Keyur Dadar 7500 19-Nov-06
106 Mayor Borivali 5500 21-Dec-06
3. Perform following queries
a) Retrieve all data from employee, jobs and deposit.
b) Give details of account no. and deposited rupees of customers having account
opened between dates 01-01-06 and 25-07-06.
c) Display all jobs with minimum salary is greater than 4000.

3130703 DBMS
d) Display name and salary of employee whose department no is 20. Give alias
name to name of employee.
e) Display employee no, name and department details of those employee whose
department lies in(10,20)
4. To study various options of LIKE predicate
a) Display all employee whose name start with ‘A’ and third character is ‘ ‘a’.
b) Display name, number and salary of those employees whose name is 5 characters
long and first three characters are ‘Ani’.
c) Display the non-null values of employees and also employee name second
character should be ‘n’ and string should be 5 characters long.
d) Display the null values of employee and also employee name’s third character
should be ‘a’.
e) What will be output if you are giving LIKE predicate as ‘%\_%’ ESCAPE ‘\’

Review Questions:
1. Is a NULL value same as zero or a blank space? If not then what is the difference?
2. What is the purpose of the condition operators BETWEEN and IN?
3. How do you search for a value in a database table when you don’t have the exact value
to search for?
[This page is intentionally left blank]

3130703 DBMS
Data Manipulation

Practical No: Date:

Aim: Develop programs to perform various data manipulation commands, aggregate functions
and sorting concept on all created tables.

Theory

• Creating a Table from a Table:


Syntax: CREATE TABLE <table_ name> (<column_name1>, <Column_name2>)
AS SELECT <column_name1>, <Column_name2> FROM <table _name>;
• DELETE:
Syntax: DELETE from <table _name>;
Description: Remove all rows
Syntax: DELETE from <table_ name> WHERE <condition>;
Description: Remove specific row

• UPADATING:
Syntax: UPDATE <table_ name>SET <coumn_name1>=<value1>,
<column_name1>=<value2>
Description: Update all row
Syntax: UPDATE <table_ name>SET <coumn_name1>=<value1>,
<column_name1>=<value2>WHERE <condition>;
Description: Update specific selected row

• MODIFING:
Syntax: ALTER TABLE <table_name>ADD ( <new_column_name>
<data_type>(<size>), new_column_name><data_type>(<size>)..);
Description: Adding new column.
Syntax: ALTER TABLE <table_name> DROP COLUMN <column_name>;
Description: Dropping column from table
Modifying existing Column:
Restriction on alter table:
• Table name and column name cannot be change.
• Decrease size of column if table data exists.

• RENAMING:
Syntax: RENAME <table_name> To <New_table_Name>;
Description: Table will be renamed.

• DROP:
Syntax: DROP TABLE <Table_name>;
Description: If table is dropped all records held within it are lost and cannot be recovered.
• All data and structure in the table are deleted.
• Any pending transactions are committed.
• All indexes are dropped.
• All constraints are dropped.
• You cannot roll back the DROP TABLE statement.
• TRUNCATING: It drop and re-create the table
Syntax: TRUNCATE TABLE <Table_name>;
Description: Truncate operation Removes all rows from a table, leaving the table empty and
the table structure intact Is a data definition language (DDL) statement rather than a DML
statement; cannot easily be undone

• ORDER BY: It sort retrieves rows with ascending order, default or descending order
Syntax: SELECT expr FROM table [WHERE condition(s)]
[ORDER BY {column, expr, numeric_position} [ASC|DESC]];
Description: The order of rows that are returned in a query result is undefined. The ORDER
BY clause can be used to sort the rows. If you use the ORDER BY clause, it must be the last
clause of the SQL statement. You can specify an expression, an alias, or a column position as
the sort condition.
Example: SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY hire_date;
Output:

• Default Ordering of Data:


The default sort order is ascending:
• Numeric values are displayed with the lowest values first (for example, 1 to 999).
• Date values are displayed with the earliest value first (for example, 01-JAN-92 before
01-JAN-95).
• Character values are displayed in alphabetical order (for example, A first and Z last).
• Null values are displayed last for ascending sequences and first for descending
sequences.
• You can sort by a column that is not in the SELECT list.
Example: SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY hire_dateDESC ;
Output: Sorting in descending order
Example: SELECT employee_id, last_name, salary*12 annsal FROM employees
ORDER BY annsal;
Output: Sorting by column alias
Example: SELECT last_name, department_id, salary FROM employees ORDER BY
department_id, salary DESC;
Output: Sorting by multiple columns
SUBSTITUTION VARIABLES
Using SQL Developer, you can create reports that prompt users to supply their own values to
restrict the range of data returned by using substitution variables. You can embed substitution
variables in a command file or in a single SQL statement. A variable can be thought of as a
container in which the values are temporarily stored. When the statement is run, the value is
substituted.
Use substitution variables to:
Temporarily store values with single-ampersand (&) and double-ampersand (&&)
substitution

3130703 DBMS
Use substitution variables to supplement the following:
• WHERE conditions
• ORDER BY clauses
• Column expressions
• Table names
• Entire SELECT statements

• “&” Substitution Variable: prompt the user for a value


Description: Use a variable prefixed with an ampersand (&) to prompt the user for a value
Example: SELECT employee_id, last_name, salary, department_id FROM employees
WHERE employee_id = &employee_num ;
Output:

Description: Character and Date Values with Substitution Variables. Use single quotation
marks for date and character values
Example: SELECT last_name, department_id, salary*12 FROM employees
WHERE job_id = '&job_title' ;
Output:
• && Substitution Variable:
Example: SELECT employee_id, last_name, job_id, &&column_name FROM employees
ORDER BY &column_name ;
Output:

Exercises:
1. Perform query on created table(i.e. in the experiment 2 and 3).
a) List total deposit from deposit.
b) List total loan from karolbagh branch
c) Give maximum loan from branch vrce.
d) Count total number of customers
e) Count total number of customer’s cities.
f) Create table supplier from employee with all the columns.
g) Create table sup1 from employee with first two columns.
h) Create table sup2 from employee with no data
i) Insert the data into sup2 from employee whose second character should be ‘n’
and string should be 5 characters long in employee name field.
j) Delete all the rows from sup1.
k) Delete the detail of supplier whose sup_ no is 103.
l) Rename the table sup2.
m) Destroy table sup1 with all the data.
n) Update the value dept_ no to 10 where second character of emp. name is ‘m’.
o) Update the value of employee name whose employee number is 103.

Review Questions:
1. What is the difference between Drop, Delete and Truncate statements in SQL Server?
2. What is Cascading referential integrity constraint?
3. Explain following features of SQL Server:
a) No Action
b) Cascade
c) Set NULL
d) Set Default

3130703 DBMS
Single Row function

Practical No: Date:

Aim: Develop programs to learn different types of Single-row functions.

Theory
Functions are a very powerful feature of SQL. They 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.

There are two types of functions:


• Single-row functions
• Multiple-row functions

Single-Row Functions: These functions operate on single rows only and return one result per
row. There are different types of single-row functions.
Multiple-Row Functions: Functions can manipulate groups of rows to give one result per
group of rows. These functions are also known as group functions.

SINGLE-ROW FUNCTIONS
Single-row functions are used to manipulate data items. They accept one or more arguments
and return one value for each row that is 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 that is returned in the query
• Returning one result per row
• Possibly returning a data value of a different type than the one that is referenced
• Possibly expecting one or more arguments
• Can be used in SELECT, WHERE, and ORDER BY clauses; can be nested

Single-Row Function:
• 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 , COALESCE ,CASE ,DECODE
Table 1: Single Row Function
Conversion Character Number Date General
Case Character
Manipulation Manipulation
Function Function
Implicit LOWER CONCAT ROUND MONTH_BETWEEN NVL
Explicit UPPER SUBSTR TRUNC ADD_MONTHS NVL2
INITCAP LENGTH MOD NEXT_DAY NVLLIF
INSTR ABS LAST_DAY COALES
CE
LPAD/RPAD POWER ROUND CASE
TRIM SQRT TRUNC DECODE
REPLACE EXP
Character functions
Table 2: Character Function (Case Manipulation)
Function Purpose
LOWER(column|expression) Converts alpha character values to lowercase
UPPER(column|expression) Converts alpha character values to uppercase
INITCAP(column|expression) Converts alpha character values to uppercase for the
first letter of each word; all other letters in lowercase
CONCAT(column1|expression1, Concatenates the first character value to the second
column2|expression2) character value; equivalent to concatenation operator
(||)
SUBSTR(column|expression,m[ Returns specified characters from character value
,n]) 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.)
Table 3: Character Function (Character Manipulation)
Function Purpose
LENGTH(column|expression) Returns the number of characters in the
expression
INSTR(column|expression, ’string’, [,m], Returns the numeric position of a named string.
[n] ) 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.
LPAD(column|expression, n, 'string') Pads the character value right-justified to a total
width of n character positions
RPAD(column|expression, n, 'string') Pads the character value left-justified to a total
width of n character positions
TRIM(leading|trailing|both, Enables you to trim heading or trailing
trim_character FROM trim_source) characters (or both) from a character string. If
trim_character or trim_source is a character
literal, you must enclose it in single quotation
marks.This is a feature that is available in
Oracle8i and later versions.

3130703 DBMS
REPLACE(text, search_string, Searches a text expression for a character string
replacement_string) and, if found, replaces it with a specified
replacement string

• CASE MANIPULATION:
Example: SELECT 'The job id for ' || UPPER(last_name) || ' is ' || LOWER(job_id) AS
"EMPLOYEE DETAILS" FROM employees;
Output:

Example: Display the employee number, name, and department number for employee Higgins
SELECT employee_id, last_name, department_id FROM employees
WHERE last_name = 'higgins';
Output: no rows selected

The WHERE clause of the first SQL statement specifies the employee name as higgins.
Because all the data in the EMPLOYEES table is stored in upper case, the name higgins does
not find a match in the table, and no rows are selected.

The WHERE clause of the second SQL statement specifies that the employee name in the
EMPLOYEES table is compared to higgins, converting the LAST_NAME column to
lowercase for comparison purposes. Because both names are now lowercase, a match is found
and one row is selected. The WHERE clause can be rewritten in the following manner to
produce the same result...WHERE last_name = 'Higgins'

So write down query as follow:


SELECT employee_id, last_name, department_id FROM employees
WHERE LOWER (last_name) = 'higgins';
CHARACTER MANIPULATION
• CONCAT: Joins values together (You are limited to using two parameters with
CONCAT.)
• SUBSTR: Extracts a string of determined length
• LENGTH: Shows the length of a string as a numeric value
• INSTR: Finds the numeric position of a named character
• LPAD: Pads the character value right-justified
• RPAD: Pads the character value left-justified
• TRIM: Trims heading or trailing characters (or both) from a character string (If
trim_character or trim_source is a character literal, you must enclose it in single
quotation marks.)
Table 4: different types of Character manipulation functions
Function Result
CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE('JACK and JUE','J','BL') BLACK and BLUE
• SUBSTR:
Example: SELECT SUBSTR (‘HELLOWORLD’, 1, 5) FROM dual;
Output: HELLO (gives 1 to 5 character from given string)
Example: SELECT SUBSTR(‘Smith’,1,0) FROM dual;
Output: 0
Example: SELECT SUBSTR(‘Smith’,1) FROM dual;
Output: Smith (gives whole string)
Example: SELECT SUBSTR(‘Smith’, -1) FROM dual;
Output: h (give the last character because when we indicate minus sign then it will give the
result from last character)
Example: SELECT SUBSTR(‘Smith’, -1, -3) FROM dual;
Output: Null (it give the NULL, not an error)
Example: SELECT SUBSTR(‘Smith’,-3) FROM dual;
Output: ith
Example: SELECT SUBSTR(‘Smith’,-3, 1) FROM dual;
Output: i (start from last third character and length is 1)

Note: For Description of Dual go to practical “Constraint”.


• LPAD: Pad value should be *, &, 0, -, +, space
Example: SELECT LPAD( salary, 10, *) FROM employees;
Output: ******3453 (if salary is 3453)
Example: SELECT LPAD( salary, 10, ‘’ ) FROM employees;
Output: return NULL
Example: SELECT LPAD( salary, 10, ‘ ‘) FROM employees;
Output: pad space value: 3453

• RPAD: Pad value should be *, &, 0, -, +, space


Example: SELECT RPAD( salary, 10, *) FROM employees;
Output: 3453****** (if salary is 3453)

• INSTR: It finds numeric position of given character.


Example: INSTR(‘HELLOWORLD’,’W’);
Output: 6

• REPLACE: Replace the character(s).


Example: REPLACE('JACK and JUE','J','BL');
Output: BLACK and BLUE

• TRIM: It trims heading and trailing character (or both) from a character string
Description: Work only for one character. Character must be first or last including space or all.
Example: TRIM(‘H’ FROM ‘HELLOWORLD’);
Output: ELLOWORLD (H trim)
Example: TRIM(‘HE’ FROM ‘HELLOWORLD’);
Output: give error
Example: TRIM(‘H’ FROM ‘ HELLOWORLD’);
Output: HELLOWORLD (space trim)

3130703 DBMS
• CONCAT, LENGTH, SUBSTR:
Description: The following example displays employee first names and last names joined
together, the length of the employee last name, and the numeric position of the letter a in the
employee last name for all employees who have the string REP contained in the job ID starting
at the fourth position of the job ID.
Example: SELECT employee_id, CONCAT(first_name, last_name) NAME job_id, LENGTH
(last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE
SUBSTR(job_id, 4) = 'REP';
Output:

• SUBSTR:
Description: Modify the SQL statement in the slide to display the data for those employees
whose last names end with the letter n.
Example: SELECT employee_id, CONCAT(first_name, last_name) NAME, LENGTH
(last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE
SUBSTR(last_name, -1, 1) = 'n';
Output:

Number Function
Number functions accept numeric input and return numeric values.
Table 5: Different types of number functions
Function Purpose
Rounds the column, expression, or value to n decimal
places or, if n is omitted, no decimal places (If n is
ROUND(column|expression, n)
negative, numbers to left of the decimal point are
rounded.)
Truncates the column, expression, or value to n
TRUNC(column|expression, n)
decimal places or, if n is omitted, n defaults to zero
MOD(m,n) Returns the remainder of m divided by n
ABS(n) Returns the absolute value of n
Returns m raised to th nth power.n must be an
POWER(m,n)
integer,else error returned.
SQRT(n) Returns square root of n. if n<0.Null
Returns e raised to the nth power.where
EXP(n)
e=2.71828283
GREATEST(expr1,expr2,..expr n) Returns the greatest value in a list of expression.
LEAST(expr1,expr2,..expr n) Returns the least value in a list of expression.
Returns the largest integer value that is equal to or
FLOOR(n)
less than a number.
Returns the smallest integer value that is equal to or
CEIL(n)
greater than a number.
Table 6: Examples of number functions.
Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
ABS(-15) 15
POWER(3,2) 9
SQRT(25) 5
EXP(5) 148.413159
GREATEST(4,5,17) 17
LEAST(4,5,17) 4
FLOOR(24.8) 24
CEIL(24.8) 25
• ROUND:
Example: SELECT ROUND (45.923,2), ROUND (45.923,0), ROUND(45.923,-1) FROM DUAL;
Output:

• TRUNC: It truncates the column, expression, or value to n decimal places.


Description: The TRUNC function works with arguments similar to those of the ROUND
function. If the second argument is 0 or is missing, the value is truncated to zero decimal places.
If the second argument is 2, the value is truncated to two decimal places. Conversely, if the
second argument is -2, the value is truncated to two decimal places to the left. If the second
argument is -1, the value is truncated to one decimal place to the left.
Like the ROUND function, the TRUNC function can be used with date functions.
Example: SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1) FROM DUAL;
Output:

• DATE: It allows to store and display date in specific format.


Description: The Oracle Database stores dates in an internal numeric format, representing the
century, year, month, day, hours, minutes, and seconds. The default display and input
format for any date is DD-MON-RR. Valid Oracle dates are between January 1, 4712 B.C.,
and December 31, 9999 A.D.
Example: SELECT last_name, hire_date FROM employees WHERE hire_date< '01-FEB-88';
Output: In the above example, the HIRE_DATE column output is displayed in the default
format DD-MON-RR. However, dates are not stored in the database in this format. All the
components of the date and time are stored. So, although a HIRE_DATE such as 17-JUN-87
is displayed as day, month, and year, there is also time and century information associated with
the date. The complete data might be June 17, 1987, 5:10:43 p.m.

• SYSDATE: It returns the current database server date and time.


Description: You can use SYSDATE just as you would use any other column name. For
example, you can display the current date by selecting SYSDATE from a table. It is customary
to select SYSDATE from a dummy table called DUAL.
Example: SELECT SYSDATE FROM DUAL;
Output: Display the current date using the DUAL table.

3130703 DBMS
• Arithmetic with Dates:
Description: Because the database stores dates as numbers, you can perform calculations using
arithmetic operators such as addition and subtraction. You can add and subtract number
constants as well as dates.
Table 7: Different arithmetic operators with Dates.
Operation Result Description
date + number Date Adds a number of days to a date
date - number Date Subtracts a number of days from a date
date - date Number of days Subtracts one date from another
date + number/24 Date Adds a number of hours to a date
In The following example displays the last name and the number of weeks employed for all
employees in department 90. It subtracts the date on which the employee was hired from the
current date (SYSDATE) and divides the result by 7 to calculate the number of weeks that a
worker has been employed.
Example: SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM
employees WHERE department_id = 90;
Output:

Table 8: Date Function.


Function Result
Finds the number of months between date1 and
date2. The result can be positive or negative. If date1
MONTHS_BETWEEN(date1,
is later than date2, the result is positive; if date1 is
date2)
earlier than date2, the result is negative. The no
integer part of the result represents a portion of the
month.
Adds n number of calendar months to date. The
ADD_MONTHS(date, n)
value of n must be an integer and can be negative.
Finds the date of the next specified day of the week
NEXT_DAY(date, 'char'): ('char') following date. The value of char may be a
number representing a day or a character string.
Finds the date of the last day of the month that
LAST_DAY(date):
contains date
Returns date rounded to the unit that is specified by
ROUND(date[,'fmt']): the format model fmt. If the format model fmt is
omitted, date is rounded to the nearest day.
Returns date with the time portion of the day
truncated to the unit that is specified by the
TRUNC(date[, 'fmt']):
format model fmt. If the format model fmt is
omitted, date is truncated to the nearest day.
Table 9: Examples of Date Function.
Function Result
MONTHS_BETWEEN('01-SEP-95','11-JAN-94') 19.6774194
ADD_MONTHS ('11-JAN-94',6) '11-JUL-94'
NEXT_DAY('01-SEP-95','FRIDAY') ‘08-SEP-95'
LAST_DAY('01-FEB-95') '28-FEB-95'

Example: Assume SYSDATE = '25-JUL-03'


Output: Table 10: Possible Output for above example.
Function Result
ROUND(SYSDATE,'MONTH') 01-AUG-03
ROUND(SYSDATE ,'YEAR') 01-JAN-04
TRUNC(SYSDATE ,'MONTH') 01-JUL-03
TRUNC(SYSDATE ,'YEAR') 01-JAN-03

Exercises:
1. Perform query on created table (i.e. in the experiment 2 and 3).
a) Write a query to display the current date. Label the column Date
b) For each employee, display the employee number, job, salary, and salary
increased by 15% and expressed as a whole number. Label the column New
Salary
c) Modify your query no 4.(2) to add a column that subtracts the old salary from
the new salary. Label the column Increase
d) Write a query that displays the employee’s names with the first letter capitalized
and all other letters lowercase, and the length of the names, for all employees
whose name starts with J, A, or M. Give each column an appropriate label. Sort
the results by the employees’ last names.
e) Write a query that produces the following for each employee: <employee last
name> earns <salary> monthly
f) Display the name, hire date, number of months employed and day of the week
on which the employee has started. Order the results by the day of the week
starting with Monday.
g) Display the hiredate of emp in a format that appears as Seventh of June 1994
12:00:00 AM.
h) Write a query to calculate the annual compensation of all employees
(sal+comm.).

Review Questions:
1. Is it possible to trim all the values in a column in a single statement?
2. Differentiate between ROUND, TRUNC and TRIM commands.
3. Which of the following commands is used to count the number of rows and non-
NULL values in Oracle database?
4. How we can perform arithmetic operations with DATE function. Explain with an
example.

3130703 DBMS
Constraints

Practical No: Date:

Aim: Develop programs to create table with different constraints.

Theory
Relating Multiple Tables
Each row of data in a table is uniquely identified by a primary key (PK). You can logically
relate data from multiple tables using foreign keys (FK).
Table 1: EMPLOYEES
Employee_ID First_Name Last_Name Dept_ID
200 Jennifer Whalen 10
201 Michael Hartstein 20
202 Pat Fay 20
205 Shelley Higgins 110
206 William Gietz 110
(Employee_ID = Primary Key, Dept_ID= Foreign Key)

Table 2: DEPARTMENTS
Dept_ID Dept_Name Manager_ID Location_ID
10 Administration 200 1700
20 Marketing 201 1800
50 Shipping 124 1500
60 IT 103 1400
80 Sales 149 2500
90 Executive 100 1700
110 Accounting 205 1700
190 Contracting (null) 1700
(Dept_ID=Primary Key)
Guidelines for Primary Keys and Foreign Keys
• You cannot use duplicate values in a primary key.
• Primary keys generally cannot be changed.
• Foreign keys are based on data values and are purely logical (not physical) pointers.
• A foreign key value must match an existing primary key value or unique key value, or
else it must be null.
• A foreign key must reference either a primary key or a unique key column.
• CONSTRAINTS: Oracle server uses constraints to prevent invalid data entry into tables.
Description: You can use constraints to do the following:
• Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from
that table. The constraint must be satisfied for the operation to succeed.
• Prevent the deletion of a table if there are dependencies from other tables
• Provide rules for Oracle tools, such as Oracle Developer
Following Constraints are there:
• NOT NULL: Specifies that the column cannot 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
Syntax: CREATE TABLE [schema.]table (column datatype [DEFAULT expr]
[column_constraint], [table_constraint][,...]);
Column-level constraint
column [CONSTRAINT constraint_name] constraint_type,
Table-level constraint
column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
Example: Column-level constraint:
CREATE TABLE employees(employee_id NUMBER(6) CONSTRAINT
emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...);
Table-level constraint
CREATE TABLE employees(employee_id NUMBER(6), first_nameVARCHAR2(20),
job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY
(EMPLOYEE_ID));

• NOT NULL Constraint:


The NOT NULL constraint ensures that the column contains no null values. Columns without
the NOT NULL constraint can contain null values by default. NOT NULL constraints must be
defined at the column level.

• UNIQUE Constraint: It validates that every value in a column or set of columns (key) be
unique—that is, no two rows of a table can have duplicate values in a specified column or
set of columns.
Description: The column (or set of columns) included in the definition of the UNIQUE key
Constraint is called the unique key. If the UNIQUE constraint comprises more than one
column, that group of columns is called a composite unique key.
Example: CREATE TABLE employees(employee_id NUMBER(6),last_name
VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary
NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT
NULL, CONSTRAINT emp_email_ukUNIQUE(email));
• Primary key constraint:
Example: CREATE TABLE departments(Department_id number(4) CONSTRAINT
dept_dept_id_pk PRIMARY KEY, Department_nameVARCHAR2(30),…);

• FOREIGN KEY Constraint:


The FOREIGN KEY (or referential integrity) constraint designates a column or combination
of columns as a foreign key and establishes a relationship between a primary key or a unique
key in the same table or a different table
Example: CREATE TABLE employees (employee_id NUMBER(6), last_name
VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2),
commission_pct NUMBER(2,2), hire_date DATE NOT NULL, department_id
NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id), CONSTRAINT
emp_email_uk UNIQUE(email));
Keywords
• FOREIGN KEY: Defines the column in the child table at the table-constraint level
• REFERENCES: Identifies the table and column in the parent table
• ON DELETE CASCADE: Deletes the dependent rows in the child table when a row
in the parent table is deleted
• ON DELETE SET NULL: Converts dependent foreign key values to null

3130703 DBMS
CHECK Constraint: It defines a condition that each row must satisfy
Description: The following expressions are not allowed:
• References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudo columns
• Calls to SYSDATE, UID, USER, and USERENV functions
• Queries that refer to other values in other rows
Example: ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...

• DUAL: It is a table owned by SYS.


Description: SYS owns the data dictionary. DUAL is a part of data dictionary. Describe the
structure of DUAL table.
Example: ESC DUAL;
Output:
NAME Null? TYPE
Dummy VARCHAR2(1)
We can run the general query by using DUAL.
Example: SELECT * FROM DUAL;
SELECT 2*2 FROM DUAL;
SELECT SYSDATE FROM DUAL;
Description: Create the DEPT table.
Example: CREATE TABLE dept (id NUMBER(7)CONSTRAINT department_id_pk
PRIMARY KEY, name VARCHAR2(25));
Description: Create the EMP table.
Example: CREATE TABLE emp (id NUMBER(7), last_name VARCHAR2(25),
first_name VARCHAR2(25), dept_id NUMBER(7) CONSTRAINT
emp_dept_id_FK REFERENCES dept (id));
Description: Populate the DEPT table with data from the DEPARTMENTS table. Include
only columns that you need.
Example: INSERT INTO dept SELECT department_id, department_name FROM departments;

Description: Create the EMPLOYEES2 table based on the structure of the EMPLOYEES
table. Include only the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and
DEPARTMENT_ID columns. Name the columns in your new table ID, FIRST_NAME,
LAST_NAME, SALARY, and DEPT_ID, respectively.
Example: CREATE TABLE employees2 AS SELECT employee_id id, first_name, last_name,
salary, department_iddept_id FROM employees;

Exercises:
1. Create A Human Resource Dataset with different constraints.
a) Human Resources (HR) Data Set
The Human Resources (HR) schema is part of the Oracle Common Schema that can be
installed in an Oracle Database. The practices in this course use the data from the HR
schema.

Table Descriptions
• REGIONS - contains rows representing a region (such as Americas, Asia, and so
on).
• COUNTRIES - contains rows for countries, each of which are associated with a
region.
• LOCATIONS - contains the addresses of specific offices, warehouses, and/or
production sites of a company in a particular country.
• DEPARTMENTS - shows details of the departments in which employees work.
Each department can have a relationship representing the department manager in
the EMPLOYEES table.
• EMPLOYEES - contains details about each employee who works for a
department. Some employees may not be assigned to any department.
• JOBS - contains the job types that can be held by each employee.
• JOB_HISTORY - contains the job history of the employees. If an employee
changes departments within the job or changes jobs within the department, a new
row is inserted in this table with the old job information of the employee.
• JOB_GRADES - identifies a salary range per job grade. The salary ranges do not
overlap.
REGIONS COUNTRY
Column_name Data Type
Column_name Data Type
REGION_ID NUMBER(4)
COUNTRY_ID NUMBER(4)
REGION_NAME VARCHAR2
COUNTRY_NAME VARCHAR2
REGION_ID NUMBER(4)
DEPARTMENTS
Column_name Null Data Type
EMPLOYEES
DEPARTMENT_ID NOT NUMBER(4)
Column_name Null Data Type
NULL
EMPLOYEE_ID NOT NUMBER(6)
DEPARTMENT_NAME NOT VARCHAR2(30)
NULL
NULL
FIRST_NAME VARCHAR2(20)
MANAGER_ID NUMBER(6)
LAST_NAME NOT VARCHAR2(25)
LOCATION_ID NUMBER(4)
NULL
JOBS EMAIL NOT VARCHAR2(25)
Column_name Null Data Type NULL
JOB_ID NOT NULL VARCHAR2(10)
PHONE_NUMBER VARCHAR2(20)
JOB_TITLE NOT NULL VARCHAR2(35)
HIRE_DATE NOT DATE
MIN_SALARY NUMBER(6) NULL
MAX_SALARY NUMBER(6) JOB_ID NOT VARCHAR2(10)
NULL
JOB_HISTORY SALARY NUMBER(8,2)
Column_name Null Data Type
COMMISSION_PAT NUMBER(2,2)
EMPLOYEE_ID NOT NUMBER(6)
MANAGER_ID NUMBER(6)
NULL
DEPRTMENT_ID NUMBER(4)
START_DATE NOT DATE
NULL
JOB_GRADES
END_DATE NOT DATE
Column_name Null Data Type
NULL
GRADE_LEVEL VARCHAR2(4)
JOB_ID NOT VARCHAR2(10)
NULL LOWEST_SAL NUMBER(6)
DEPARTMENT_ID NUMBER(4) HIGHEST_SAL NUMBER(6)

Review Questions:
1. What is the Purpose of foreign key constraint in SQL Server?
2. What do you understand by data integrity? List out types of data integrity?
3. Explain Referential Integrity Constraint.

3130703 DBMS
Types of Joins

Practical No: Date:

Aim: Displaying data from Multiple Tables (join)

Theory
Displaying Data from Multiple Tables
• Types of Joins
• Equijoins
• Nonequijoins
• Outer joins
• Self-joins
• Cross joins
• Natural joins
• Full (or two-sided) outer joins
• Cartesian Products
• A Cartesian product results in a display of all combinations of rows. This is done
by either omitting the WHERE clause or specifying the CROSS JOIN clause.
• Table Aliases
• Table aliases speed up database access.
• Table aliases can help to keep SQL code smaller by conserving memory.

Fig 1: Report displays data from two separate tables.


Sometimes you need to use data from more than one table. In the above example, the Employee
IDs exist in the EMPLOYEES table.
• Department IDs exist in both the EMPLOYEES and DEPARTMENTS tables.
• Department names exist in the DEPARTMENTS table.
To produce the report, you need to link the EMPLOYEES and DEPARTMENTS tables and
access data from both of them.
Types of Joins
Joins that are compliant with the SQL: 1999 standard include the following:
• Cross joins
• Natural joins
• USING clause
• Full (or two-sided) outer joins
• Arbitrary join conditions for outer joins

• Join: It links and use data from more than one table.
Syntax: SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] | [JOIN table2 ON (table1.column_name =
table2.column_name)]| [LEFT|RIGHT|FULL OUTER JOIN table2 ON
(table1.column_name = table2.column_name)]| [CROSS JOIN table2];

• Natural Joins: It selects rows from the two tables that have equal values in all matched
columns.
Description: The NATURAL JOIN clause is based on all columns in the two tables that have
the same name. If the columns having the same names have different data types, an error is
returned. In the following example, the LOCATIONS table is joined to the DEPARTMENT
table by the LOCATION_ID column, which is the only column of the same name in both tables.
If other common columns were present, the join would have used them all.
Example: INSERT INTO dept SELECT department_id, department_name FROM departments;
Output:

• Natural Joins with a WHERE Clause:


Description: Additional restrictions on a natural join are implemented by using a WHERE
clause. The following example limits the rows of output to those with a department ID equal
to 20 or 50.
Example: SELECT department_id, department_name, location_id, city FROM departments
NATURAL JOIN locations WHERE department_id IN (20, 50);

• Inner Join: It is a clause to match only one column when more than one column matches
Description: If several columns have the same names but the data types do not match, natural
join can be applied by using the INNER JOIN to specify the columns that should be used for
an equijoin. Do not use a table name or alias in the referenced columns.
Syntax: We can write the query by following two methods. Both are same.
SELECT <Table_name>.<column_name1>, <Table_name>.<column_name2>,
<Table_name>.<column_nameN>FROM <Table_name1> INNER JOIN
<Table_name2>ON <Table_name1>.<column_name1> = <Table_name2>.
<column_name2>WHERE <condition>ORDER BY <column_name1>,
<column_name2>, <column_nameN>;
OR
3130703 DBMS
SELECT <Table_name>.<column_name1>, <Table_name>.<column_name2>,
<Table_name>.<column_nameN>FROM <Table_name1>, <Table_name2>
WHERE <Table_name1>.<column_name1> = Table_name2>.<column_name2>
AND <condition>ORDER BY <column_name1>, <column_name2>,<column_nameN>;
• Column_name1 in table_name1 is usually that table’s PRIMARY KEY.
• Column_name2 in table_name2 is a FOREIGN KEY in that table.
• Column_name1 and Column_name2 must have the same data type and for certain
data types, the same size.
EMPLOYEES DEPARTMENTS

Fig 2: EMPLOYEES and DEPARTMENTS tables.


To determine an employee’s department name, you compare the value in the
DEPARTMENT_ID column in the EMPLOYEES table with the DEPARTMENT_ID values
in the DEPARTMENTS table. The relationship between the EMPLOYEES and
DEPARTMENTS tables is an equijoin; that is, values in the DEPARTMENT_ID column in
both tables must be equal. Frequently, this type of join involves primary and foreign key
complements.
Example: SELECT employees.employee_id, Departments.department_name FROM
employees INNER JOIN departments ON employees.department_id =
Departments. department_id;
OR
SELECT employees.employee_id, Departments.department_name FROM
employees,departments WHERE employees.department_id = Departments.
department_id;

• Table Aliases: Aliases have been used to simplify queries and to improve performance.
Description:
• Table aliases can be up to 30 characters in length, but shorter aliases are better than
longer ones.
• If a table alias is used for a particular table name in the FROM clause, then that
table alias must be substituted for the table name throughout the SELECT statement.
• Table aliases should be meaningful.
• The table alias is valid for only the current SELECT statement.
Example: SELECT e.employee_id, e.last_name, d.location_id, d.department_id FROM
employees e INNER JOIN departments d ON e.department_id = d.department_id;
• Self-Joins Using the ON Clause: It join a table to itself
Description: To find the name of each employee’s manager, you need to join the
EMPLOYEES table to itself, or perform a self-join. For example, to find the name of Lorentz’s
manager, you need to:
• Find Lorentz in the EMPLOYEES table by looking at the LAST_NAME column
• Find the manager number for Lorentz by looking at the MANAGER_ID column.
Lorentz’s manager number is 103.
• Find the name of the manager with EMPLOYEE_ID 103 by looking at the
LAST_NAME column. Hunold’s employee number is 103, so Hunold is Lorentz’s
manager.
In this process, you look in the table twice. The first time you look in the table to find Lorentz
in the LAST_NAME column and MANAGER_ID value of 103. The second time you look in
the EMPLOYEE_ID column to find 103 and the LAST_NAME column to find Hunold.
MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGERtable.

Fig 3: EMPLOYEES (WORKER) and EMPLOYEES (MANAGER)


Example: Self-join of the EMPLOYEES table, based on the EMPLOYEE_ID and
MANAGER_ID columns.
SELECT e.last_name, m.last_name FROM employees e JOIN employees m
ON (e.manager_id = m.employee_id);
Output:

3130703 DBMS
Example: Aliasing the column name. (In the following example bold + italic word refer to as
alise name of column.)
SELECT e.employee_ideid, e.last_namelastname, e.department_id, d.department_id,
d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;

• Non Equijoins: It is a join condition containing something other than an equality


operator.
Description: The relationship between the EMPLOYEES table and the JOB_GRADES table
is an example of a nonequijoin. A relationship between the two tables is that the SALARY
column in the EMPLOYEES table must be between the values in the LOWEST_SALARY and
HIGHEST_SALARY columns of the JOB_GRADES table. The relationship is obtained using
an operator other than equality (=).
Salary in the EMPLOYEES table must be between lowest salary and highest salary in the
JOB_GRADES table.
EMPLOYEES JOB_GRADES

Fig 4: EMPLOYEES and JOB_GRADES tables.


Example: SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j
ON e.salary BETWEEN j.lowest_sal AND j.highest_sal;
Output:

The above example creates a nonequijoin to evaluate an employee’s salary grade. The salary
must be between any pair of the low and high salary ranges.
It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
• None of the rows in the job grade table contain grades that overlap. That is, the salary
value for an employee can lie only between the low salary and high salary values of
one of the rows in the salary grade table.
• All of the employees’ salaries lie within the limits that are provided by the job grade
table. That is, no employee earns less than the lowest value contained in the
LOWEST_SAL column or more than the highest value contained in the
HIGHEST_SAL column.
Note: Other conditions (such as <= and >=) can be used, but BETWEEN is the simplest.
Remember to specify the low value first and the high value last when using BETWEEN. Table
aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.
• Outer Joins: A join between two tables that returns the results of the inner join as well as
the unmatched rows from the left (or right) tables is called a left (or right) outer join.
Description: If a row does not satisfy a join condition, the row does not appear in the query
result. For example, in the equijoin condition of EMPLOYEES and DEPARTMENTS tables,
department ID 190 does not appear because there are no employees with that department ID
recorded in the EMPLOYEES table. Instead of seeing 20 employees in the result set, you see
19 records. To return the department record that does not have any employees, you can use an
outer join. There are no employees in department 190.

Fig 5: EMPLOYEES and DEPARTMENTS tables.


INNER versus OUTER Joins
• In SQL: 1999, the join of two tables returning only matched rows is called an inner join.
• A join between two tables that returns the results of the inner join as well as the
unmatched rows from the left (or right) tables is called a left (or right) outer join.
• A join between two tables that returns the results of an inner join as well as the results
of a left and right join is a full outer join.
• There are three types of outer joins:
• LEFT OUTER
• RIGHT OUTER
• FULL OUTER
• Left Outer Join:
Description: The following query retrieves all rows in the EMPLOYEES table, which is the
table on the left even if there is no match in the DEPARTMENTS table.
Example: SELECT e.last_name, e.department_id, d.department_name FROM employees e
LEFT OUTER JOIN departments d ON (e.department_id = d.department_id);
Output:

3130703 DBMS
• Right Outer Join:
Description: The following query retrieves all rows in the DEPARTMENTS table, which is
the table on the right even if there is no match in the EMPLOYEES table.
Example: SELECT e.last_name, e.department_id, d.department_name FROM employees e
RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id);
Output:

• Full Outer Join:


Description: The following query retrieves all rows in the EMPLOYEES table, even if there
is no match in the DEPARTMENTS table. It also retrieves all rows in the DEPARTMENTS
table, even if there is no match in the EMPLOYEES table.
Example: SELECT e.last_name, d.department_id, d.department_name FROM employees e
FULL OUTER JOIN departments d ON (e.department_id = d.department_id);
Output:

• Cartesian product: When a join condition is invalid or omitted completely, the result is
a Cartesian product, in which all combinations of rows are displayed. All rows in the first
table are joined to all rows in the second table.
Description: A Cartesian product tends to generate a large number of rows, and the result is
rarely useful. You should always include a valid join condition unless you have a specific need
to combine all rows from all tables. Cartesian products are useful for some tests when you need
to generate a large number of rows to simulate a reasonable amount of data.A Cartesian product
is generated if a join condition is omitted.
Example: Employee last name and department name from the EMPLOYEES and
DEPARTMENTS tables. Because no join condition has been specified, all rows (20 rows) from
the EMPLOYEES table are joined with all rows (8 rows) in the DEPARTMENTS table,
thereby generating 160 rows in the output.
Fig 6: Cartesian product of EMPLOYEES and DEPARTMENTS tables.
• Creating Cross Joins: It produces the cross-product of two tables.
Description: This is also called a Cartesian product between the two tables.
Example: SELECT last_name, department_name FROM employees CROSS JOIN departments;

Exercises:
1) Displaying data from Multiple Tables (join)
1. Perform query on created table (i.e. in the experiment 2 and 3).
a) Give details of customers ANIL.
b) Give name of customer who are borrowers and depositors and having
living city Nagpur
c) Give city as their city name of customers having same living branch.
d) Write a query to display the last name, department number, and
department name for all employees.
e) Create a unique listing of all jobs that are in department 30. Include the
location of the department in the output
f) Write a query to display the employee name, department number, and
department name for all employees who work in NEW YORK.
g) Display the employee last name and employee number along with their
manager’s last name and manager number. Label the columns
Employee, Emp#, Manager, and Mgr#, respectively.

Review Questions:
1. Explain Self-Joins Using the ON Clause
2. Explain All Join in Relational algebra with example.
3. Explain types of Join query writing. Write both ANSI and Theta style query for
Exercise Queries: a to c.
4. Explain How Null values plays role in joining two tables.

3130703 DBMS
Data Aggregation

Practical No: Date:

Aim: To apply the concept of Aggregating Data using Group functions.

Theory

• AGGREGATED DATA USING THE GROUP FUNCTIONS [GROUP BY CLAUSE]:


Unlike single-row functions, group functions operate on sets of rows to give one result per
group. These sets may comprise the entire table or the table split into groups.
Table 1: Types of Group Functions
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) Maximum value of expr, ignoring null
values
MIN([DISTINCT|ALL]expr) Minimum value of expr, ignoring null
values
STDDEV([DISTINCT|ALL]x) Standard deviation of n, ignoring null values
SUM([DISTINCT|ALL]n) Sum values of n, ignoring null values
VARIANCE([DISTINCT|ALL]x) Variance of n, ignoring null values
Syntax: SELECT [column,] group_function(column),....
FROM table [WHERE condition] [GROUP BY column][ORDER BY column];
Description: DISTINCT makes the function consider only non-duplicate 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.

• AVG and SUM Functions: They are used for numeric data.
Example: SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM
employees WHERE job_id LIKE '%REP%';
Output:

• MIN and MAX Functions: They are used for numeric, character, and date data types.
Description: You can use the MAX and MIN functions for numeric, character, and date data
types.
Example: The below example displays the most junior and most senior employees.
SELECT MIN(hire_date), MAX(hire_date) FROM employees;
Output:

Example: The following example displays the employee last name that is first and the
employee last name that is last in an alphabetized list of all employees:
SELECT MIN(last_name), MAX(last_name) FROM employees;
Output:

Note: The AVG, SUM, VARIANCE, and STDDEV functions can be used only with numeric
data types. MAX and MIN cannot be used with LOB or LONG data types.

• COUNT Function: It counts rows.


Description:
The COUNT function has three formats:
• COUNT(*)
• COUNT(expr)
• COUNT(DISTINCT expr)
COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT
statement, including duplicate rows and rows containing null values in any of the columns. If
a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows
that satisfy the condition in the WHERE clause. In contrast, COUNT(expr) returns the number
of non-null values that are in the column identified by expr. COUNT(DISTINCT expr) returns
the number of unique, non-null values that are in the column identified by expr.
Example: The following example displays the number of employees in department 50.
SELECT COUNT (*) FROM employees WHERE department_id = 50;

Example: The following example displays the number of employees in department 80 who
can earn a commission. Using the DISTINCT Keyword COUNT(DISTINCT expr) returns
the number of distinct non-null values of expr.
SELECT COUNT (commission_pct) FROM employees WHERE department_id = 80;

Example: To display the number of distinct department values in the EMPLOYEES table
SELECT COUNT (DISTINCT department_id) FROM employees;

• GROUP BY: It creates groups of data.


Syntax: SELECT column, group_function(column) FROM table [WHERE condition]
[GROUP BY group_by_expression][ORDER BY column];
Description: You need to divide the table of information into smaller groups. You can do this
by using the GROUP BY clause.
Example: Find Average salary in the EMPLOYEES table for each department.
Table 2: DEPARTMENT WISE EMPLOYEES SALARY Table
Dept_ID Salary
1 10 1000
2 10 2000
3 20 1000
4 20 2000
5 30 2000
6 30 2000
Output:
Dept_ID Salary
1 10 1500
2 20 1500
3 30 2000
• If you include a group function in a SELECT clause, you cannot select individual results
as well, unless the individual column appears in the GROUP BY clause. You receive
an error message if you fail to include the column list in the GROUP BY clause.
• Using a WHERE clause, you can exclude rows before dividing them into groups.
• You must include the columns in the GROUP BY clause.
• You cannot use a column alias in the GROUP BY clause.
Example: All columns in the SELECT list that are not in group functions must be in the
GROUP BY clause.
SELECT department_id, AVG(salary) FROM employees GROUP BY department_id
Output:

Here is how this SELECT statement, containing a GROUP BY clause, is evaluated:


• The SELECT clause specifies the columns to be retrieved, as follows:
o Department number column in the EMPLOYEES table
o The average of all the salaries in the group that you specified in the GROUP BY
clause
• The FROM clause specifies the tables that the database must access: the EMPLOYEES
table.
• The WHERE clause specifies the rows to be retrieved. Because there is no WHERE
clause, all rows are retrieved by default.
• The GROUP BY clause specifies how the rows should be grouped. The rows are
grouped by department number, so the AVG function that is applied to the salary
column calculates the average salary for each department.
Example: You can use the group function in the ORDER BY clause
SELECT department_id, AVG(salary) FROM employees GROUP BY
department_id ORDER BY AVG(salary);
Output:

GROUP BY on Multiple Columns:


Example: SELECT department_iddept_id, job_id, SUM(salary) FROM employeesGROUP
BY department_id, job_id;
Output:

You can return summary results for groups and subgroups by listing more than one GROUP
BY column. You can determine the default sort order of the results by the order of the columns
in the GROUP BY clause. In the slide example, the SELECT statement containing a GROUP
BY clause is evaluated as follows:
• The SELECT clause specifies the column to be retrieved:
o Department number in the EMPLOYEES table
o Job ID in the EMPLOYEES table
o The sum of all the salaries in the group that you specified in the GROUP BY
clause
• The FROM clause specifies the tables that the database must access: the EMPLOYEES
table.
• The GROUP BY clause specifies how you must group the rows:
o First, the rows are grouped by department number.
o Second, the rows are grouped by job ID in the department number groups.
• So the SUM function is applied to the salary column for all job IDs in each department
numbergroup.
• Illegal Queries Using Group Functions:
Description: Any column or expression in the SELECT list that is not an aggregate function
must be in the GROUP BY clause:
Example: SELECT department_id, COUNT(last_name) FROM employees;
Output: Error (Column missing in the GROUP BY clause)

Description: Whenever you use a mixture of individual items (DEPARTMENT_ID) and group
functions (COUNT) in the same SELECT statement, you must include a GROUP BY clause
that specifies the individual items (in this case, DEPARTMENT_ID). If the GROUP BY clause
is missing, then the error message “not a single-group group function” appears. You can correct
the error in the slide by adding the GROUP BY clause.

Example: SELECT department_id, count(last_name) FROM employees GROUP BY


department_id;
Output:

Illegal Queries Using Group Functions


• You cannot use the WHERE clause to restrict groups.
• You use the HAVING clause to restrict groups.
• You cannot use group functions in the WHERE clause.
Example: SELECT department_id, AVG(salary) FROM employees WHERE
AVG (salary) > 8000 GROUP BY department_id;
Output: Error (Cannot use the WHERE clause to restrict groups)
You can correct the error in the example by using the HAVING clause to restrict groups:
Example: SELECT department_id, AVG(salary) FROM employees HAVING
AVG(salary) > 8000 GROUP BY department_id;
Output:

RESTRICTING GROUP RESULTS:


Table 3: DEPARTMENT WISE EMPLOYEES SALARY Table
Dept_ID Salary
1 10 5000
2 10 2000
3 20 9000
4 20 2000
5 30 6000
6 30 2000
Syntax: SELECT column, group_function FROM table [WHERE condition]
[GROUP BY group_by_expression] [HAVING group_condition]
[ORDER BY column];
Description: Find the maximum salary per department when it is greater than $3000.
Dept_ID Salary
1 10 5000
3 20 9000
5 30 6000
In the same way that you use the WHERE clause to restrict the rows that you select, you use
the HAVING clause to restrict groups. To find the maximum salary in each of the departments
that have a maximum salary greater than $3000, you need to do the following:
• Find the average salary for each department by grouping by department number.
Output:
• Restrict the groups to those departments with a maximum salary greater than $3000.
Restricting Group Results with the HAVING Clause
When you use the HAVING clause, the Oracle server restricts groups as follows:
• Rows are grouped.
• The group function is applied.
• Groups matching the HAVING clause are displayed.
Example: Example displays department numbers and maximum salaries for those
departments with a maximum salary that is greater than $10,000.
SELECT department_id, MAX(salary) FROM employees GROUP BY
department_id HAVING MAX(salary)>10000 ;
Description: You can use the GROUP BY clause without using a group function in the
SELECT list. If you restrict rows based on the result of a group function, you must have a
GROUP BY clause as well as the HAVING clause.
Example: The following example displays the job ID and total monthly salary for each job
that has a total payroll exceeding $13,000. The example excludes sales representatives and
sorts the list by the total monthly salary.
SELECT job_id, SUM(salary) PAYROLL FROM employees WHERE
job_id NOT LIKE '%REP%' GROUP BY job_id HAVING SUM(salary) > 13000
ORDER BY SUM(salary);
Output:

• Nesting Group Functions:


Example: Display the maximum average salary
SELECT MAX(AVG(salary)) FROM employees GROUP BY department_id;
Exercises:
1. Perform query on created table (i.e. in the experiment 2 and 3).
a) List total deposit of customer having account date after 1-jan-96.
b) List total deposit of customers living in city Nagpur.
c) List maximum deposit of customers living in Bombay.
d) Display the highest, lowest, sum, and average salary of all employees.
Label the columns Maximum, Minimum, Sum, and Average,
respectively. Round your results to the nearest whole number.
e) Write a query that displays the difference between the highest and lowest
salaries. Label the column DIFFERENCE.
f) Create a query that will display the total number of employees and, of
that total, the number of employees hired in 1995, 1996, 1997, and 1998
g) Find the average salaries for each department without displaying the
respective department numbers.
h) Write a query to display the total salary being paid to each job title, within
each department.
i) Find the average salaries > 2000 for each department without displaying
the respective department numbers.
j) Display the job and total salary for each job with a total salary amount
exceeding 3000, in which excludes president and sorts the list by the total
salary.
k) List the branches having sum of deposit more than 5000 and located in
city Bombay.
Review Questions:
1. Explain Group by having with example.
2. Explain Scalar function in SQL.
3. What is DUAL? Data types of DUAL. Display current date in Dual.
4. What is the difference between WHERE and HAVING clause in SQL?
5. List and explain various aggregate functions in SQL.
[This page is intentionally left blank]
Applying Sub query

Practical No: Date:

Aim: Develop programs to perform various sub query functions.

Theory
• Sub query:
Description: A query is called correlated sub query when both the inner query and the outer
query are interdependent. For every row processed by the inner query, the outer query is
processed as well. The inner query depends on the outer query before it can be processed.
Syntax: SELECT p.product_name FROM product p WHERE p.product_id = (SELECT
o.product_id FROM order_items o WHERE o.product_id = p.product_id);

A Subquery or Inner query or Nested query is a query within another SQL query, and embedded
within the WHERE clause.
A Subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.

Fig. 1: Sub Query syntax( Inner Query & Outer Query)


Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that Subqueries must follow;
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
• An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER
BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value
operators, such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
can be used within the subquery.
• Sub queries with the SELECT Statement:
Syntax: SELECT column_name [, column_name ] FROM table1 [, table2 ]
WHERE column_name OPERATOR (SELECT column_name [, column_name ]
FROM table1 [, table2 ] [WHERE]);

Description: Sub queries are most frequently used with the SELECT statement.
Example: Consider CUSTOMERS table is having following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now let us check following sub-query with SELECT statement:
Output:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

• Sub queries with the INSERT Statement:


Syntax: INSERT INTO table_name[ (column1 [, column2 ])] SELECT [ *|column1 [,
column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ]
Description: Subqueries also can be used with INSERT statements. The INSERT statement
uses the data returned from the subquery to insert into another table. The selected data in the
subquery can be modified with any of the character, date, or number functions.
The basic syntax is as follows:
Example: Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.
Now to copy complete CUSTOMERS table into CUSTOMERS_BKP,
INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
• Sub queries with the UPDATE Statement:
Syntax: UPDATE table SET column_name = new_value [WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME FROM TABLE_NAME) [WHERE)]
Description: The subquery can be used in conjunction with the UPDATE statement. Either
single or multiple columns in a table can be updated when using a subquery with the UPDATE
statement.
Example: Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table.
UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN
(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27);
Output: It updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose
AGE is greater than or equal to 27
This would impact two rows and finally CUSTOMERS table would have following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
• Sub queries with the DELETE Statement:
Syntax: DELETE FROM TABLE_NAME [WHERE OPERATOR [ VALUE ]
SELECT COLUMN_NAME FROM TABLE_NAME) [WHERE)];
Description: The sub query can be used in conjunction with the DELETE statement like with
any other statements mentioned above.
Example: Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. Following example deletes records from CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27
DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP WHERE AGE >27);
Output: This would impact two rows and finally CUSTOMERS table would have following
records
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

Exercises:
1. To solve queries using the concept of sub query.
a) Write a query to display the last name and hire date of any employee in
the same department as SCOTT. Exclude SCOTT
b) Give name of customers who are depositors having same branch city of
Mr. Sunil.
c) Give deposit details and loan details of customer in same city where
Pramod is living.
d) Create a query to display the employee numbers and last names of all
employees who earn more than the average salary. Sort the results in
ascending order of salary.
e) Give names of depositors having same living city as mr. anil and having
deposit amount greater than 2000
f) Display the last name and salary of every employee who reports to ford.
g) Display the department number, name, and job for every employee in the
Accounting department.
h) List the name of branch having highest number of depositors.
i) Give the name of cities where in which the maximum numbers of
branches are located.
j) Give name of customers living in same city where maximum depositors
are located.
2. Manipulating Data
a) Give 10% interest to all depositors.
b) Give 10% interest to all depositors having branch vrce
c) Give 10% interest to all depositors living in Nagpur and having branch city
Bombay.
d) Write a query which changes the department number of all employees with
empno 7788’s job to employee 7844’current department number.
e) Transfer 10 Rs from account of anil to sunil if both are having same branch.
f) Give 100 Rs more to all depositors if they are maximum depositors in their
respective branch.
g) Delete depositors of branches having number of customers between 1 to 3.
h) Delete deposit of Vijay.
i) Delete borrower of branches having average loan less than 1000.

Review Questions:
1. Which of the following are the types of sub-queries?
2. The construct returns true if a given tuple is present in the sub query.
3. State true or false: We can use Sub queries inside the from clause.
4. Which of the following clause is mandatorily used in a sub-query? Justify your
answer.
a. SELECT
b. WHERE
c. ORDER BY
d. GROUP BY
5. Which of the following single-row operators can be used for writing a sub-query?
a. &gt;=
b. &lt;
c. =
d. All of the above
Transaction control commands

Practical No: Date:

Aim: Study of various Transaction control commands.

Theory
What Is a Transaction?
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
In a relational database using SQL, transactions are accomplished using the DML commands
(INSERT, UPDATE, and DELETE) A transaction is the propagation of one or more changes
to the database. For instance, you are performing a transaction if you performed an UPDATE
statement on a table to change an individual's name.
A transaction can either be one DML statement or a group of statements. When managing
groups of Transactions, each designated group of transactions must be successful as one entity
or none of them will be successful.
The following list describes the nature of transactions:
• All transactions have a beginning and an end.
• A transaction can be saved or undone.
• If a transaction fails in the middle, no part of the transaction can be saved to the
database.
Note: To start or execute transactions is implementation-specific. You must check your
particular implementation for how to begin transactions. There is no explicit start or begin
transaction in the ANSI standard.

What Is Transactional Control?


Transactional control is the ability to manage various transactions that may occur within a
relational database management system. When you speak of transactions, you are referring to
the INSERT, UPDATE, and DELETE commands.
When a transaction is executed and completes successfully, the target table is not immediately
changed, although it may appear so according to the output. When a transaction successfully
completes, there are transactional control commands that are used to finalize the transaction,
either saving the changes made by the transaction to the database or reversing the changes made
by the transaction.
There are three commands used to control transactions:
• COMMIT
• ROLLBACK
• SAVEPOINT
Each of these is discussed in detail in the following sections.
Note Transactional control commands are only used with the DML commands INSERT,
UPDATE, and DELETE. For example, you do not issue a COMMIT statement after creating a
table. When the table is created, it is automatically committed to the database. Likewise, you
cannot issue a ROLLBACK to replenish a table that was just dropped.
When a transaction has completed, the transactional information is stored either in an allocated
area or in a temporary rollback area in the database. All changes are held in this temporary
rollback area until a Transactional control command is issued. When a transactional control
command is issued, changes are either made to the database or discarded; then, the temporary
rollback area is emptied.
Fig. 1: Rollback area.
• COMMIT Command: It is the transactional command used to save changes invoked by a
transaction to the database.
Syntax: COMMIT [WORK];
Description: The COMMIT command saves all transactions to the database since the last
COMMIT or ROLLBACK command.
Example: SELECT * FROM PRODUCTS_TMP;
Output: 11 rows selected
Example: DELETE FROM PRODUCTS_TMP WHERE COST < 14;
Output: 8 rows deleted.
Example: COMMIT;
Output: Commit complete

• ROLLBACK Command: It is the transactional control command used to undo


transactions that have not already been saved to the database.
Syntax: rollback [work];
Description: The ROLLBACK command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued. Once again, as in the COMMIT statement,
the WORK keyword is an optional part of the ROLLBACK syntax.
Example: In the following example, you begin by selecting all records from the
PRODUCTS_TMP table since the previous deletion of 14 records.
SELECT * FROM PRODUCTS_TMP;
Output: 3 rows selected.
Example: Next, you update the table, changing the product cost to $39.99 for the product
identification number 11235
UPDATE PRODUCTS_TMP SET COST = 39.99 WHERE PROD_ID = '11235';
Output: 1 row updated.
Example: If you perform a quick query on the table, the change appears to have occurred;
SELECT * FROM PRODUCTS_TMP;
Output: 3 rows selected.
Example: Now, issue the ROLLBACK statement to undo the last change:
ROLLBACK;
Output: Rollback complete.
• SAVEPOINT Command: It is point in a transaction when you can roll the transaction
back to a certain point without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME
Description: This command serves only in the creation of a SAVEPOINT among transactional
statements. The ROLLBACK command is used to undo a group of transactions. The
SAVEPOINT is a way of managing transactions by breaking large numbers of transactions into
smaller, more manageable groups.
• Note: The SAVEPOINT name must be unique to the associated group of transactions.
However, the SAVEPOINT can have the same name as a table or other object. Refer to
specific implementation documentation for more details on naming conventions.
• ROLLBACK TO SAVEPOINT Command:
Syntax: ROLLBACK TO SAVEPOINT_NAME;
Example: In this example, you plan to delete the remaining three records from the
PRODUCTS_TMP table. You want to create a SAVEPOINT before each delete, so that you
can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state;
Input
SAVEPOINT SP1;
Output
Savepoint created.
Input
DELETE FROM PRODUCTS_TMP WHERE PROD_ID = '11235';
Output
1 row deleted.
Input
SAVEPOINT SP2;
Output
Savepoint created.
Input
DELETE FROM PRODUCTS_TMP WHERE PROD_ID = '90';
Output
1 row deleted.
Input
SAVEPOINT SP3;
Output
Savepoint created.
Input
DELETE FROM PRODUCTS_TMP WHERE PROD_ID = '2345';
Output
1 row deleted.

Now that the three deletions have taken place, say you have changed your mind and decided to
ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after
the first deletion, the last two deletions are undone;
Input
ROLLBACK TO SP2;
Output
Rollback complete.
• RELEASE SAVEPOINT Command: It is used to remove a SAVEPOINT that you have
created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME;
Description: Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the SAVEPOINT.

Exercises:
1. Perform all the transaction command and write down 2 example of each.

Review Questions:
1. Explain SAVEPOINT with example.
2. Explain ROLLBACK with example.
3. List out TCL commands.
4. Save points divide a long transaction into smaller parts. This statement is true or
false.
5. What is the fundamental difference between COMMIT and COMMIT WORK?
Access Privileges

Practical No: Date:

Aim: Study of various Transaction control commands.

Theory

Introduction to Privileges
A privilege is a right to execute a particular type of SQL statement or to access another user's
object. Some examples of privileges include the right to:
• Connect to the database (create a session)
• Create a table
• Select rows from another user's table
• Execute another user's stored procedure
You grant privileges to users so these users can accomplish tasks required for their job. You
should grant a privilege only to a user who absolutely requires the privilege to accomplish
necessary work. Excessive granting of unnecessary privileges can compromise security. A user
can receive a privilege in two different ways:
• You can grant privileges to users explicitly. For example, you can explicitly grant the
privilege to insert records into the employees table to the user SCOTT.
• You can also grant privileges to a role (a named group of privileges), and then grant the
role to one or more users. For example, you can grant the privileges to select, insert,
update, and delete records from theemployees table to the role named clerk, which in
turn you can grant to the users Scott and Brian.
Because roles allow for easier and better management of privileges, you should normally grant
privileges to roles and not to specific users.
There are two distinct categories of privileges:
• System privileges
• Schema object privileges

System Privileges
A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type. For example, the privileges to create table spaces and to
delete the rows of any table in a database are system privileges. There are over 60 distinct
system privileges.
Grant and Revoke System Privileges - You can grant or revoke system privileges to users
and roles. If you grant system privileges to roles, then you can use the roles to manage
system privileges. For example, roles permit privileges to be made selectively available.

Use either of the following to grant or revoke system privileges to users and roles:
• Oracle Enterprise Manager Console
• The SQL statements GRANT and REVOKE

Who Can Grant or Revoke System Privileges?


Only users who have been granted a specific system privilege with the ADMIN OPTION or
users with the system privileges GRANT ANY PRIVILEGE or GRANT ANY OBJECT
PRIVILEGE can grant or revoke system privileges to other users.
Schema Object Privileges:
Description: A schema object privilege is a privilege or right to perform a particular action
on a specific schema object:
• Table
• View
• Sequence
• Procedure
• Function
• Package
Different object privileges are available for different types of schema objects. For example, the
privilege to delete rows from the departments table is an object privilege.
Some schema objects, such as clusters, indexes, triggers, and database links, do not have
associated object privileges. Their use is controlled with system privileges. For example, to
alter a cluster, a user must own the cluster or have the ALTER ANY CLUSTER system
privilege.
A schema object and its synonym are equivalent with respect to privileges. That is, the object
privileges granted for a table, view, sequence, procedure, function, or package apply whether
referencing the base object by name or using a synonym.
Example: Assume there is a table jward.emp with a synonym named jward.employee and the
user jward issues the following statement;
GRANT SELECT ON emp TO swilliams;
The user swilliams can query jward.emp by referencing the table by name or using the
synonym jward.employee;
SELECT * FROM jward.emp;
SELECT * FROM jward.employee;
If you grant object privileges on a table, view, sequence, procedure, function, or package to
a synonym for the object, the effect is the same as if no synonym were used. For example,
if jward wanted to grant the SELECT privilege for the emp table to swilliams, jward could
issue either of the following statements;
GRANT SELECT ON emp TO swilliams;
GRANT SELECT ON employee TO swilliams;
If a synonym is dropped, all grants for the underlying schema object remain in effect, even if
the privileges were granted by specifying the dropped synonym.

Grant and Revoke Schema Object Privileges


Schema object privileges can be granted to and revoked from users and roles. If you grant
object privileges to roles, you can make the privileges selectively available. Object privileges
for users and roles can be granted or revoked using the following:
• The SQL statements GRANT and REVOKE, respectively
• The Add Privilege to Role/User dialog box and the Revoke Privilege from Role/User
dialog box of Oracle Enterprise Manager.

Grant Schema Object Privileges:


Description: A user automatically has all object privileges for schema objects contained in his
or her schema. A user can grant any object privilege on any schema object he or she owns to
any other user or role. A user with the GRANTANY OBJECT PRIVILEGE can grant or revoke
any specified object privilege to another user with or without the GRANT OPTION of
the GRANT statement. Otherwise, the grantee can use the privilege, but cannot grant it to other
users.
Example: Assume user SCOTT has a table named t2;
SQL> GRANT grant any object privilege TO U1;
SQL> connect u1/u1
Connected.
SQL> GRANT select on scott.t2 \TO U2;
SQL> SELECT GRANTEE, OWNER, GRANTOR, PRIVILEGE, GRANTABLE FROM
DBA_TAB_PRIVS WHERE TABLE_NAME = 'employees';
Output:
GRANTEE OWNER

GRANTOR PRIVILEGE GRA

U2 SCOTT
SCOTT SELECT NO

Table Security
Schema object privileges for tables allow table security at the level of DML and DDL
operations.
Data Manipulation Language Operations
You can grant privileges to use the DELETE, INSERT, SELECT, and UPDATE DML
operations on a table or view. Grant these privileges only to users and roles that need to query
or manipulate a table's data.
You can restrict INSERT and UPDATE privileges for a table to specific columns of the table.
With selective INSERT, a privileged user can insert a row with values for the selected columns.
All other columns receive NULL or the column's default value. With selective UPDATE, a
user can update only specific column values of a row. Selective
INSERT and UPDATE privileges are used to restrict a user's access to sensitive data. For
example, if you do not want data entry users to alter the salary column ofthe
employees table, selective INSERT or UPDATE privileges can be granted that exclude the
salary column. Alternatively, a view that excludes the salary column could satisfy this needfor
additional security.

Data Definition Language Operations


The ALTER, INDEX, and REFERENCES privileges allow DDL operations to be performed
on a table. Because these privileges allow other users to alter or create dependencies on a table,
you should grant privileges conservatively. A user attempting to perform a DDL operation on
a table may need additional system or object privileges. For example, to create a trigger on a
table, the user requires both the ALTER TABLE object privilege for the table andthe
CREATE TRIGGER system privilege.
As with the INSERT and UPDATE privileges, the REFERENCES privilege can be granted on
specific columns of a table. The REFERENCES privilege enables the grantee to use the table
on which the grant is made as a parent key to any foreign keys that the grantee wishes to create
in his or her own tables. This action is controlled with a special privilege because the presence
of foreign keys restricts the data manipulation and table alterations that can be done to the
parent key. A column-specific REFERENCES privilege restricts the grantee to using the named
columns (which, of course, must include at least one primary or unique key of the parent table).

Exercises:
1. Create different user and give the roles. Also gives the different access rights
according to roles.
Review Questions:
1. Explain GRANT with All Privilege.
2. Explain REVOKE with All Privilege.
3. GRANT ALL ON Table_1 to A;
i. In above statement ALL means:
4. DENY and REVOKE remove any GRANT permission on a securable. This
statement is true or false.

You might also like