You are on page 1of 39

Integrity Constraints

o Integrity constraints are a set of rules. It is used to maintain the quality of


information.
o Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the
database.

Types of Integrity Constraint

1. Domain constraints

o Domain constraints can be defined as the definition of a valid set of values for
an attribute.
o The data type of domain includes string, character, integer, time, date, currency,
etc. The value of the attribute must be available in the corresponding domain.

Example:
2. Entity integrity constraints

o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those
rows.
o A table can contain a null value other than the primary key field.

Example:

3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.


o In the Referential integrity constraints, if a foreign key in Table 1 refers to the
Primary Key of Table 2, then every value of the Foreign Key in Table 1 must be
null or be available in Table 2.
Example:

4. Key constraints

o Keys are the entity set that is used to identify an entity within its entity set
uniquely.
o An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and null value in the relational
table.

Example:

65.3M
1.2K
Difference between JDK, JRE, and JVM
1, ENFORCING INTEGRITY CONSTRAINTS
ENROLLED LIST WITH STUDENT TABLE

2, QUERYING RELATIONAL DATA


SELECT *FROM TABLE NAME WHERE COL NAME WITH
OPERATION

3, LOGICAL DATABASE DESIGN


ENTITY SETS TO TABLE
RELATIONSHIP SETS TO TABLE

4, INTRODUCTION TO VIEWS
CREATE VIEW TABLE NAME (COLA)
AS SELECT COLA WHERE COLA>1
CREATE VIEW TABLE NAME (COLA,COLB)
AS SELECT COLA,COLB WHERE COLA>COLB

ENFORCING INTEGRITY CONSTRAINTS


As we observed earlier, ICs are specified when a relation is created and enforced when a relation is
modified.

The impact of domain, PRIMARY KEY, and UNIQUE constraints is straightforward:

If an insert, delete, or update command causes a violation, it is rejected.

Every potential Ie violation is generally checked at the end of each SQL statement execution,
although it can be deferred until the end of the transaction executing the statement, as we will see
in Section 3.3.1. Consider the instance 51 of Students shown in Figure 3.1.

The following insertion violates the primary key constraint because there is already a tuple with the
s'id 53688, and it will be rejected by the DBMS:

INSERT INTO Students (sid, name, login, age, gpa)

VALUES (53688, 'Mike', 'mike@ee', 17,3.4)

The following insertion violates the constraint that the primary key cannot contain null:

INSERT INTO Students (sid, name, login, age, gpa)

VALUES (null, 'Mike', 'mike@ee', 17,3.4)

Of course, a similar problem arises whenever we try to insert a tuple with a value in a field that is
not in the domain associated with that field, that is, whenever we violate a domain constraint.
Deletion does not cause a violation of clornain, primary key or unique constraints. However, an
update can cause violations, sirnilar to an insertion:

UPDATE Students S

SET S.sid = 50000

WHERE S.sid = 53688 CHAPTER, 3 This update violates the primary key constraint because there is
already a tuple with sid 50000.

The impact of foreign key constraints is more complex because SQL sometimes tries to rectify a
foreign key constraint violation instead of simply rejecting the change. We discuss the referential
integrity enforcement steps taken by the DBMS in terms of our Enrolled and Students tables, with
the foreign key constraint that Enrolled. sid is a reference to (the primary key of) Students.

In addition to the instance 81 of Students, consider the instance of Enrolled shown in Figure 3.4.
Deletions of Enrolled tuples do not violate referential integrity, but insertions of Enrolled tuples
could.

The following insertion is illegal because there is no Students tuple with sid 51111:

INSERT

INTO Enrolled (cid, grade, studid)

VALUES ('Hindi101', 'B', 51111)

QUERYING RELATIONAL DATA


A relational database query (query, for short) is a question about the data, and the answer consists
of a new relation containing the result. For example, we might want to find all students younger
than 18 or all students enrolled in Reggae203.

A query language is a specialized language for writing queries.

SQL is the most popular commercial query language for a relational DBMS.

