0% found this document useful (0 votes)
35 views87 pages

2nd and 3rd Unit

Bsc notes

Uploaded by

srigopi1415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views87 pages

2nd and 3rd Unit

Bsc notes

Uploaded by

srigopi1415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

atomic domain in DBMS

A domain is the original sets of atomic values used to model


data. By atomic value, we mean that each value in
the domain is indivisible as far as the relational model is
concerned. For example: ... The domain of First Name is the
set of character strings that represents names of people.
Atomicity: The atomicity acid property in SQL. It means
either all the operations (insert, update, delete) inside a
transaction take place or none. Or you can say, all the
statements (insert, update, delete) inside a transaction are
either completed or rolled back.

Normalization
A large database defined as a single relation may result in data duplication. This
repetition of data may result in:

o Making relations very large.


o It isn't easy to maintain and update data as it would involve searching many
records in relation.
o Wastage and poor utilization of disk space and resources.
o The likelihood of errors and inconsistencies increases.

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.

Why do we need Normalization?

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.

Data modification anomalies can be categorized into three types:

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.

Types of Normal Forms:


Normalization works through a series of stages called Normal forms. The normal forms
apply to individual relations. The relation is said to be in particular normal form if it
satisfies constraints.

Following are the various types of Normal forms:


Normal Description
Form

1NF A relation is in 1NF if it contains an atomic value.

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.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

BCNF A stronger definition of 3NF is known as Boyce Codd's normal form.

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.

First Normal Form (1NF)


o A relation will be 1NF if it contains an atomic value.
o It states that an attribute of a table cannot hold multiple values. It must hold only single-
valued attribute.
o First normal form disallows the multi-valued attribute, composite attribute, and their
combinations.

Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute


EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully functional dependent on the
primary key

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

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30

47 English 35
83 Math 38

83 Computer 38

In the given table, non-prime attribute TEACHER_AGE is dependent on TEACHER_ID


which is a proper subset of a candidate key. That's why it violates the rule for 2NF.

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:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on

Candidate key: {EMP_ID}


Non-prime attributes: In the given table, all attributes except EMP_ID are non-
prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent


on EMP_ID. The non-prime attributes (EMP_STATE, EMP_CITY) transitively
dependent on super key(EMP_ID). It violates the rule of third normal form.

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:

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich
462007 MP Bhopal

Boyce Codd normal form (BCNF)


o BCNF is the advance version of 3NF. It is stricter than 3NF.
o A table is in BCNF if every functional dependency X → Y, X is the super key of the table.
o For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than one department.

EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate key: {EMP-ID, EMP-DEPT}

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 DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

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:

For the first table: EMP_ID


For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}

Fourth normal form (4NF)


o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued
dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then the
relation will be a multi-valued dependency.

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.

In the STUDENT relation, a student with STU_ID, 21 contains two


courses, Computer and Math and two hobbies, Dancing and Singing. So there is a
Multi-valued dependency on STU_ID, which leads to unnecessary repetition of data.
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

Fifth normal form (5NF)


o A relation is in 5NF if it is in 4NF and not contains any join dependency and joining
should be lossless.
o 5NF is satisfied when all the tables are broken into as many tables as possible in order to
avoid redundancy.
o 5NF is also known as Project-join normal form (PJ/NF).

SEMESTER SUBJECT

Semester 1 Computer

Semester 1 Math

Semester 1 Chemistry

Semester 2 Math

Example
SUBJECT LECTURER SEMESTER

Computer Anshika Semester 1

Computer John Semester 1

Math John Semester 1

Math Akash Semester 2

Chemistry Praveen Semester 1

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

SQL is a language to operate databases; it includes database creation, deletion,


fetching rows, modifying rows, etc. SQL is an ANSI (American National Standards
Institute) standard language, but there are many different versions of the SQL
language.

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 −

 MS SQL Server using T-SQL,


 Oracle using PL/SQL,
 MS Access version of SQL is called JET SQL (native format) etc.

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.

