2nd and 3rd Unit Notes
2nd and 3rd Unit Notes
Normalization
A large database defined as a single relation may result in data duplication.
This repetition of data may result in:
What is Normalization?
o Normalization is the process of organizing the data in the database.
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.
Normal Description
Form
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.
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
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.
So to make the above table into 4NF, we can decompose it into two tables:
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.
SQL Process
When you are executing an SQL command for any RDBMS, the system determines the
best way to carry out your request and SQL engine figures out how to interpret the
task.
There are various components included in this process.
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.
DELETE
4
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:
The as clause is particularly useful to replace a long relation name with a shortened
version that is more convenient to use elsewhere in the query.
Q. Find the names of all instructors whose salary is greater than at least one instructor in the
Biology department.
instructor (ID, name, dept_name, salary)
In the above query, T and S can be thought as aliases, that is as alternative names, for the
relation instructor
SQL specifies strings by enclosing them in single quotes, for example, ’Computer’.
A single quote character that is part of a string can be specified by using two single
quote characters; Example, the string "It’s right" can be specified by "It''s right".
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.
Pattern matching can be performed on strings, using the operator like. We describe patterns
by using two special characters:
2. ’%Comp%’ matches any string containing “Comp” as a substring, for example, ’Intro.
to Computer Science’, and ’Computational Biology’.
Patterns are case sensitive; that is, uppercase characters do not match lowercase
characters, or vice versa.
SQL allows us to search for mismatches instead of matches by using the not
like comparison operator.
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 '\'.
2. The escape character is used immediately before a special pattern character to indicate that
the special pattern character is to be treated like a normal character.
3. We define the escape character for a like comparison using the escape keyword.
1. select *
2. from instructor;
The order by clause causes the tuples in the result of a query to appear in sorted order.
By default, the order by clause lists items in ascending order. To specify the sort order, we
may specify desc for descending order or asc for ascending order.
1. select name
2. from instructor
4. order by name;
Q . To list the entire instructor relation in descending order of salary, if several instructors
have the same salary, we order them in ascending order by name.
1. select *
2. from instructor
SQL includes a between comparison operator to simplify where clauses that specify that a
value be less than or equal to some value and greater than or equal to some other value.
Q . To find the names of instructors with salary amounts between $90,000 and $100,000
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
1. (select courseid
2. from section
4. union
5. (select courseid
6. from section
8.
2. The union operation automatically eliminates duplicates, unlike the select clause.
3. If we want to retain all duplicates, we must write union all in place of union:
1. (select courseid
2. from section
4. union all
5. (select courseid
6. from section
Q . Illustrate use of 'intersect' -> To find the set of all courses taught in Fall 2009 as well as in
Spring 2010
1. (select courseid
2. from section
4. intersect
5. (select courseid
6. from section
8.
2. The intersect operation automatically eliminates duplicates, unlike the select clause.
3. If we want to retain all duplicates, we must write intersect all in place of union:
1. (select courseid
2. from section
4. intersect all
5. (select courseid
6. 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:
Let us see each of the SET operators in more detail with the help of
examples.
Table 1: t_employees
Table 2: t2_employees
Table 3: t_students
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.
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.
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:
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.
Example 2:
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.
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:
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:
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.
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!
We will have to use the IS NULL and IS NOT NULL operators instead.
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;
COUNT() Function
SUM() Function
AVG() Function
MIN() Function
View More
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.
The below-given command will display those product ids where the unit price
is greater than 4.
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.
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.
AVG() Function
Syntax:
AVG()
or
Example:
MIN() Function
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
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,
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.
4) A subquery can be used in the SELECT statement as follows. Lets use the product
and order_items table defined in the sql_joins section.
101
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;
where clause. At the other extreme, the where clause may be empty.
The request
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 S.ID= takes.ID and
takes.grade <> ’F’ and
takes.grade is not null);
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
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(LEFT JOIN):
1.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
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 Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
1.
Example Queries(FULL JOIN):
1.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
NAME COURSE_ID
HARSH 1
NAME COURSE_ID
PRATIK 2
RIYANKA 2
DEEP 3
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.
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;
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;
WHERE condition;
For example, if we want to update the view MarksView and
add the field AGE to this View from StudentMarks Table, we
can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:
Output:
The WITH CHECK OPTION clause in SQL is a very useful clause for
views. It is applicable to a updatable view. If the view is not updatable,
then there is no meaning of including this clause in the CREATE VIEW
statement.
The WITH CHECK OPTION clause is used to prevent the
insertion of rows in the view where the condition in the WHERE
clause in CREATE VIEW statement is not satisfied.
If we have used the WITH CHECK OPTION clause in the CREATE
VIEW statement, and if the UPDATE or INSERT clause does not
satisfy the conditions then they will return an error.
Example:
In the below example we are creating a View SampleView from
StudentDetails Table with WITH CHECK OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the
NAME column then it will give an error because the view is created with
the condition for NAME column as NOT NULL.
For example,though the View is updatable but then also the below
query for this View is not valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
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.
The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database.
The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database. The COMMIT command saves all the transactions to
the database since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
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 |
+----+----------+-----+-----------+----------+
Following is an example, which would delete those records from the table which have
the age = 25 and then ROLLBACK the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
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.
dept char(10),
age number(2),
salary number(10),
location char(10)
);
or
CREATE TABLE employee
( id number(5) CONSTRAINT emp_id_pk PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Primary Key at column level:
CREATE TABLE employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT emp_id_pk PRIMARY KEY (id)
);
Primary Key at table level:
CREATE TABLE employee
( id number(5), NOT NULL,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
ALTER TABLE employee ADD CONSTRAINT PK_EMPLOYEE_ID PRIMARY KEY (id)
);
2) SQL Foreign key or Referential Integrity :
This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a
relationship between two columns in the same table or between different tables. For a column to be
defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or
more columns can be defined as Foreign key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES
referenced_table_name(column_name);
For Example:
1) Lets use the "product" table and "order_items".
1. Binary Datatypes :
There are four subtypes of this datatype which are given below :
Granting 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:
iii. Syntax:
iv. Example:
The revocation of privileges from user or role may cause other user or
roles also have to loose that privileges.This behavior is called
cascading of the revoke.
Revoke select
ON Emp_Salary
FROM U1,U2,U3.
i. Reference privileges:
GRANT REFERENCES(Eid)
ON Emp_Salary
TO U1
GRANT EXECUTE
ON Create_Acc
TO U1.