We now present some SQL examples that illustrate how easily relations can be queried. Consider
the instance of the Students relation shown in Figure 3.1.

We can retrieve rows corresponding to students who are younger than 18 with the following SQL
query:

SELECT *

FROM Students S

WHERE S.age < 18

The symbol ,*, means that we retain all fields of selected tuples in the result. Think of S as a variable
that takes on the value of each tuple in Students, one tuple after the other. The condition S. age < 18
in the WHERE clause specifies that we want to select only tuples in which the age field has a value
less than 18. This query evaluates to the relation

Students with age < 18 OIl Instance 51

This example illustrates that the domain of a field restricts the operations that are permitted on field
values, in addition to restricting the values that can appear in the field. The condition S. age < 18
involves an arithmetic comparison of an age value with an integer and is permissible because the
domain of age is the set of integers. On the other hand, a condition such as S.age = S."id does not
make sense because it compares an integer value with a string value, and this comparison is defined
to fail in SQL; a query containing this condition produces no answer tuples.

In addition to selecting a subset of tuples, a query can extract a subset of the

fields of each selected tuple. vVe can compute the names and logins of students

who are younger than 18 with the following query:

SELECT S.name, S.login

FROM Students S
WHERE S.age < 18

Figure 3.7 shows the answer to this query; it is obtained by applying the selection to the instance 81
of Students (to get the relation shown in Figure

3.6), followed by removing unwanted fields. Note that the order in which we

perform these operations does matter-if we remove unwanted fields first, we

cannot check the condition S. age < 18, which involves one of those fields.

We can also combine information in the Students and Enrolled relations. If we

want to obtain the names of all students who obtained an A and the id of the

course in which they got an A, we could write the following query:

SELECT S.name, E.cid

FROM Students S, Enrolled E

WHERE S.sid = E.studid AND E.grade = 'A'

This query can be understood as follows: "If there is a Students tuple Sand

an Enrolled tuple E such that S.sid = E.studid (so that S describes the student

who is enrolled in E) and E.grade = 'A', then print the student's name and

the course id." When evaluated on the instances of Students and Enrolled in

Figure 3.4, this query returns a single tuple

LOGICAL DATABASE DESIGN


ER TO RELATIONAL

The ER model is convenient for representing an initial, high-level databi'lse

design. Given an ER diagram describing a databa'3e, a standard approach is

taken to generating a relational database schema that closely approximates


the ER design. (The translation is approximate to the extent that we cannot

capture all the constraints implicit in the ER design using SQL, unless we use

certain SQL constraints that are costly to check.) We now describe how to

translate an ER diagram into a collection of tables with associated constraints,

that is, a relational database schema.

3.5.1 Entity Sets to Tables

the ER design. (The translation is approximate to the extent that we cannot capture all the
constraints implicit in the ER design using SQL, unless we use certain SQL constraints that are costly
to check.) We now describe how to translate an ER diagram into a collection of tables with
associated constraints, that is, a relational database schema. 3.5.1 Entity Sets to Tables An entity set
is mapped to a relation in a straightforward way: Each attribute of the entity set becomes an
attribute of the table. Note that we know both the domain of each attribute and the (primary) key of
an entity set. Consider the Employees entity set with attributes ssn, name, and lot shown in Figure
3.8. A possible instance of the Employees entity set, containing three

INTRODUCTION TO VIEWS
Creating view
A view can be created using the CREATE VIEW statement. We can create a view from
a single table or multiple tables.

1. CREATE VIEW view_name AS


2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;

2. Creating View from a single table


In this example, we create a View named DetailsView from the table Student_Detail.

Query:

1. CREATE VIEW DetailsView AS


2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.
1. SELECT * FROM DetailsView;

Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in the
SELECT statement.

In the given example, a view is created named Marks View from two tables
Student_Detail and Student_Marks.

Query:

1. CREATE VIEW MarksView AS


2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARK
S
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

1. SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.

Syntax

1. DROP VIEW view_name;

Example:

If we want to delete the View MarksView, we can do this as:

1. DROP VIEW MarksView;

destroying altering table views


