You are on page 1of 33

CHAPTER4 RELATIONAL DATABASE MODEL 18 MARKS

Schema in DBMS
It is the overall description or the overall design of the database specified during the database design. Important
thing to be remembered here is it should not be changed frequently. Basically, it displays the record
types(entity),names of data items(attribute) but not the relation among the files.

Sub schema in DBMS


It can be defined as the subset or sub-level of schema that has the same properties as the schema. In simple words it
is just a way to see part of schema for the view. Well, it is interesting to note that it provides the users a window
through which the user can view only that part of database which is of matter of interest to him.

RELATIONAL MODEL

(RM) represents the database as a collection of relations.

A relation is nothing but a table of values.

Every row in the table represents a collection of related data values.

The data are represented as a set of relations.

In the relational model, data are stored as tables.

Properties:

In this each column of a table contains same kind of values.

Each data value is a simple number or a character string. That is a table must be in first
normal form.

All rows of a table are distinct.

The ordering of rows with in a table is immaterial.

The column of a table are assigned distinct names and the ordering of these columns in
immaterial.
Attribute: Each column in a Table. Attributes are the properties which define a relation. e.g.,
Student_Rollno, NAME,etc.

Tables – In the Relational model the, relations are saved in the table format. It is stored along
with its entities. A table has two properties rows and columns. Rows represent records and
columns represent attributes.

Tuple – It is nothing but a single row of a table, which contains a single record.

Relation Schema: A relation schema represents the name of the relation with its attributes.

Degree: The total number of attributes which in the relation is called the degree of the
relation.

Cardinality: Total number of rows present in the Table.

Column: The column represents the set of values for a specific attribute.

Relation instance – Relation instance is a finite set of tuples in the RDBMS system. Relation
instances never have duplicate tuples.

Relation key - Every row has one, two or multiple attributes, which is called relation key.

Attribute domain – Every attribute has some pre-defined value and scope which is known as
attribute domain

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.
1. Domain constraints
2. Key constraints
3. Entity Integrity constraints
4. Referential integrity constraints
Let discuss each of the above constraints in detail.
1. Domain constraints :
Three types
A) NULL CONSTRAINT: Database may have some attributes compulsory whose
value not null or blank.
B) CHECK CONSTRAINT:This satisfies that attribute value satisfies specific
condition ex. Mobile no should be of 10 digits ,Value enterd in database must be
valid or correct.
C) DEFAULT CONSTRAINT: Default keyword is used to add a default specified
value if no attribute value is provided by user.

1. Every domain must contain atomic values (smallest indivisible units) it means
composite and multi-valued attributes are not allowed.
2. We perform data type check here, which means when we assign a data type to a
column we limit the values that it can contain. Eg. If we assign the datatype of
attribute age as int, we cant give it values other then int datatype.
Example:

Explanation:
In the above relation, Name is a composite attribute and Phone is a multi-values
attribute, so it is violating domain constraint.
2. Key Constraints or Uniqueness Constraints :
1. These are called uniqueness constraints since it ensures that every tuple in the
relation should be unique.
2. A relation can have multiple keys or candidate keys(minimal superkey), out of which
we choose one of the keys as primary key, we don’t have any restriction on
choosing the primary key out of candidate keys, but it is suggested to go with the
candidate key with less number of attributes.
3. Null values are not allowed in the primary key, hence Not Null constraint is also a
part of key constraint.
Example:
Explanation:
In the above table, EID is the primary key, and first and the last tuple has the same
value in EID ie 01, so it is violating the key constraint.
3. Entity Integrity Constraints :
1. Entity Integrity constraints says that no primary key can take NULL value, since
using primary key we identify each tuple uniquely in a relation.
Example:

Explanation:
In the above relation, EID is made primary key, and the primary key cant take NULL
values but in the third tuple, the primary key is null, so it is a violating Entity Integrity
constraints.
4. Referential Integrity Constraints :
1. The Referential integrity constraints is specified between two relations or tables and
used to maintain the consistency among the tuples in two relations.
2. This constraint is enforced through foreign key, when an attribute in the foreign key
of relation R1 have the same domain(s) as the primary key of relation R2, then the
foreign key of R1 is said to reference or refer to the primary key of relation R2.
3. The values of the foreign key in a tuple of relation R1 can either take the values of
the primary key for some tuple in relation R2, or can take NULL values, but can’t be
empty.
Example:
R1

R2

Explanation:
In the above, DNO of the first relation is the foreign key, and DNO in the second
relation is the primary key. DNO = 22 in the foreign key of the first table is not allowed
since DNO = 22
is not defined in the primary key of the second relation. Therefore Referential integrity
constraints is violated here