A Brief History of SQL


 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational
databases. He described a relational model for databases.
 1974 − Structured Query Language appeared.
 1978 − IBM worked to develop Codd's ideas and released a product named
System/R.
 1986 − IBM developed the first prototype of relational database and
standardized by ANSI. The first relational database was released by Relational
Software which later came to be known as Oracle.
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.
These components are −

 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 −

DDL - Data Definition Language

[Link]. Command & Description

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.

DML - Data Manipulation Language

[Link] Command & Description


.

1 SELECT
Retrieves certain records from one or more tables.

INSERT
2
Creates a record.

UPDATE
3
Modifies records.

4 DELETE
Deletes records.

DCL - Data Control Language

[Link] Command & Description


.

1 GRANT
Gives a privilege to user.

REVOKE
2
Takes back privileges granted from user.

dditional Basic Operations of SQL

The Rename Operation

 Consider the query below:

o select name, courseid

o from instructor, teaches

o where [Link] = [Link];

 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:

o select name as instructor_name, course id

o from instructor, teaches

o where [Link] = [Link];

'as' clause - Renaming relations

 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.

o select [Link], [Link]

o from instructor as T, teaches as S

o where [Link] = [Link];

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)

o select distinct [Link]

o from instructor as T, instructor as S

o where [Link] > [Link] and [Link] = ’Biology’;


 In the above query, T and S can be thought as aliases, that is as
alternative names, for the relation instructor

String Operations of SQL

 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:

0. Percent (%): The % character matches any substring

1. Underscore (_): The character matches any character

 To illustrate pattern matching, we consider the following examples:

0. ’Intro%’ matches any string beginning with “Intro”.


1. ’%Comp%’ matches any string containing “Comp” as a substring, for
example, ’Intro. to Computer Science’, and ’Computational Biology’.

2. ’_ _ _ ’ matches any string of exactly three characters.

3. ’_ _ _%’ matches any string of at least three characters.

 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

3. where building like ’%Watson%’;

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.

Q . Write a query that matches all strings beginning with “ab%cd”.

1. like ’ab\%cd%’ escape ’\’

Q . Write a query that matches all strings beginning with “ab\cd”.

1. like ’ab\\cd%’ escape ’\’

Q . Write a query to select all attributes of relation instructor.

1. select *

2. from instructor;

Ordering the Display of Tuples

 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.
 Ordering can be performed on multiple attributes.

Q . To list in alphabetic order all instructors in the Physics department

1. select name

2. from instructor

3. where deptname = ’Physics’

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

3. order by salary desc, name asc;

Where Clause Predicates

 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

3. where salary between 90000 and 100000;

Q . Find the instructor names and the courses they taught for all instructors in
the Biology department who have taught some course.

 teaches(ID, course_id, sec_id, semester, year)

 instructor(ID, name, dept_name, salary)

1. select name, courseid

2. from instructor, teaches

3. where [Link] = [Link] and dept name = ’Biology’;

1. Second way of writing the query:

2. select name, course id

3. from instructor, teaches


4. where ([Link], dept name) = ([Link], ’Biology’);

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

2. where semester = ’Fall’ and year = 2009)

3. union

4. (select courseid

5. from section

6. where semester = ’Spring’ and year = 2010);

7.
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:

0. (select courseid

1. from section

2. where semester = ’Fall’ and year = 2009)

3. union all

4. (select courseid

5. from section

6. where semester = ’Spring’ and year = 2010);

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

2. where semester = ’Fall’ and year = 2009)

3. intersect
4. (select courseid

5. from section

6. where semester = ’Spring’ and year = 2010);

7.

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:

0. (select courseid

1. from section

2. where semester = ’Fall’ and year = 2009)

3. intersect all