Basic sql Querys
Basic SELECT Query

Here’s an example of possibly, the most commonly used query


in SQL:
SELECT *
FROM Pets;
Result:

+---------+-------------+-----------+-----------+------------+
| PetId | PetTypeId | OwnerId | PetName | DOB |
|---------+-------------+-----------+-----------+------------|
| 1 | 2 | 3 | Fluffy | 2020-11-20 |
| 2 | 3 | 3 | Fetch | 2019-08-16 |
| 3 | 2 | 2 | Scratch | 2018-10-01 |
| 4 | 3 | 3 | Wag | 2020-03-15 |
| 5 | 1 | 1 | Tweet | 2020-11-28 |
| 6 | 3 | 4 | Fluffy | 2020-09-17 |
| 7 | 3 | 2 | Bark | NULL |
| 8 | 2 | 4 | Meow | NULL |
+---------+-------------+-----------+-----------+------------+

This query selects all rows and all columns from the Pets table. This is
because the asterisk (*) wildcard selects all columns.

Select Column Names


For performance reasons, it’s usually best to avoid selecting all
columns unless you really need them. It’s usually better to select just
the columns you need.

Here’s an example.
SELECT PetId, PetName
FROM Pets;
Result:

+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 1 | Fluffy |
| 2 | Fetch |
| 3 | Scratch |
| 4 | Wag |
| 5 | Tweet |
| 6 | Fluffy |
| 7 | Bark |
| 8 | Meow |
+---------+-----------+

Filter the Results


You can add a WHERE clause to filter the results to just the rows you
need.
SELECT PetId, PetName
FROM Pets
WHERE PetName = 'Fluffy';
Result:

+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 1 | Fluffy |
| 6 | Fluffy |
+---------+-----------+

Here’s another example of filtering the results. This time we use the
greater than operator (>) to filter it by date.
SELECT PetName, DOB
FROM Pets
WHERE DOB > '2020-01-01';
Result:

+-----------+------------+
| PetName | DOB |
|-----------+------------|
| Fluffy | 2020-11-20 |
| Wag | 2020-03-15 |
| Tweet | 2020-11-28 |
| Fluffy | 2020-09-17 |
+-----------+------------+

You can swap the greater than operator to other operators, such as
the greater than or equals to operator (>=), less than operator (<), or
less than or equals to operator (<=).

You can also use the BETWEEN operator to filter the results to a specific
range (e.g. between two dates).
SELECT
PetName,
DOB
FROM Pets
WHERE DOB BETWEEN '2018-01-01' AND '2020-01-01';
Result:

+-----------+------------+
| PetName | DOB |
|-----------+------------|
| Fetch | 2019-08-16 |
| Scratch | 2018-10-01 |
+-----------+------------+

Sort the Results


You can add an ORDER BY clause to sort the rows that are returned by
the query.

Ascending Order

Use the ASC keyword to sort the results in ascending order. This is the
default value, so you can also omit this keyword if you want the
results in ascending order.
SELECT PetId, PetName
FROM Pets
ORDER BY PetName ASC;
Or:
SELECT PetId, PetName
FROM Pets
ORDER BY PetName;
Result:
+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 7 | Bark |
| 2 | Fetch |
| 1 | Fluffy |
| 6 | Fluffy |
| 8 | Meow |
| 3 | Scratch |
| 5 | Tweet |
| 4 | Wag |
+---------+-----------+

Descending Order

Use the DESC keyword to sort the results in descending order.


SELECT PetId, PetName
FROM Pets
ORDER BY PetName DESC;
Result:

+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 4 | Wag |
| 5 | Tweet |
| 3 | Scratch |
| 8 | Meow |
| 1 | Fluffy |
| 6 | Fluffy |
| 2 | Fetch |
| 7 | Bark |
+---------+-----------+

Sort by Multiple Columns

You can sort by multiple columns by listing each column, separated


by a comma.
SELECT PetId, PetName
FROM Pets
ORDER BY PetName ASC, PetId ASC;

SELECT PetId, PetName