Key
A key is an attribute or set of attributes which helps us in uniquely identifying
the rows of a table. It also helps in establishing relationship among tables. We
will now see how this is done with the help of examples.

Example: If we have the details of students of a classroom stored in Student


table as follows:
Now, from this classroom, if we want to call a student whose name is ‘Andrew’
we don't know which ‘Andrew’ to call as there are two students with the same
name. Also, we if know the age of student ‘Andrew’ we can’t distinguish
between both the students because both are having the same age. So, there
must some value through which we can distinguish and uniquely identify the
students. The ‘Roll_no’ attribute will help us in uniquely identifying the rows
in a table. We can say that ‘Roll_no’ is the key here. Now, if we know the
‘Roll_no’ of the student then there will be no confusion and we can easily select
the student from here.

Key can be of the following types:

● Super Key
● Candidate Key
● Primary Key
● Alternate Key
● Foreign Key

Super Key
A super key or simply key is a combination of all possible attribute which can
uniquely identify the rows(tuples) in a table. This means that a superkey may
have some extra attribute which isn't necessary for uniquely identifying the
rows in the table.

Example: In the given Student Table we can have the following keys as the
super key.
1. {Roll_no}
2. {Registration_no}
3. {Roll_no, Registration_no},
4. {Roll_no, Name}
5. {Name, Registration_no}
6. {Roll_no, Name, Registration_no}
All the above keys are able to uniquely identify each row. So, each of these keys
is super key. Here you can see that by using Roll_no only, we can uniquely
identify the rows but if you are making a super key, then you will try to find all
the possible cases of keys that can be used to identify data uniquely.

Candidate Key

A candidate key is a minimal super key or a super key with no redundant


attribute. It is called a minimal superkey because we select a candidate key
from a set of super key such that selected candidate key is the minimum
attribute required to uniquely identify the table. It is selected from the set of
the super key which means that all candidate keys are super key. Candidate
Keys are not allowed to have NULL values.

If the subset of the candidate key is a super key, then that candidate
key is not a valid candidate key.

Example: In the above example, we had 6 super keys but all of them cannot
become a candidate key. Only those super keys would become a candidate key
which have no redundant attributes.

1. {Roll_no}: This key doesn't have any redundant or repeating attribute.


So, it can be considered as a candidate key.
2. {Registration_no}: This key also doesn't have any repeating attribute.
So, it can be considered as a candidate key.
3. {Roll_no, Registration_no}: This key cannot be considered as a
candidate key because when we take the subset of this key we get two
attributes i.e Roll_no or Registration_no. Each of these attributes is the
candidate key. So, it is not a minimal super key. Hence, this key is not a
candidate key.
4. {Roll_no, Name}: This key cannot be considered as a candidate key
because when we take the subset of this key we get two attributes i.e.
Roll_no or Name. Roll_no is a candidate key. So, it is not a minimal
super key. Hence, this key is not a candidate key.
5. {Name, Registration_no}: This key cannot be considered as a
candidate key because when we take the subset of this key we get two
attributes i.e Registration_no or Name. Registration_no is a candidate
key. So, it is not a minimal super key. Hence, this key is not a candidate
key.
6. {Roll_no, Name, Registration_no}: This key cannot be considered
as a candidate key because when we take the subset of this key we get
three attributes i.e Roll_no, Registration_no and Name. Two of these
attributes i.e Roll_no and Registration_no are the candidate key. So, it is
not a minimal superkey. Hence, this key is not a candidate key.
So, from the above discussion, we conclude that we can have only 2 out of
above 6 super keys as the candidate key. i.e. (Roll_no) and(Registration_no).

Primary Key
The primary key is the minimal set of attributes which uniquely identifies any
row of a table. It is selected from a set of candidate keys. Any candidate
key can become a primary key. It depends upon the requirements and is
done by the Database Administrator (DBA). The primary key cannot have a
NULL value. It cannot have a duplicate value.

Example: In the above example, we saw that we have two candidate keys i.e
(Roll_no) and (Registration_no). From this set, we can select any key as the
primary key for our table. It depends upon our requirement. Here, if we are
talking about class then selecting ‘Roll_no’ as the primary key is more logical
instead of ‘Registrartion_no’.

Alternate Key
All the candidate key which are not a primary key are called an alternate
key.

Example: In the above example, since we have made ‘Roll_no’ as the Primary
Key our Alternate Key would be ‘Registration_no’.
Foreign Key
The foreign key of a table is the attribute which establishes the relationship
among tables. The foreign key is the attribute which points to the primary key
of another table.