4. (select courseid

5. from section

6. where semester = ’Spring’ and year = 2010);

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

 where semester = ’Fall’ and year= 2009)

 except

 (select courseid

 from section

 where semester = ’Spring’ and year= 2010)

 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.

 If we want to retain duplicates, we must write except all in place of


except:

 (select courseid

 from section

 where semester = ’Fall’ and year= 2009)

 except all

 (select courseid

 from section

 where semester = ’Spring’ and year= 2010)


SET Operators in SQL
SET operators are special type of operators which are used to combine the result of two
queries.

Operators covered under SET operators are:

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:

1. The number and order of columns must be the same.


2. Data types must be compatible.
Let us see each of the SET operators in more detail with the help of examples.

All the examples will be written using the MySQL database.

Consider we have the following tables with the given data.

Table 1: t_employees

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

Table 2: t2_employees

ID Name Department Salary Year_of_Experience

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1


Table 3: t_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

Table 4: t2_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

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:

1. mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;

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.

You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1


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:

1. mysql> SELECT *FROM t_students UNION SELECT *FROM t2_students;

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.

You will get the following output:

ID Name Department Salary Year_of_Experience

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

2 Ishwari Dixit Delhi 86 Hindi

4 Pakhi Arora Surat 70 Sanskrit

6 Jayshree Patel Pune 91 Maths

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:

1. mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;

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.

You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1


3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

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:

1. mysql> SELECT *FROM t_students UNION ALL SELECT *FROM t2_students;

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.

You will get the following output:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English


7 Prachi Jaiswal Gurugram 96 Hindi

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

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:

1. mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;

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.

You will get the following output:

ID Name Hometown Percentage Favourite_Subject


2 Abhishek Pawar Production 45000 1

4 Shubham Mahale Accounts 57000 2

6 Bhushan Wagh R&D 75000 2

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:

1. mysql> SELECT *FROM t_students INTERSECT SELECT *FROM t2_students;

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.

You will get the following output:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

3 Anuja Rajput Jaipur 78 History

5 Renuka Deshmukh Panipat 90 Biology

7 Prachi Jaiswal Gurugram 96 Hindi

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:

1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;

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.

You will get the following output:

ID Name Department Salary

1 Aakash Singh Development 72000

3 Pranav Deshmukh HR 59900

5 Sunil Kulkarni Development 87000

7 Paras Jaiswal Marketing 32000

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:

1. mysql> SELECT *FROM t_students MINUS SELECT *FROM t2_students;


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.

You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Harshada Sharma Kanpur 92 Chemistry

4 Pranali Singh Nashik 88 Geography

6 Swati Kumari Faridabad 93 English

Since we have performed a minus operation between both the tables, so only the
Unmatched records from both the tables are displayed.

SQL NULL Values


❮ PreviousNext ❯

What is a NULL Value?


A field with a NULL value is a field with no value.

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!

How to Test for NULL Values?


It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
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;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerI CustomerNam ContactNam Address City PostalCod Country


D e e e

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 German


Futterkiste y

2 Ana Trujillo Ana Trujillo Avda. de la Méxic 05021 Mexico


Emparedados y Constitución o D.F.
helados 2222

3 Antonio Antonio Mataderos Méxic 05023 Mexico


Moreno Moreno 2312 o D.F.
Taquería

4 Around the Thomas 120 Hanover Londo WA1 1DP UK


Horn Hardy Sq. n

5 Berglunds Christina Berguvsväge Luleå S-958 22 Sweden


snabbköp Berglund n8

The IS NULL Operator


The IS NULL operator is used to test for empty values (NULL values).

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 IS NOT NULL Operator