FROM Pets
ORDER BY PetName ASC, PetId DESC;
Result:

+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 7 | Bark |
| 2 | Fetch |
| 1 | Fluffy |
| 6 | Fluffy |
| 8 | Meow |
| 3 | Scratch |
| 5 | Tweet |
| 4 | Wag |
+---------+-----------+
(8 rows affected)
+---------+-----------+
| PetId | PetName |
|---------+-----------|
| 7 | Bark |
| 2 | Fetch |
| 6 | Fluffy |
| 1 | Fluffy |
| 8 | Meow |
| 3 | Scratch |
| 5 | Tweet |
| 4 | Wag |
+---------+-----------+
(8 rows affected)

We can see that the two Fluffys are a different order in each result
(we can tell by looking at their PetId values). This is because
the PetName column was sorted first, then the PetId sorted any
duplicates from the first sorting.

introduction to nested queries


Select AVG (no of students) from class where teacher ID IN (
Select id from teacher
Where subject=’science’ OR subject=’maths’);

SELECT * FROM student


WHERE classID = (
SELECT id
FROM class
WHERE no of students = (
SELECT MAX (no of students)
FROM class));

There are mainly two types of nested queries:


 Independent Nested Queries: In independent nested queries,
query execution starts from innermost query to outermost queries.
The execution of inner query is independent of outer query, but the
result of inner query is used in execution of outer query. Various
operators like IN, NOT IN, ANY, ALL etc are used in writing
independent nested queries.

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’
or ‘DBMS’, we can write it with the help of independent nested
query and IN operator. From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use
these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME =
‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID


Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’
or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and
outer query will return those S_IDs for which C_ID is equal to any
member of set (C1 and C3 in this case). So, it will return S1, S2 and
S4.

Note: If we want to find out names of STUDENTs who have either


enrolled in ‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have


neither enrolled in ‘DSA’ nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3.
Second inner query will return those S_IDs for which C_ID is equal
to any member of set (C1 and C3 in this case) which are S1, S2
and S4. The outermost query will return those S_IDs where S_ID is
not a member of set (S1, S2 and S4). So it will return S3.

 Co-related Nested Queries: In co-related nested queries, the


output of inner query depends on the row which is being currently
executed in outer query. e.g.; If we want to find
out S_NAME of STUDENTs who are enrolled in C_ID ‘C1’, it can be
done with the help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where
S.S_ID=SC.S_ID and SC.C_ID=’C1’);

For each row of STUDENT S, it will find the rows


from STUDENT_COURSE where S.S_ID = SC.S_ID and
SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then inner query will
return true and corresponding S_ID will be returned as output.

This article has been contributed by Sonal Tuteja.


Correlated nested query:
Correlated subqueries are used for row-by-row processing. Each subquery
is executed once for every row of the outer query.
A correlated subquery is evaluated once for each row processed by the
parent statement. The parent statement can be a SELECT, UPDATE,
or DELETE statement.
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);
A correlated subquery is one way of reading every row in a table and
comparing values in each row against related data. It is used whenever a
subquery must return a different result or set of results for each candidate
row considered by the main query. In other words, you can use a correlated
subquery to answer a multipart question whose answer depends on the
value in each row processed by the parent statement.

Nested Subqueries Versus Correlated Subqueries :


With a normal nested subquery, the inner SELECT query runs first and
executes once, returning values to be used by the main query. A correlated
subquery, however, executes once for each candidate row considered by the
outer query. In other words, the inner query is driven by the outer query.
NOTE : You can also use the ANY and ALL operator in a correlated
subquery.
EXAMPLE of Correlated Subqueries : Find all the employees who earn
more than the average salary in their department.
SELECT last_name, salary, department_id
FROM employees outer
WHERE salary >
(SELECT AVG(salary)
FROM employees
WHERE department_id =
outer.department_id);
Other use of correlation are in UPDATE and DELETE
CORRELATED UPDATE :
UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column =
alias2.column);
Use a correlated subquery to update rows in one table based on rows from
another table.