Example: If we have two tables of Student and Course then we can establish a
relationship between these two tables using a foreign key. The ‘Course_id’ in
the Student table is the foreign key as it establishes the link between the
Student and Course Table. So, if we need to find the information about any
course opted by any student then we can go the Course table using the foreign
key.

One thing that is to be noted here is that the foreign key of one table may or
may not be the primary key. But it should be the primary key of another table.
In the above example, Course_id is not a primary key in the Student table but
it is a primary key in the Course table.
Codd's 12 Rules
Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with
twelve rules of his own, which according to him, a database must obey in order to be regarded as a true
relational database.

Rule 1: Information Rule


The data stored in a database, may it be user data or metadata, must be a value of some table
cell. Everything in a database must be stored in a table format.

Rule 2: Guaranteed Access Rule


Every single data element (value) is guaranteed to be accessible logically with a combination of
table-name, primary-key (row value), and attribute-name (column value). No other means, such
as pointers, can be used to access data.

Rule 3: Systematic Treatment of NULL Values


The NULL values in a database must be given a systematic and uniform treatment. This is a very
important rule because a NULL can be interpreted as one the following − data is missing, data is
not known, or data is not applicable.

Rule 4: Active Online Catalog


The structure description of the entire database must be stored in an online catalog, known
as data dictionary, which can be accessed by authorized users. Users can use the same query
language to access the catalog which they use to access the database itself.

Rule 5: Comprehensive Data Sub-Language Rule


A database can only be accessed using a language having linear syntax that supports data
definition, data manipulation, and transaction management operations. This language can be
used directly or by means of some application. If the database allows access to data without any
help of this language, then it is considered as a violation.

Rule 6: View Updating Rule


All the views of a database, which can theoretically be updated, must also be updatable by the
system.

Rule 7: High-Level Insert, Update, and Delete Rule


A database must support high-level insertion, updation, and deletion. This must not be limited to a
single row, that is, it must also support union, intersection and minus operations to yield sets of
data records.

Rule 8: Physical Data Independence


The data stored in a database must be independent of the applications that access the database.
Any change in the physical structure of a database must not have any impact on how the data is
being accessed by external applications.

Rule 9: Logical Data Independence


The logical data in a database must be independent of its user’s view (application). Any change in
logical data must not affect the applications using it. For example, if two tables are merged or one
is split into two different tables, there should be no impact or change on the user application. This
is one of the most difficult rule to apply.

Rule 10: Integrity Independence


A database must be independent of the application that uses it. All its integrity constraints can be
independently modified without the need of any change in the application. This rule makes a
database independent of the front-end application and its interface.

Rule 11: Distribution Independence


The end-user must not be able to see that the data is distributed over various locations. Users
should always get the impression that the data is located at one site only. This rule has been
regarded as the foundation of distributed database systems.

Rule 12: Non-Subversion Rule


If a system has an interface that provides access to low-level records, then the interface must not
be able to subvert the system and bypass security and integrity constraints.

WORKING WITH DATABASES:

What is DDL in SQL?

DDL allows you to create SQL statements to make operations with database data
structures (schemas, tables etc.).

CREATE

CREATE statement is used to create a new database, table, index or stored procedure.

Create TABLE example:

CREATE TABLE Employee

(Emp_id varchar2(10),

Full_name char(50),
Address char(50),

Birth_date date

);

CREATE TABLE Student (

Roll_no INT(16) PRIMARY KEY AUTO_INCREMENT,

Stud_name VARCHAR(255) NOT NULL

);

DROP

DROP statement allows you to remove database, table, index or stored procedure.

Drop database example:

DROP TABLE Employee;

ALTER

ALTER is used to modify existing database data structures (database, table).

Alter table example:

ALTER TABLE Student ADD COLUMN Address VARCHAR(255) NOT NULL;

RENAME

RENAME command is used to rename SQL table.

Rename table example:


RENAME TABLE Student TO IF3ISTUDENTS;

TRUNCATE

TRUNCATE operation is used to delete all table records.

Logically it’s the same as DELETE command.

Differences between DELETE and TRUNCATE commands are:

TRUNCATE is really faster

TRUNCATE cannot be rolled back

TRUNCATE command does not invoke ON DELETE triggers

Example:

TRUNCATE student;

What is DML in SQL?

DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate
(select, insert, update, delete etc.) data in the database.

This is DML commands list with examples:

SELECT