The IS NOT NULL operator is used to test for non-empty values (NOT 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.

What is an Aggregate Function in SQL?

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.

Various types of SQL aggregate functions are:

 Count()

 Sum()

 Avg()

 Min()

 Max()
COUNT() Function

The COUNT() function returns the number of rows in a database table.

Syntax:

COUNT(*)

or

COUNT( [ALL|DISTINCT] expression )

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.

This will produce the following result.


The below-given command will display those product ids where the unit price is greater than 4.

This will display the following result.

Let's look at how we can use GROUP BY and HAVING functions with the COUNT function.

Consider the following dataset:

The SQL command given below will list the number of customers in each city.
This will produce the following results:

SUM() Function

The SUM() function returns the total sum of a numeric column.

Syntax:

SUM()

or

SUM( [ALL|DISTINCT] expression )

Example:
The following SQL statement finds the sum of the "unit price" fields in the "products" table:

This will produce the following result.

Let’s look at how we can use GROUP BY and HAVING functions with the SUM function.

Consider the following dataset:

The SQL command below will list the number of customers in each city, having a sum of points
greater than 3000.

This will produce the following result:


AVG() Function

The AVG() function calculates the average of a set of values.

Syntax:

AVG()

or

AVG( [ALL|DISTINCT] expression )

Example:

The following SQL command calculates the average quantity in stock.

This will produce the following result.


MIN() Function

The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL values.

Syntax:

MIN()

or

MIN( [ALL|DISTINCT] expression )

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

AVG( [ALL|DISTINCT] expression )

Example:

The code depicted below will give us the maximum quantity in stock in the products table.

This will produce the following result.

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 are an alternate way of returning data from multiple tables.

Subqueries can be used with the following SQL statements along with the comparision
operators like =, <, >, >=, <= etc.

SQL Subquery Example:


1) Usually, a subquery should return only one record, but sometimes it can also return
multiple records when used with operators LIKE IN, NOT IN in the where clause. The
query syntax would be like,

SELECT first_name, last_name, subject

FROM student_details

WHERE games NOT IN ('Cricket', 'Football');

Subquery output would be similar to:


first_name last_name subject
------------- ------------- ----------
Shekar Gowda Badminton
Priya Chandra Chess
2) Lets consider the student_details table which we have used earlier. If you know the
name of the students who are studying science subject, you can get their id's by using
this query below,

SELECT id, first_name

FROM student_details

WHERE first_name IN ('Rahul', 'Stephen');

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

WHERE first_name IN (SELECT first_name

FROM student_details

WHERE subject= 'Science');

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.

SQL Subquery; INSERT Statement


3) Subquery can be used with INSERT statement to add rows of data from one or more
tables to another table. Lets try to group all the students who study Maths in a table
'maths_group'.

INSERT INTO maths_group(id, name)

SELECT id, first_name || ' ' || last_name

FROM student_details WHERE subject= 'Maths'

SQL Subquery; SELECT Statement


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.

select p.product_name, p.supplier_name, (select order_id from

order_items where product_id = 101) as order_id from product p

where p.product_id = 101

product_name supplier_name order_id


------------------ ------------------ ----------
Television Onida 5103
Correlated Subquery
A query is called correlated subquery 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.

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);

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

2) If a subquery is not dependent on the outer query it is called a non-correlated


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".

SQL Subquery Comments

Adding SQL Subquery comments are good habit (/* your command comment */) which
can save you time, clarify your previous work .. results in less SQL headaches

Modification of the Database


We have restricted our attention until now to the extraction of information
from
the database. Now, we show how to add,remove, or change information
with SQL.

1. Deletion

A delete request is expressed in much the same way as a query. We can


delete only
whole tuples; we cannot delete values on only particular attributes. SQL
expresses
a deletion by

delete from r
where P;

where P represents a predicate and r represents a relation.


The delete statement
first finds all tuples t in r for which P(t) is true, and then deletes them
from r. The
where clause can be omitted, in which case all tuples in r are deleted.

Note that a delete command operates on only one relation. If we want to


delete
tuples from several relations, we must use one delete command for each
relation.
The predicate in the where clause may be as complex as a select
command’s
where clause. At the other extreme, the where clause may be empty.
The request

delete from instructor;

deletes all tuples from the instructor relation. The instructor relation itself
still
exists, but it is empty.

