2nd and 3rd Unit
2nd and 3rd Unit
Normalization
A large database defined as a single relation may result in data duplication. This
repetition of data may result in:
So to handle these problems, we should analyze and decompose the relations with
redundant data into smaller, simpler, and well-structured relations that are satisfy
desirable properties. Normalization is a process of decomposing the relations into
relations with fewer attributes.
What is Normalization?
o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of
relations. It is also used to eliminate undesirable characteristics like Insertion,
Update, and Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using
relationships.
o The normal form is used to reduce redundancy from the database table.
The main reason for normalizing the relations is removing these anomalies. Failure to
eliminate anomalies leads to data redundancy and can cause data integrity and other
problems as the database grows. Normalization consists of a series of guidelines that
helps to guide you in creating a good database structure.
o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new
tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the deletion
of data results in the unintended loss of some other important data.
o Updatation Anomaly: The update anomaly is when an update of a single data
value requires multiple rows of data to be updated.
2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are fully
functional dependent on the primary key.
4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has no multi-
valued dependency.
5NF A relation is in 5NF. If it is in 4NF and does not contain any join dependency,
joining should be lossless.
Advantages of Normalization
o Normalization helps to minimize data redundancy.
o Greater overall database organization.
o Data consistency within the database.
o Much more flexible database design.
o Enforces the concept of relational integrity.
Disadvantages of Normalization
o You cannot start building the database before knowing what the user needs.
o The performance degrades when normalizing the relations to higher normal
forms, i.e., 4NF, 5NF.
o It is very time-consuming and difficult to normalize relations of a higher degree.
o Careless decomposition may lead to a bad database design, leading to serious
problems.
EMPLOYEE table:
14 John 7272826385, UP
9064738238
The decomposition of the EMPLOYEE table into 1NF has been shown below:
14 John 7272826385 UP
14 John 9064738238 UP
Example: Let's assume, a school can store the data of teachers and the subjects they
teach. In a school, a teacher can teach more than one subject.
TEACHER table
25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
To convert the given table into 2NF, we decompose it into two tables:
TEACHER_DETAIL table:
TEACHER_ID TEACHER_AGE
25 30
47 35
83 38
TEACHER_SUBJECT table:
TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer
Third Normal Form (3NF)
o A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
o 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
o If there is no transitive dependency for non-prime attributes, then the relation must be in
third normal form.
A relation is in third normal form if it holds atleast one of the following conditions for
every non-trivial function dependency X → Y.
1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.
Example:
EMPLOYEE_DETAIL table:
That's why we need to move the EMP_CITY and EMP_STATE to the new
<EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.
EMPLOYEE table:
EMPLOYEE_ZIP table:
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys.
To convert the given table into BCNF, we decompose it into three tables:
EMP_COUNTRY table:
EMP_ID EMP_COUNTRY
264 India
264 India
EMP_DEPT table:
EMP_DEPT_MAPPING table:
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549
Functional dependencies:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate keys:
Example
STUDENT
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics
The given STUDENT table is in 3NF, but the COURSE and HOBBY are two independent
entity. Hence, there is no relationship between COURSE and HOBBY.
STUDENT_COURSE
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics
STUDENT_HOBBY
STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey
SEMESTER SUBJECT
Semester 1 Computer
Semester 1 Math
Semester 1 Chemistry
Semester 2 Math
Example
SUBJECT LECTURER SEMESTER
In the above table, John takes both Computer and Math class for Semester 1 but he
doesn't take Math class for Semester 2. In this case, combination of all these fields
required to identify a valid data.
Suppose we add a new Semester as Semester 3 but do not know about the subject and
who will be taking that subject so we leave Lecturer and Subject as NULL. But all three
columns together acts as a primary key, so we can't leave other two columns blank.
So to make the above table into 5NF, we can decompose it into three relations P1, P2 &
P3:
P1
P2
SUBJECT LECTURER
Computer Anshika
Computer John
Math John
Math Akash
Chemistry Praveen
P3
SEMSTER LECTURER
Semester 1 Anshika
Semester 1 John
Semester 1 John
Semester 2 Akash
Semester 1 Praveen
What is SQL?
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational
Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL as their standard database language.
Also, they are using different dialects, such as −
Why SQL?
SQL is widely popular because it offers the following advantages −
Allows users to access data in the relational database management systems.
Allows users to describe the data.
Allows users to define the data in a database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & pre-
compilers.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views.
Query Dispatcher
Optimization Engines
Classic Query Engine
SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query engine won't
handle logical files.
Following is a simple diagram showing the SQL Architecture −
SQL Commands
The standard SQL commands to interact with relational databases are CREATE,
SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified
into the following groups based on their nature −
1 CREATE
Creates a new table, a view of a table, or other object in the database.
ALTER
2
Modifies an existing database object, such as a table.
DROP
3
Deletes an entire table, a view of a table or other objects in the database.
1 SELECT
Retrieves certain records from one or more tables.
INSERT
2
Creates a record.
UPDATE
3
Modifies records.
4 DELETE
Deletes records.
1 GRANT
Gives a privilege to user.
REVOKE
2
Takes back privileges granted from user.
The result of this query is a relation with the following attributes: name,
courseid
SQL provides a way of renaming the attributes of a result relation. It uses
the as clause, taking the form:
Q. Find the names of all instructors whose salary is greater than at least one
instructor in the Biology department.
The SQL standard specifies that the equality operation on strings is case
sensitive; as a result the expression "'comp. sci.' = 'Comp.
Sci.'" evaluates to false.
Patterns are case sensitive; that is, uppercase characters do not match
lowercase characters, or vice versa.
Q: “Find the names of all departments whose building name includes the
substring ‘Computer’.”
1. select deptname
2. from department
Additional Notes:
1. For patterns to include the special pattern characters (that is, % and
_ ), SQL allows the specification of an escape character '\'.
1. select *
2. from instructor;
The order by clause causes the tuples in the result of a query to appear
in sorted order.
1. select name
2. from instructor
4. order by name;
1. select *
2. from instructor
1. select name
2. from instructor
Q . Find the instructor names and the courses they taught for all instructors in
the Biology department who have taught some course.
Note : In the above query: if we write (a1, a2) ≤ (b1, b2) then it is the same as
writing a1 ≤ b1 and a2 ≤ b2. The comparison operators can be used on tuples,
and the ordering is defined lexicographically.
Set Operations
The SQL operations union, intersect, and except operate on relations and
correspond to the mathematical set-theory operations ∪, ∩, and −.
Q . Illustrate use of 'union' -> To find the set of all courses taught either in Fall
2009 or in Spring 2010, or both
0. (select courseid
1. from section
3. union
4. (select courseid
5. from section
7.
2. The union operation automatically eliminates duplicates, unlike the select
clause.
0. (select courseid
1. from section
3. union all
4. (select courseid
5. from section
Q . Illustrate use of 'intersect' -> To find the set of all courses taught in Fall 2009
as well as in Spring 2010
0. (select courseid
1. from section
3. intersect
4. (select courseid
5. from section
7.
0. (select courseid
1. from section
3. intersect all
4. (select courseid
5. from section
Q. Illustrate use of The Except Operation -> To find all courses taught in the Fall
2009 semester but not in the Spring 2010 semester
(select courseid
from section
except
(select courseid
from section
The except operation outputs all tuples from its first input that do not
occur in the second input; that is, it performs set difference. The
operation automatically eliminates duplicates in the inputs before
performing set difference.
(select courseid
from section
except all
(select courseid
from section
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
There are certain rules which must be followed to perform operations using SET
operators in SQL. Rules are as follows:
Table 1: t_employees
Table 2: t2_employees
Table 4: t2_students
1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after performing the
UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_employees table.
Example 2:
Write a query to perform union between the table t_students and the table t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_students table.
Since we have performed union operation between both the tables, so only the records
from the first and second table are displayed except for the duplicate records.
2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform UNION ALL operation with
the records fetched by the second SELECT query from the t2_employees table.
Since we have performed union all operation between both the tables, so all the records
from the first and second table are displayed, including the duplicate records.
Example 2:
Write a query to perform union all operation between the table t_students and the table
t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform UNION ALL operation with the
records fetched by the second SELECT query from the t2_students table.
Since we have performed union all operation between both the tables, so all the records
from the first and second table are displayed, including the duplicate records.
3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform INTERSECT operation with
the records fetched by the second SELECT query from the t2_employees table.
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
Example 2:
Write a query to perform intersect operation between the table t_students and the table
t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_students table.
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
1. MINUS
o It displays the rows which are present in the first query but absent in the second
query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform MINUS operation with the
records fetched by the second SELECT query from the t2_employees table.
Since we have performed Minus operation between both the tables, so only the
unmatched records from both the tables are displayed.
Example 2:
Write a query to perform a minus operation between the table t_students and the table
t2_students.
Query:
Since we have performed a minus operation between both the tables, so only the
Unmatched records from both the tables are displayed.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a
NULL value is one that has been left blank during record creation!
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Tip: Always use IS NULL to look for NULL values.
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
SQL Aggregate Functions: SUM(), COUNT(),
AVG(), Functions
Table of Contents
What is an Aggregate Function in SQL?
COUNT() Function
SUM() Function
AVG() Function
MIN() Function
View More
An aggregate function in SQL performs a calculation on multiple values and returns a single
value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc. An
aggregate function ignores NULL values when it performs the calculation, except for the count
function.
An aggregate function in SQL returns one value after calculating multiple values of a column.
We often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT
statement.
Count()
Sum()
Avg()
Min()
Max()
COUNT() Function
Syntax:
COUNT(*)
or
Example:
We will use the ‘products’ table from the sample database for our demonstration.
The following SQL statement fetches the number of products in the table.
Let's look at how we can use GROUP BY and HAVING functions with the COUNT function.
The SQL command given below will list the number of customers in each city.
This will produce the following results:
SUM() Function
Syntax:
SUM()
or
Example:
The following SQL statement finds the sum of the "unit price" fields in the "products" table:
Let’s look at how we can use GROUP BY and HAVING functions with the SUM function.
The SQL command below will list the number of customers in each city, having a sum of points
greater than 3000.
Syntax:
AVG()
or
Example:
The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL values.
Syntax:
MIN()
or
Example:
The above code will give us the minimum quantity in stock in the products table.
MAX() Function
The MAX() aggregate function returns the highest value (maximum) in a set of non-NULL
values.
Syntax:
AVG()
or
Example:
The code depicted below will give us the maximum quantity in stock in the products table.
Conclusion
The aggregate function in SQL is very powerful in the database. It serves the same purpose as
their equivalents in MS Excel. In this article, we have seen several examples of aggregate
functions.
SQL Subquery
Janwang 1/03/2018 Mysql , Sql 1 Comments
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery is
usually added in the WHERE Clause of the SQL statement. Most of the time, a subquery
is used when you know how to search for a value using a SELECT statement, but do not
know the exact value in the database.
Subqueries can be used with the following SQL statements along with the comparision
operators like =, <, >, >=, <= etc.
FROM student_details
FROM student_details
but, if you do not know their names, then to get their id's you need to write the query
in this manner,
SELECT id, first_name
FROM student_details
FROM student_details
Subquery Output:
id first_name
-------- -------------
100 Rahul
102 Stephen
In the above sql statement, first the inner query is processed first and then the outer
query is processed.
Subquery Notes
Nested Subquery
1) You can nest as many queries you want but it is recommended not to nest more
than 16 subqueries in oracle
Non-Corelated Subquery
Subquery Errors
3) Minimize subquery errors: Use drag and drop, copy and paste to avoid running
subqueries with spelling and database typos. Watch your multiple field SELECT comma
use, extra or to few getting SQL error message "Incorrect syntax".
Adding SQL Subquery comments are good habit (/* your command comment */) which
can save you time, clarify your previous work .. results in less SQL headaches
1. Deletion
delete from r
where P;
deletes all tuples from the instructor relation. The instructor relation itself
still
exists, but it is empty.
• Delete all tuples in the instructor relation for those instructors associated
with
a department located in the Watson building.
from department
where building = ’Watson’);
This delete request first finds all departments located in Watson, and then
deletes all instructor tuples pertaining to those departments.
Note that, although we may delete tuples from only one relation at a time,
we may reference any number of relations in a select-from-
where nested in the
where clause of a delete. The delete request can contain a
nested select that
references the relation from which tuples are to be deleted. For example,
suppose
that we want to delete the records of all instructors with salary below the
average
at the university. We could write:
from instructor);
The delete statement first tests each tuple in the relation instructor to
check
whether the salary is less than the average salary of instructors in the
univer?sity. Then, all tuples that fail the test— that is, represent an
instructor with a
lower-than-average salary—are deleted. Performing all the tests before
perform?ing any deletion is important—if some tuples are deleted before
other tuples have been tested, the average salary may change, and the
final result of the delete
would depend on the order in which the tuples were processed!
2. Insertion
In this example, the values are specified in the order in which the
corresponding
attributes are listed in the relation schema. For the benefit of users who
may not
remember the order of the attributes, SQL allows the attributes to be
specified as
part of the insert statement. For example, the following
SQL insert statements are
identical in function to the preceding one:
More generally, we might want to insert tuples on the basis of the result of
a
query. Suppose that we want to make each student in the Music
department who
has earned more than 144 credit hours, an instructor in the Music
department,
with a salary of $18,000. We write:
select *
from student;
The tuple inserted by this request specified that a student with ID “3003”
is in the
Finance department, but the tot cred value for this student is not known.
Consider
the query:
select student
from student
where tot_cred > 45;
3. Updates
Suppose that annual salary increases are being made, and salaries of all
in?structors are to be increased by 5 percent. We write:
update instructor
set salary= salary * 1.05;
update instructor
set salary = salary * 1.05
where salary < 70000;
In general, the where clause of the update statement may contain any
construct
legal in the where clause of the select statement (including nested
selects). As
with insert and delete, a nested select within an update statement may
reference
the relation that is being updated. As before, SQL first tests all tuples in
the relation
to see whether they should be updated, and carries out the updates
afterward.
For example, we can write the request “Give a 5 percent salary raise to
instructors
whose salary is less than average” as follows:
update instructor
set salary = salary * 1.05
where salary < (select avg (salary)
from instructor);
Let us now suppose that all instructors with salary over $100,000 receive
a
3 percent raise, whereas all others receive a 5 percent raise. We could
write two
update statements:
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
SQL provides a case construct that we can use to perform both the
updates
with a single update statement, avoiding the problem with the order of
updates.
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
case
when pred1 then result1
when pred2 then result2
...
when predn then resultn
else result0
end
The operation returns resulti , where i is the first of pred1, pred2,..., predn
that is
satisfied; if none of the predicates is satisfied, the operation returns
result0. Case
statements can be used in any place where a value is expected.
Scalar subqueries are also useful in SQL update statements, where they
can be
used in the set clause. Consider an update where we set the tot cred
attribute of
each student tuple to the sum of the credits of courses successfully
completed by
the student. We assume that a course is successfully completed if the
student has
a grade that is not ’F’ or null. To specify this update, we need to use a
subquery
in the set clause, as shown below:
update student S
set tot_cred = (
select sum(credits)
from takes natural join course
where [Link]= [Link] and
[Link] <> ’F’ and
[Link] is not null);
Observe that the subquery uses a correlation variable S from
the update statement.
In case a student has not successfully completed any course, the above
update
statement would set the tot cred attribute value to null. To set the value
to 0
instead, we could use another update statement to replace null values by
0; a
better alternative is to replace the clause “select sum(credits)” in the
preceding
subquery by the following select clause using a case expression:
select case
when sum(credits) is not null then sum(credits)
else 0
end
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
Consider the two tables below:
Student
StudentCourse
1. INNER JOIN: The INNER JOIN keyword selects all rows from both the
tables as long as the condition satisfies. This keyword will create the result-set
by combining all rows from both the tables where the condition satisfies i.e
value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(INNER JOIN)
1.
This query will show the names and age of students enrolled in
different courses.
1. LEFT JOIN: This join returns all the rows of the table on the left side of the
join and matching rows for the table on the right side of join. The rows for
which there is no matching row on right side, the result-set will contain null.
LEFT JOIN is also known as LEFT OUTER [Link]:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(RIGHT JOIN):
1.
SELECT [Link],StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
1. FULL JOIN: FULL JOIN creates the result-set by combining result of both
LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from
both the tables. The rows for which there is no matching, the result-set will
contain NULL [Link]:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
NAME COURSE_ID
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
SQL | Views
Difficulty Level : Easy
Last Updated : 01 Sep, 2020
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in
a real table in the database. We can create a view by selecting fields from one or more
tables present in the database. A View can either have all the rows of a table or specific
rows based on certain condition.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails
StudentMarks
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a
single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Creating View from multiple tables: In this example we will create a View
named MarksView from two tables StudentDetails and StudentMarks. To
create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:
CREATE VIEW MarksView AS
SELECT [Link], [Link],
[Link]
FROM StudentDetails, StudentMarks
WHERE [Link] = [Link];
To display data of View MarksView:
SELECT * FROM MarksView;
Output:
DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any
more? Obviously we will want to delete it. SQL allows us to delete an existing View. We
can delete or drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;
SQL - Transactions
Advertisements
Previous Page
Next Page
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all
the previous operations are rolled back to their former state.
Consistency − ensures that the database properly changes states upon a
successfully committed transaction.
Isolation − enables transactions to operate independently of and transparent to
each other.
Durability − ensures that the result or effect of a committed transaction persists
in case of a system failure.
Transaction Control
The following commands are used to control transactions.
COMMIT − to save the changes.
ROLLBACK − to roll back the changes.
SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
SET TRANSACTION − Places a name on a transaction.
Following is an example which would delete those records from the table which have
age = 25 and then COMMIT the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;
Thus, two rows from the table would be deleted and the SELECT statement would
produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Thus, the delete operation would not impact the table and the SELECT statement
would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 that the three deletions have taken place, let us assume that 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 −
SQL> ROLLBACK TO SP2;
Rollback complete.
Notice that only the first deletion took place since you rolled back to SP2.
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
6 rows selected.
1. Binary Datatypes :
There are four subtypes of this datatype which are given below :
2. Exact Numeric Datatype :
There are nine subtypes which are given below in the table. The table contains the range
of data in a particular type.
Authorization is finding out if the person, once identified, is permitted to have the
resource.
Authorization explains that what you can do and is handled through the DBMS unless
external security procedures are available.
Database management system allows DBA to give different access rights to the users
as per their requirements.
Basic Authorization we can use any one form or combination of the following basic
forms of authorizations
Granting of privileges:
ii. An authorized user may pass on this authorization to other [Link] process is
called as ganting of privileges.
iii. Syntax:
iv. Example:
The following grant statement grants user U1,U2 and U3 the select privilege on
Emp_Salary relation:
GRANT select
ON Emp_Salary
TO U1,U2 and U3.
Revoking of privileges:
i. We can reject the privileges given to particular user with help of revoke statement.
iii. Syntax:
REVOKE <privilege list>
ON<relation name or view name>
FROM <user/role list>[restrict/cascade]
iv. Example:
The revocation of privileges from user or role may cause other user or roles also have
to loose that [Link] behavior is called cascading of the revoke.
Revoke select
ON Emp_Salary
FROM U1,U2,U3.
i. Reference privileges:
Example: Allow user U1 to create relation that references key ‘Eid’ of Emp_Salary
relation.
GRANT REFERENCES(Eid)
ON Emp_Salary
TO U1
Thus,only user who has execute privilege on a function Create_Acc() can call function.
GRANT EXECUTE
ON Create_Acc
TO U1.