SELECT query is used to retrieve a data from SQL tables.

Example:

SELECT * FROM student;


INSERT

INSERT command is used to add new rows into the database table.

Example:

INSERT INTO student (ROLL_NO,NAME) VALUES ('901', 'AGR');

UPDATE

UPDATE statement modifies records into the table.

Example:

UPDATE student

SET name = 'Anand'

WHERE ROLL_NO = '901';

DELETE

DELETE query removes entries from the table.

Example:

DELETE FROM student

WHERE name = 'Anand';

What is DCL in SQL?

DCL a Data Control Language.

Its commands are responsible for access restrictions inside of the database

GRANT
GRANT command gives permissions to SQL user account.

GRANT all

ON STUDENT

TO USER1

REVOKE

REVOKE statement is used to remove privileges from user accounts.

REVOKE ALL

ON STUDENT

FROM USER1

What is TCL in SQL?

TCL is a Transaction Control Language.

Its commands are used to manage transactions in SQL databases.

START TRANSACTION (BEGIN, BEGIN WORK)

START TRANSACTION is used to start a new SQL transaction.

BEGIN and BEGIN WORK are aliases for START TRANSACTION.

Example:

START TRANSACTION;

after that, you’re doing manipulations with a data (insert, update, delete) and at the end,
you need to commit a transaction.

COMMIT

As a mentioned above COMMIT command finishes transaction and stores all changes
made inside of a transaction.
Example:

START TRANSACTION;

INSERT INTO student (ROLL_NO, NAME) VALUES ('902', 'SWATI');

COMMIT;

ROLLBACK

ROLLBACK statement reverts all changes made in the scope of transaction.

Example:

START TRANSACTION;

INSERT INTO student (ROLL_NO, NAME)

VALUES ('902', 'SWATI');

ROLLBACK;

ORDERBY CLAUSE IN SQL


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or
more columns. Some databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to
sort that column should be in the column-list.

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 has an example, which would sort the result in an ascending order by the NAME
and the SALARY −
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending order by NAME.
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

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

CustomerI CustomerName ContactNam Address City PostalCod Country


D e e

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

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


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

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


snabbköp Berglund 8

SQL GROUP BY Examples


The following SQL statement lists the number of customers in each country:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

The following SQL statement lists the number of customers in each country, sorted high
to low:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

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

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 1996-07-04 3

10249 81 6 1996-07-05 1

10250 34 4 1996-07-08 2

And a selection from the "Shippers" table:

ShipperID ShipperName

1 Speedy Express

2 United Package
3 Federal Shipping

The SQL COUNT(), AVG() and SUM() Functions


The COUNT() function returns the number of rows that matches a specified criterion.

The AVG() function returns the average value of a numeric column.

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

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

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

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles

4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

COUNT() Example
The following SQL statement finds the number of products:

Example
SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.

AVG() Example
The following SQL statement finds the average price of all products:

Example
SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.

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

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails"
table:

Example
SELECT SUM(Quantity)
FROM OrderDetails;

SQL commands list:


Language Command List
▪ CREATE
▪ DROP
 DDL ▪ ALTER
▪ RENAME
▪ TRUNCATE

▪ SELECT
▪ INSERT
 DML
▪ UPDATE
▪ DELETE

▪ GRANT
 DCL
▪ REVOKE

▪ START TRANSACTION
 TCL ▪ COMMIT
▪ ROLLBACK

What is an Operator in SQL?


An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations. These Operators
are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.

● Arithmetic operators
● Comparison operators
● Logical operators
● Operators used to negate conditions

SQL Arithmetic Operators


Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples
Operator Description Example

Adds values on either side of the operator. a + b will


+ (Addition)
give 30

Subtracts right hand operand from left hand operand. a - b will


- (Subtraction)
give -10

Multiplies values on either side of the operator. a * b will


* (Multiplication)
give 200

Divides left hand operand by right hand operand. b / a will


/ (Division)
give 2

Divides left hand operand by right hand operand and returns b%a
% (Modulus) remainder. will give
0

SQL Comparison Operators


Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (a = b) is
=
condition becomes true. not true.

Checks if the values of two operands are equal or not, if values are not (a != b)
!=
equal then condition becomes true. is true.

Checks if the values of two operands are equal or not, if values are not (a <> b)
<>
equal then condition becomes true. is true.

Checks if the value of left operand is greater than the value of right (a > b) is
>
operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than the value of right operand, (a < b) is
<
if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to the value of (a >= b)
>= right operand, if yes then condition becomes true. is not
true.