Here are examples of SQL delete requests:

• Delete all tuples in the instructor relation pertaining to instructors in the


Finance department.

delete from instructor


where dept_name= ’Finance’;
• Delete all instructors with a salary between $13,000 and $15,000.

delete from instructor


where salary between 13000 and 15000;

• Delete all tuples in the instructor relation for those instructors associated
with
a department located in the Watson building.

delete from instructor


where dept_name in (select dept_name

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:

delete from instructor


where salary< (select avg (salary)

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

To insert data into a relation, we either specify a tuple to be inserted or


write a
query whose result is a set of tuples to be inserted. Obviously, the
attribute values
for inserted tuples must be members of the corresponding attribute’s
domain.
Similarly, tuples inserted must have the correct number of attributes.

The simplest insert statement is a request to insert one tuple. Suppose


that
we wish to insert the fact that there is a course CS-437 in the Computer
Science
department with title “Database Systems”, and 4 credit hours. We write:

insert into course

values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

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:

insert into course (course_id, title, dept_name, credits)

values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

insert into course (title, course_id, credits, dept_name)


values (’Database Systems’, ’CS-437’, 4, ’Comp. Sci.’);

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:

insert into instructor

select ID, name, dept_name, 18000


from student
where dept_name = ’Music’ and tot_cred > 144;

Instead of specifying a tuple as we did earlier in this section, we use


a select to
specify a set of tuples. SQL evaluates the select statement first, giving a
set of
tuples that is then inserted into the instructor relation. Each tuple has an
ID, a
name, a dept name (Music), and an salary of $18,000.

It is important that we evaluate the select statement fully before we carry


out any insertions. If we carry out some insertions even as
the select statement is
being evaluated, a request such as:

insert into student

select *
from student;

might insert an infinite number of tuples, if the primary key constraint on


student
were absent. Without the primary key constraint, the request would insert
the
first tuple in student again, creating a second copy of the tuple. Since this
second
copy is part of student now, the select statement may find it, and a third
copy
would be inserted into student. The select statement may then find this
third
copy and insert a fourth copy, and so on, forever. Evaluating the select
statement
completely before performing insertions avoids such problems. Thus, the
above
insert statement would simply duplicate every tuple in the student
relation, if the
relation did not have a primary key constraint.

Our discussion of the insert statement considered only examples in which


a value is given for every attribute in inserted tuples. It is possible for
inserted
tuples to be given values on only some attributes of the schema. The
remaining
attributes are assigned a null value denoted by null. Consider the request:

insert into student

values (’3003’, ’Green’, ’Finance’, null);

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;

Since the tot_cred value of student “3003” is not known, we cannot


determine
whether it is greater than 45.

Most relational database products have special “bulk loader” utilities to


insert
a large set of tuples into a relation. These utilities allow data to be read
from
formatted text files, and can execute much faster than an equivalent
sequence of
insert statements.

3. Updates

In certain situations, we may wish to change a value in a tuple without


changing
all values in the tuple. For this purpose, the update statement can be
used. As we
could for insert and delete, we can choose the tuples to be updated by
using a
query.

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;

The preceding update statement is applied once to each of the tuples in


instructor
relation.

If a salary increase is to be paid only to instructors with salary of less than


$70,000, we can write:

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;

Note that the order of the two update statements is important. If we


changed the
order of the two statements, an instructor with a salary just under
$100,000 would
receive an over 8 percent raise.

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

The general form of the case statement is as follows.

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

SQL | Join (Inner, Left, Right and Full


Joins)
 Difficulty Level : Easy
 Last Updated : 22 Apr, 2022
A SQL Join statement is used to combine data or rows from two or more tables based on
a common field between them. Different types of Joins are:

 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
Consider the two tables below:

Student
StudentCourse

The simplest Join is INNER JOIN.

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also write JOIN instead of INNER JOIN. JOIN is same as
INNER JOIN.

1.
Example Queries(INNER JOIN)
1.
 This query will show the names and age of students enrolled in
different courses.

SELECT StudentCourse.COURSE_ID, [Link], [Link] FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
 Output:

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are
same.
1.
Example Queries(LEFT JOIN):
1.
SELECT [Link],StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:
1. RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the
rows of the table on the right side of the join and matching rows for the table
on the left side of join. The rows for which there is no matching row on left
side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER [Link]:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1. Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both
are same.

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;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
1.
1.
Example Queries(FULL JOIN):
1.
SELECT [Link],StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
1. Output:

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;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
Examples:
 Creating View from a single table:
 In this example we will create a View named DetailsView from the
table StudentDetails.
Query:
 CREATE VIEW DetailsView AS
 SELECT NAME, ADDRESS
 FROM StudentDetails
 WHERE S_ID < 5;
To see the data in the View, we can query the view in the same
manner as we query a table.
SELECT * FROM DetailsView;
Output:

 In this example, we will create a view named StudentNames from


the table StudentDetails.
Query:
 CREATE VIEW StudentNames AS
 SELECT S_ID, NAME
 FROM StudentDetails
 ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

 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;

view_name: Name of the View which we want to delete.


For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these
conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using
multiple tables then we will not be allowed to update the view.
 We can use the CREATE OR REPLACE VIEW statement to add or remove
fields from a view.
Syntax:
 CREATE OR REPLACE VIEW view_name AS
 SELECT column1,coulmn2,..
 FROM table_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 [Link], [Link],
[Link], [Link]
FROM StudentDetails, StudentMarks
WHERE [Link] = [Link];
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

 Inserting a row in a view:


We can insert a row in a View in a same way as we do in a table. We can use
the INSERT INTO statement of SQL to insert a row in a [Link]:
 INSERT INTO view_name(column1, column2 , column3,..)
 VALUES(value1, value2, value3..);

 view_name: Name of the View


Example:
In the below example we will insert a new row in the View DetailsView which
we have created above in the example of “creating views from a single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:
 Deleting a row from a View:
Deleting rows from a view is also as simple as deleting rows from a table. We
can use the DELETE statement of SQL to delete rows from a view. Also
deleting a row from a view first delete the row from the actual table and the
change is then reflected in the [Link]:
 DELETE FROM view_name
 WHERE condition;

 view_name:Name of view from where we want to delete rows


 condition: Condition to select rows
Example:
In this example we will delete the last row from the view DetailsView which
we just added in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

WITH CHECK OPTION


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

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.
A transaction is the propagation of one or more changes to the database. For example,
if you are creating a record or updating a record or deleting a record from the table,
then you are performing a transaction on that table. It is important to control these
transactions to ensure the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of
them together as a part of a transaction.

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.

Transactional Control Commands


Transactional control commands are only used with the DML Commands such as -
INSERT, UPDATE and DELETE only. They cannot be used while creating tables or
dropping them because these operations are automatically committed in the database.

The COMMIT Command


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 |
+----+----------+-----+-----------+----------+

The ROLLBACK Command


The ROLLBACK command is the transactional command used to undo transactions
that have not already been saved to the database. This command can only be used to
undo transactions since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
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
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 |
+----+----------+-----+-----------+----------+

The SAVEPOINT Command


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a
certain point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the
transactional statements. The ROLLBACK command is used to undo a group of
transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the
CUSTOMERS 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.
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 |
+----+----------+-----+-----------+----------+

The following code block contains the series of operations.


SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.

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.

The RELEASE SAVEPOINT Command


The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.
The syntax for a RELEASE SAVEPOINT command is as follows.
RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT.

The SET TRANSACTION Command


The SET TRANSACTION command can be used to initiate a database transaction.
This command is used to specify characteristics for the transaction that follows. For
example, you can specify a transaction to be read only or read write.
The syntax for a SET TRANSACTION command is as follows.
SET TRANSACTION [ READ WRITE | READ ONLY ];
SQL Integrity Constraints
Integrity Constraints are used to apply business rules for the database tables.
The constraints available in SQL are Foreign Key, Not Null, Unique, Check.
Constraints can be defined in two ways
1) The constraints can be specified immediately after the column definition. This is called column-level
definition.
2) The constraints can be specified after all the columns are defined. This is called table-level definition.
1) SQL Primary key:
This constraint defines a column or combination of columns which uniquely identifies each row in the
table.
Syntax to define a Primary key at column level:
column name datatype [CONSTRAINT constraint_name] PRIMARY KEY
Syntax to define a Primary key at table level:
[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2,..)
 column_name1, column_name2 are the names of the columns which define the primary Key.
 The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.