CORRELATED DELETE :
DELETE FROM table1 alias1
WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows
from another table.

Using the EXISTS Operator :


The EXISTS operator tests for existence of rows in the results set of the
subquery. If a subquery row value is found the condition is
flagged TRUE and the search does not continue in the inner query, and if it
is not found then the condition is flagged FALSE and the search continues in
the inner query.
EXAMPLE of using EXIST operator :
Find employees who have at least one person reporting to them.
SELECT employee_id, last_name, job_id, department_id
FROM employees outer
WHERE EXISTS ( SELECT ’X’
FROM employees
WHERE manager_id =
outer.employee_id);
OUTPUT :

EXAMPLE of using NOT EXIST operator :


Find all departments that do not have any employees.
SELECT department_id, department_name
FROM departments d
WHERE NOT EXISTS (SELECT ’X’
FROM employees
WHERE department_id
= d.department_id);
OUTPUT :
(Q28) Count the number of sailors.
SELECT COUNT (*)
FROM Sailors S

SQL NULL Values


In SQL there may be some records in a table that do not have values or data for
every field. This could be possible because at a time of data entry information is
not available. So SQL supports a special value known as NULL which is used to
represent the values of attributes that may be unknown or not apply to a tuple.
SQL places a NULL value in the field in the absence of a user-defined value. For
example, the Apartment_number attribute of an address applies only to address
that are in apartment buildings and not to other types of residences.
Importance of NULL value:
 It is important to understand that a NULL value is different from a zero
value.
 A NULL value is used to represent a missing value, but that it usually has
one of three different interpretations:
 The value unknown (value exists but is not known)
 Value not available (exists but is purposely withheld)
 Attribute not applicable (undefined for this tuple)
 It is often not possible to determine which of the meanings is intended.
Hence, SQL does not distinguish between the different meanings of
NULL.
Principles of NULL values:

 Setting a NULL value is appropriate when the actual value is unknown,


or when a value would not be meaningful.
 A NULL value is not equivalent to a value of ZERO if the data type is a
number and is not equivalent to spaces if the data type is character.
 A NULL value can be inserted into columns of any data type.
 A NULL value will evaluate NULL in any expression.
 Suppose if any column has a NULL value, then UNIQUE, FOREIGN key,
CHECK constraints will ignore by SQL.
In general, each NULL value is considered to be different from every other
NULL in the database. When a NULL is involved in a comparison operation, the
result is considered to be UNKNOWN. Hence, SQL uses a three-valued logic with
values True, False, and Unknown. It is, therefore, necessary to define the results
of three-valued logical expressions when the logical connectives AND, OR, and
NOT are used.

How to test for NULL Values?


SQL allows queries that check whether an attribute value is NULL. Rather than
using = or to compare an attribute value to NULL, SQL uses IS and IS NOT. This is
because SQL considers each NULL value as being distinct from every other NULL
value, so equality comparison is not appropriate.
Now, consider the following Employee Table,
Suppose if we find the Fname, Lname of the Employee having no Super_ssn then
the query will be:
Query
SELECT Fname, Lname FROM Employee WHERE Super_ssn IS NULL;
Output:

Now if we find the Count of the number of Employees having Super_ssn.


Query:

SELECT COUNT(*) AS Count FROM Employee WHERE Super_ssn IS NOT NULL;


Output:

sql Query to Exclude Null Values


In this article, we will look at how to exclude Null Values from the table using
a SQL query.
Null Value:
A null value indicates no value. It means that the column value is absent in a row.
A null value is not the same as a blank space or a zero value. A zero value is an
integer and a blank space is a character while a null value is the one that has been
left blank.
To exclude the null values from a table we have to create a table with null values.
So, let us create a table.
Step 1: Creating table
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....);
Query:
CREATE TABLE Student(Name varchar(40),
Department varchar(30),Roll_No int, );
Using the above query student table is created in our database. The student table
has three fields Name, Department, and Roll Number of a student. To insert
values in the table we have to use the INSERT query.
Output:

