Unit 6 SQL
Unit 6 SQL
SQL is used to control all of the functions that a DBMS provides for its users, including:
1. Data definition: SQL lets a user define the structure and organization of the stored data
and relationships among the stored data items.
2. Data retrieval: SQL allows a user or an application program to retrieve stored data from
the database and use it.
3. Data manipulation: SQL allows a user or an application program to update the database
by adding new data, removing old data, and modifying previously stored data.
4. Access control: SQL can be used to restrict a user's ability to retrieve, add, and modify
data, protecting stored data against unauthorized access.
5. Data sharing: SQL is used to coordinate data sharing by concurrent users, ensuring that
they do not interfere with one another.
6. Data integrity: SQL defines integrity constraints in the database, protecting it from
corruption due to inconsistent updates or system failures.
SQL is also called fourth generation language as a programmer can tell through about what he and she
want. SQL is an example of a transform oriented language or a language designed to use relations to
transform inputs into required outputs. The SQL commands are shown in below:
Data definition language (DDL)
We specify the database schema by a set of definition expressed by a special language called DDL. It is a
set of commands used to create a database structure; their commands are normally not used by a general
user who should access the database via an application. They are normally used by database administrator.
DDL also updates a special setup tables called a data dictionary. DDL concerned with creating and
modifying table.
The most important DDL statements in SQL are:
Sailors
Sid sname Rating age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
Now we want to select the content of the columns named "sname" and "age" from the table
Sailors. We use the following SELECT statement:
SELECT sname, age
FROM Sailors;
The result-set will look like this:
Sname Age
Ajaya 33
Robin 43
Ganga 28
Manoj 31
Rahul 22
Sanjaya 42
Raju 19
SELECT * Example
Now we want to select all the columns from the “Sailors " table. We use the following SELECT
statement:
SELECT * FROM Sailors
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want
to return for at least one of the columns.
AND And
OR Or
OR Operator Example:
Now we want to select only the Sailors with the first name equal to "Rahul" OR the rating equal to
9: We use the following SELECT statement:
SELECT * FROM Sailors
WHERE sname='Rahul' OR rating=9;
The result-set will look like this:
sid Sname Rating Age
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
Combining AND & OR
We can also combine AND and OR (use parenthesis to form complex expressions). Now we want to
select only the Sailors of rating equal to 9 AND the age equal to 31 OR to 42: We use the following
SELECT statement:
SELECT *
FROM Sailors
WHERE rating=9 AND (age=31 OR age=42)
The result-set will look like this:
sid Sname Rating Age
4 Manoj 9 31
9 Sanjaya 9 42
ORDER BY Example:
Now we want to select all the Sailors from the table above, however, we want to sort the
Sailors by their name. We use the following SELECT statement:
SELECT *
FROM Sailors
ORDER BY sname;
The result-set will look like this:
Sid Sname Rating Age
1 Ajaya 12 33
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
11 Raju 4 19
2 Robin 11 43
9 Sanjaya 9 42
ORDER BY DESC Example:
Now we want to select all the Sailors from the table above, however, we want to sort theSailors
descending by their name. We use the following SELECT statement:
SELECT *
FROM Sailors
ORDER BY sname DESC
The result-set will look like this:
Sid Sname Rating Age
9 Sanjaya 9 42
2 Robin 11 43
11 Raju 4 19
7 Rahul 7 22
4 Manoj 9 31
3 Ganga 32 28
1 Ajaya 12 33
SQL IN Operator:
The IN operator allows us to specify multiple values in a WHERE clause.
SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2...);
IN Operator Example:
The following SQL statement selects all Sailors with a rating of 9 or 11:
SELECT *
FROM Sailors
WHERE Rating IN (9, 11);
The result-set will look like this:
Sid sname Rating Age
2 Robin 11 43
4 Manoj 9 31
9 Sanjaya 9 42
Example:
SELECT *
FROM Sailors
WHERE sname LIKE ‘%ya’;
This SQL statement will match any Sailors first names that end with ‘ya’.
The result-set will look like this:
GROUP BY Clause:
The SQL GROUP BY clause is use to divide the rows in a table into groups. The GROUP BY
statement is used along with the SQL aggregate functions. In GROUP BY clause, the tuples with
same values are placed in one group.
Example: Find the age of the youngest sailor for each rating level.
SELECT rating, MIN(age)
FROM Sailors
GROUP BY rating;
The result-set will look like this: Rating Min(age)
4 19
7 22
9 31
11 43
12 33
32 28
This table display the minimum age of each group according to their rating.
NULL Values:
SQL allows the use of NULL values to indicate absence of information about the value of an
attribute. It has a special meaning in the database- the value of the column is not currently known
but its value may be known at a later time.
A special comparison operator IS NULL is used to test a column value for NULL. It has
following general format:
Value1 IS [NOT] NULL;
This comparison operator return true if value contains NULL, otherwise return false. The
optional NOT reverses the result.
Following syntax is illegal in SQL:
WHERE attribute=NULL;
Example: let’s take an instance S of Sailors,
S
sid sname Rating Age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya NULL NULL
11 Raju 4 19
22 Robin NULL NULL
32 Anish NULL NULL
Find all sailors that appear in S relation with NULL values for rating and age:
SELECT sname
FROM S4
Example:
Example1: Find the names of sailors who have reserved boat 41.
SELECT sname
FROM Sailors
WHERE sid IN ( SELECT sid
FROM Reserves
WHERE bid=41);
The result-set will look like this:
Sname
Ajaya
Raju
Example 2: Find the names of sailors who have reserved a red boat.
SELECT sname
FROM sailors
WHERE sid IN (SELECT sid
FROM Reservs
WHERE bid IN ( SELECT bid
FROM Boats
WHERE color=’Red’));
The result-set will look like this:
sname
Ajaya
Robin
Sanjaya
Views:
A database view is a logical table. It does not physically store data like tables but
represent data stored in underlying tables in different formats. A view does not require desk
space and we can use view in most places where a table can be used.
Since the views are derived from other tables thus when the data in its source tables are updated,
the view reflects the updates as well. They also can be used by DBA to enforce database
security.
Advantages of Views:
Database security: view allows users to access only those sections of database that
directly concerns them.
View provides data independence.
Easier querying
Shielding from change
Views provide group of users to access the data according to their criteria.
Vies allow the same data to be seen by different users in different ways at the same time.
1. 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.
Example 1: suppose we need to insert a new record of Sailors of id is11, name is “Rahul”, rating
is 9 and of age is 29 then we write following SQL query,
INSERT INTO Sailors VALUES (11,’Rahul’, 9, 29);
OR
INSERT INTO Sailors (sid, sname, rating, age)
VALUES (11,’Rahul’, 9, 29);
2. Deletion:
It is used to remove whole records or rows from the table.
Syntax:
DELETE FROM table_name
WHERE <predicate>
Example 1: suppose we need to remove all tuples of Sailors whose age is 32,
DELETE FROM Sailors
WHERE age=32;
Example 2: Remove all tuples of Sailors whose age is less than 30 and rating greater than 7,
DELETE FROM Sailors WHERE
age<32 AND rating>7;
3. Updates:
If we need to change a particular value in a tuple without changing all values in the tuple, then
for this purpose we use update operation.
Syntax:
UPDATE table_name
SET <column i> = <expression i>;
Example: suppose we need to increase the rating of those sailors whose age is greater than 40 by
20%, this can be write as,
Joined relations:
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
The types the different SQL JOINs are:
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
INNER JOIN:
It is most common type of join. An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
SQL INNER JOIN Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example 1: Find the sailor id, boat id, boat name, boat color of those sailors who have
reserved a red boat.
SELECT sailors.sid, sailors.sname, boats.bid, boats.bname,
boats.color FROM sailors INNER JOIN reserves INNER JOIN
boats
WHERE sailors.sid=reserves.sid AND reserves.bid=boats.bid;
The result-set will look like this:
Example 2: Find the name and age of those sailors who have reserved a Marine boat.
SELECT sailors.sname, sailors.age
FROM sailors INNER JOIN reserves INNER JOIN boats WHERE
sailors.sid=reserves.sid AND reserves.bid=boats.bid;
The result-set will look like this:
Relational Integrity Constraints are referred to conditions which must be present for a valid
relation.
Integrity constraints are a set of rules. It is used to maintain the quality of information.
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.
Thus, integrity constraint is used to guard against accidental damage to the database.
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:
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
Referential integrity ensures that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation to establish the relationship
between tables.
For referential integrity to hold in a relational database, any field in a table that is declared a foreign
key can contain either a null value, or only values from a parent table's primary key. For instance,
deleting a record that contains a value referred to by a foreign key in another table would break
referential integrity.
In relational model we often store data in different tables and put them together to get complete
example. For example, in PAYMENTS table we have only ROLLNO of the student. To get
remaining information about the student we have to use STUDENTS table.
STUDENTS
RollNO Name Address
1 Anisha Ktm
2 Bibek Pokhara
3 Nikey Lalitpur
4 Rashmi Bhaktapur PAYMENTS
RollNO Date Amount
1 12-03-2010 10000
3 06-08-2011 5000
2 02-07-2012 9000
Foreign Key 4 14-03-2013 15000
Thus for referential integrity a foreign key can have only two possible values- either the
relevant primary key or a null value. No other values are allowed.
Primary and candidate keys and foreign keys can be specified as parts of the SQL create table statement:
Example:
CREATE TABLE Sailors
(
sid integer not null, CREATE TABLE Boats
sname varchar(20),
rating integer, (
bid integer not null,
age integer,
bname varchar(20),
primary key (sid) color varchar(10),
primary key (bid)
)
)
CREATE TABLE Reserve
(
sid integer, bid integer,
rdate date,
foreign key (sid) references Sailors,
foreign key (bid) references Boats,
)
4. Key constraints
Keys are the entity set that is used to identify an entity within its entity set uniquely.
The various types of key constraints used in DBMS are described below.
Not null:
While creating a table if row lacks data for a particular column, it is said to be Null. By default the
table can contain null values. The enforcement of not null constraint in a table ensures that the table
contains some value. When a column is defined as not null as the column become mandatory columns
which imply that the user is forced to enter some data into column.
E.g.
);
Check:
This constraint can be defined to allow only the particular range of value for a column, it specify a
condition that each row must satisfy.
E.g.
);
Primary key(pk):
This constraint avoids duplication rows and doesn’t allow null value. A table can contain only one
primary key constraint. If a pk constraint is composed of more than one attribute, it is said to be composite
pk
E.g.
);
id int (10),
);
Unique key
Example:
);
To establish parent child relationship between two tables having a common column we make use of
referential integrity constraint.
To implement this we should define a column in the parent table as primary and the same column table as
a foreign key. Referencing to the corresponding to the parent table.
E.g.
);
);