For Example: To create an employee table with Primary Key constraint, the query would be like.
Primary Key at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
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".

Foreign Key at column level:


CREATE TABLE product
( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
CREATE TABLE order_items
( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,
product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id),
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
Foreign Key at table level:
CREATE TABLE order_items
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
CONSTRAINT od_id_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id)
);
2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references primary key 'id'
within the same table, the query would be like,
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
mgr_id number(5) REFERENCES employee(id),
salary number(10),
location char(10)
);
3) SQL Not Null Constraint :
This constraint ensures all rows in the table contain a definite value for the column which is specified as
not null. Which means a null value is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOT NULL
For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
4) SQL Unique Key:
This constraint ensures that a column or a group of columns in each row have a distinct value. A
column(s) can have a null value but the values cannot be duplicated.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name] UNIQUE(column_name)
For Example: To create an employee table with Unique key, the query would be like,
Unique Key at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) UNIQUE
);
or
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) CONSTRAINT loc_un UNIQUE
);
Unique Key at table level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT loc_un UNIQUE(location)
);
5) SQL Check Constraint :
This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can
be applied for a single column or a group of columns.
Syntax to define a Check constraint:
[CONSTRAINT constraint_name] CHECK (condition)
For Example: In the employee table to select the gender of a person, the query would be like
Check Constraint at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1) CHECK (gender in ('M','F')),
salary number(10),
location char(10)
);
Check Constraint at table level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1),
salary number(10),
location char(10),
CONSTRAINT gender_ck CHECK (gender in ('M','F'))
);