Step 2: Insert Data into the Table


Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Query:
INSERT INTO Student
VALUES ('Rahul Sharma','Electronics',15),
('Soha Shaikh','Computer Science',NULL),
('Vivek Rao',NULL,31),
('Sonali Rane','Electronics',20);
Using the above query we have added the data to our table. We used the NULL
keyword to insert NULL values.
Output:
Step 3: View Table Data
We can print the data in the table using the SELECT query as below.
Syntax:
SELECT * FROM table_name
Query:
SELECT * FROM Student
The output will show the table with all the fields because we used ‘*’ in the query.
It means that select all fields within the table.
Output:

Step 4: Exclude Null Values


To exclude the null values from the table we need to use IS NOT NULL operator
with the WHERE clause.
 WHERE Clause:
 The WHERE clause is used to filter the records.
 It will extract those records that fulfill the condition.
 It can be used with SELECT, UPDATE, DELETE queries.
 IS NOT NULL Operator:
 This operator is used to test for non-empty values.
Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Query:
SELECT * FROM Student
WHERE Name IS NOT NULL
AND Department IS NOT NULL
AND Roll_No IS NOT NULL;
To exclude the null values from all the columns we used AND operator. AND
operator shows the record if all the conditions are true.
Output:

SQL Join
(Inner, Left, Right and Full Joins)
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 as follows:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN

Consider the two tables below:


Student

Studen t Course

The simplest Join is INNER JOIN.


A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. 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 the 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.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

Example Queries (INNER JOIN)


This query will show the names and age of students enrolled in different
courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM
Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches
rows for the table on the right side of the join. For the rows for which there is no
matching row on the right side, the result-set will contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.
Syntax:
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.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

Example Queries(LEFT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
C. 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 the
join. For the rows for which there is no matching row on the left side, the result-
set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
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.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the

same.
Example Queries(RIGHT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and
RIGHT JOIN. The result-set will contain all the rows from both tables. For the
rows for which there is no matching, the result-set will contain NULL values.

Syntax:
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.
Example Queries(FULL JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID

HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5
NAME COURSE_ID

NULL 4

The AND , OR Operator


The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.

Syntax
The basic syntax of the AND operator with a WHERE clause is as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using the AND operator

Consider the sample table ‘emp’

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7839 KING PRESIDENT – 17-NOV-81 5000 – 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 500 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 500 10
7566 JONES MANAGER 7839 02-APR-81 2975 – 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 – 20
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20
7369 SMITH CLERK 7902 17-DEC-80 800 500 20

IS NULL operator

All operations upon null values present in the table must be done using this ‘is null’
operator .we cannot compare null value using the assignment operator

Example
select * from emp
where comm is null
out put:……………………..
IS NOT NULL

select * from emp


where comm is not null;
O/P

NOT NULL Constraint

 Not all constraints prevents a column to contain null values

 Once not null is applied to a particular column, you cannot enter null values to that

column and restricted to maintain only some proper value other than null

 A not-null constraint cannot be applied at table level

Example

CREATE TABLE STUDENT


(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

NVL () NULL Function

 Using NVL function you can substitute a value in the place of NULL values.

 The substituted value then temporarily replaces the NULL values in your calculations or

expression. Remember that the substituted value only replaces the NULL value

temporarily for the session and does not affect the value stored in the table.

 Here is the syntax of NVL function.

NVL (exp, replacement-exp)


 As you can see NVL function takes two parameters exp and replacement exp. First

parameter exp can be a column name of a table or an arithmetic expression and the second

parameter replacement expression will be the value which you want to substitute when a

NULL value is encountered.

 Always remember the data type of both the parameters must match otherwise the compiler

will raise an error.

Example

SELECT NVL (comm, 500) FROM employees


WHERE salary>1000;
 On execution all the null values in the result set will get replaced by 500.

 Similarly we can use NVL null function while performing arithmetic expression.

 Again let’s take the same arithmetic expression which we used in the previous query where

we added 100 to the values of commission column.


SELECT NVL(comm,100), NVL(comm,100)+100 FROM employees WHERE salary>1000;

You might also like