Checks if the value of left operand is less than or equal to the value of (a <= b)
<=
right operand, if yes then condition becomes true. is true.

Checks if the value of left operand is not less than the value of right (a !< b)
!<
operand, if yes then condition becomes true. is false.

Checks if the value of left operand is not greater than the value of right (a !> b)
!>
operand, if yes then condition becomes true. is true.

SQL Logical Operators


Here is a list of all the logical operators available in SQL.
Show Examples

Sr.No. Operator & Description

1 ALL
The ALL operator is used to compare a value to all values in another value set.

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

ANY
3 The ANY operator is used to compare a value to any applicable value in the list as per
the condition.

BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.

EXISTS
5 The EXISTS operator is used to search for the presence of a row in a specified table
that meets a certain criterion.

6 IN
The IN operator is used to compare a value to a list of literal values that have been
specified.

LIKE
7 The LIKE operator is used to compare a value to similar values using wildcard
operators.

NOT
8 The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR
9 The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.

IS NULL
10
The NULL operator is used to compare a value with a NULL value.

UNIQUE
11 The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).

SET Operations in SQL

ID Name

1 abhi

2 adam
ID Name

2 adam

3 Chester

ID NAME

1 abhi

2 adam

3 Chester

ID NAME

1 abhi

2 adam

ID NAME

2 adam

3 Chester
ID NAME

1 abhi

2 adam

2 adam

3 Chester

ID NAME

1 abhi

2 adam

ID NAME

2 adam

3 Chester

ID NAME

2 adam
ID NAME

1 abhi

2 adam

ID NAME

2 adam

3 Chester

ID NAME

1 abhi

We have to create Table in MS-access:

QUERY for Creating EMP table:


CREATE TABLE S (S_No CHAR (5) NOT NULL, SNAME CHAR (20) NOT NULL, STATUS SMALLINT NOT NULL,
CITY CHAR (15) NOT NULL, PRIMARY KEY (S_No));

Answer the following queries in SQL.


1.  QUERY for Find all the ENAME’s whose salary is < Rs.20000.
SELECT * FROM EMP WHERE SALARY < 20000;
2.  QUERY for Find all the employees working with SALES Department and with designation MANAGER.
SELECT * FROM EMP WHERE DEPT_NAME=’SALES’ AND DESIGNATION=’MANAGER’;

3.  QUERY for Find all employees whose name starts with S.
SELECT * FROM EMP WHERE ENAME LIKE “S*”;

4.  QUERY for Find total number of employees who work with RESEARCH department.
SELECT COUNT (*) FROM (SELECT * FROM EMP WHERE DEPT_NAME=’RESEARCH’);

5.  QUERY for Find all the employees who joined after Jan 1, 2010.
SELECT * FROM EMP WHERE DATE_OF_JOIN > #01/01/2010#;

6.  QUERY for Count number of employees whose salary is between Rs.8000 and Rs.12500.
SELECT * FROM EMP WHERE SALARY BETWEEN 8000 AND 12500;

7.  QUERY for Sort the supplier table by ENAME.


SELECT * FROM EMP ORDER BY ENAME;
8.  QUERY for Find the employees whose designation is SALESMAN and joined after 1st Aug, 1990.
SELECT * FROM EMP WHERE DESIGNATION=’SALESMAN’ AND DATE_OF_JOIN > #01/08/1990#;

9.  QUERY for Find all the employees whose designation is CLERK.
SELECT * FROM EMP WHERE DESIGNATION=’CLERK’;

10.  QUERY for Count number of SALESMAN in SALES department.


SELECT COUNT (*) FROM EMP WHERE DESIGNATION=’SALESMAN’ AND DEPT_NAME=’SALES’;

11.  QUERY for Count all the number of employees who are working with the company.
SELECT COUNT (*) FROM EMP;

12.  QUERY for Find S# of supplier who supply part “p2”.


WRONG QUESTION
13.  QUERY for Find the employees joined between 1st Jan, 1997 and 31st Dec, 2010.
SELECT * FROM EMP WHERE DATE_OF_JOIN BETWEEN #01/01/1997# AND #31/12/2010#;

14.  QUERY for Sort the table by the SALARY, descending order.
SELECT * FROM EMP ORDER BY SALARY DESC;

15.  QUERY for Find the employees with similar names and display their designation, department and
data of join.
SELECT DESIGNATION, DEPT_NAME, DATE_OF_JOIN  FROM EMP WHERE (ENAME) IN (SELECT ENAME
FROM EMP GROUP BY ENAME HAVING COUNT (*) >1);

You might also like