SQL Data Types


 Difficulty Level : Basic
 Last Updated : 24 Aug, 2021
Like in other programming languages, SQL also has certain datatypes available. A brief
idea of all the datatypes are discussed below.

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.

3. Approximate Numeric Datatype :


The subtypes of this datatype are given in the table with the range.

4. Character String Datatype :


The subtypes are given in below table –
5. Unicode Character String Datatype :
The details are given in below table –

6. Date and Time Datatype :


The details are given in below table.

 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

i. Resource authorization:-Authorization to access any system resource. e.g. sharing of


database, printer etc.

ii. Alternation Authorization:- Authorization to add attributes or delete attributes from


relations

iii. Drop Authorization:-Authorization to drop a relation.

 Granting of privileges:

i. A system privilege is the right to perform a particular action,or to perform an action


on any schema objects of a particular type.

ii. An authorized user may pass on this authorization to other [Link] process is
called as ganting of privileges.

iii. Syntax:

GRANT <privilege list>


ON<relation name or view name>
TO<user/role list>

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.

ii. To revoke an authorization, we use the 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.

 Some other types of Privileges:

i. Reference privileges:

SQL permits a user to declare foreign keys while creating relations.

Example: Allow user U1 to create relation that references key ‘Eid’ of Emp_Salary
relation.

GRANT REFERENCES(Eid)
ON Emp_Salary
TO U1

ii. Execute privileges:

This privileges authorizes a user to execute a function or procedure.

Thus,only user who has execute privilege on a function Create_Acc() can call function.

GRANT EXECUTE
ON Create_Acc
TO U1.

You might also like