Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

KKW Unit 2 Relational Data Model

Uploaded by

thakkarparth793
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

KKW Unit 2 Relational Data Model

Uploaded by

thakkarparth793
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Data Base Management System 2021

Chapter 02- Relational Data Model


Course Outcomes (COs) / Unit Outcomes (UOs):
Course Outcome (CO 304.1):Design Normalized database on given data
(CO 304.2): Create & manage database using SQL command
Unit Outcomes:
1a) State the importance of DBMS over file processing in the given situation
1b) Describe the overall structure of the given DBMS
1c) Identify the relevant database model in the given situation
1d) Draw the E-R diagram of the given database & identify relationship between the entities
2a) Explain the concept of RDBMS also appropriateness for the given problem
2b)Design normalized database structure in the given problem
2c) Design SQL queries to create Relational database & apply in the given data constraints
2d)Identify the operators for queries implementation of the given problem

2.1 Fundamentals of RDBMS


 Record
 Records are composed of fields, each of which contains one item of information. A set of records constitutes a file. For
example, a personnel file might contain records that have three fields: a name field, an address field, and a phone number
field. In relational database management systems, records are called tuples.
 Fields
 In a database table, a field is a data structure for a single piece of data. Fields are organized into records, which contain all
the information within the table relevant to a specific entity.

 Data Types
 A data type defines what type of data we are storing for particular column.
 Tables
 It consists of columns, and rows.
 In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns
(identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect.
 A table is a means of displaying data or information in rows and columns.
 Rows are also called a record and columns are also known as parameters, fields, or attributes.
 The point of intersection between a column and a row is called a cell
 Database
 A database is a data structure that stores organized information.
 Most databases contain multiple tables, which may each include several different fields. T

2.2 Concept of RDBMS


 A relational database consists of a collection of tables each of which assigned a unique name.
 A row in a table represents a relationship among a set of values
 A table is an entity set and a row is an entity
 Relation- It is a collection of tuples each of which contains values for a fixed number of attributes
 Attributes-It is a column of a table
 Domain-The set of permissible values for each attribute is called the domains
 Tuple- It is a single row from a table
 Key-A single attribute or combination of attributes whose value uniquely identifies the tuple of the relation.

 E. F. Codds rule for RDBMS:


DBMS can be considered a relational DBMS (RDBMS). In 1985, Dr. E. F. Codd first published this list of rules that became a
standard way of evaluating a relational system. Following are Codd's original 12 rules:

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 1


Data Base Management System 2021

1. The Information rule: All information in an RDBMS is represented logically in just one way - by values in tables.
2. The Guaranteed Access rule: Each item of data in an RDBMS is guaranteed to be logically accessible by resorting to a
combination of table name, primary key value, and column name.

3. The Systematic Treatment of Null Values rule: Null values (distinct from an empty character string or a string of blank
characters and distinct from zero or any other number) are supported in a fully relational DBMS for representing missing
information and inapplicable information in a systematic way, independent of the data type.

4. The Dynamic Online Catalog Based o n the Relational Model rule: The database description is represented at the logical
level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as
they apply to the regular data.

5. The Data Language rule: A relational system may support several languages and various modes of terminal use. However,
there must be at least one language whose statements are expressible, per some well-defined syntax, as character strings and
whose ability to support all of the following is comprehensible: data definition, view definition, data manipulation, integrity
constraints, and transaction boundaries.

6. The View Updating rule: All views of the data which are theoretically updatable must be updatable in practice by the DBMS.

7. The High-level Insert, Update, and Delete rule: The database must support high level insertion, updation and deletion.

8. The Physical Data Independence rule: Application programs and terminal activities remain logically unimpaired whenever
any changes are made in either storage representations or access methods.

9. The Logical Data Independence rule: Application programs and terminal activities remain logically unimpaired when
information preserving changes of any kind that theoretically permit unimpaired are made to the base tables.

10. The Integrity Constraints rule: Integrity constraints must be definable in the RDBMS sub-language and stored in the system
catalogue and not within individual application programs.

11. The Database Distribution Independence: An RDBMS has distribution independence. Distribution independence implies
that users should not have to be aware of whether a database is distributed.

12. The Non subversion rule: If the database has any means of handling a single record at a time, that low -level language must not
be able to subvert or avoid the integrity rules which are expressed in a higher-level language that handles multiple records at a
time.

 Key Concepts:
1. Primary key
– Primary key denotes a candidate key that is chosen by the database designer as the principal means of identifying items
within an entity set.
– The primary key should be chosen such that its attributes are never, or very rarely, changed.
– For example, SSN are guaranteed to never changed.
– To ensure that each record is unique in each table, we can set one field to be a Primary Key field.
– A Primary Key is a field that that will contain no duplicates and no blank values.

2. Foreign key
– A foreign key is a combination of column with a value based on the primary key values from another table.
– A foreign key constraint also known as referential constraint corresponds to a actual values of the primary key in the
another table. Foreign Keys link to data in other tables.

3. Super key
It is a set of one or more attributes that, taken collectively, to identify uniquely an item in the entity set.
For example, SSN is a superkey.

4. Candidate key
Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 2
Data Base Management System 2021
It is a minimal superkey. For example, Last name and Hire date is sufficient to distinguish among members of the customer
entity set. Then { Last name, Hire date } is a candidate key.

2.3 Introduction to SQL


 SQL is a database language for querying and modifying relational databases
 It was developed by IBM researcher in mid 1970 and standardized by ANSI in 1986
 It is also pronounced as Sequel.
 The relational model defines two root languages for accessing the relational database i. e. Relational Algebra and
Relational Calculus
 SQL is a version of relational Calculus
 The basic structure of a SQL is the statement.
 Semicolon Separates the multiple Statements.
 To access the data from the table we use SQL. The main use off SQL is to shoot the queries & access, update, add or
delete the data.
 According to Functionality there are three basic categories of SQL Statements
1. SQL DDL- SQL Data Definition Language used for main Schema Definition
2. SQL DML- SQL Data Manipulation Language used for query and modify table data.
3. SQL DCL-SQL Data Control Language used for Controlling operations on Database.

 Data Types in SQL


1. Each column in a database table is required to have a name and a data type.
2. SQL developers have to decide what types of data will be stored inside each and every table column when creating a
SQL table.
3. The data type is a label and a guideline for SQL to understand what type of data is expected inside of each column,
and it also identifies how SQL will interact with the stored data.
4. A table can have up to 254 columns in which column may have different or same datatype.
5. The following table lists the general data types in SQL:
Data type Description

CHAR(n) Character string,


Fixed-length n,
max size for n is 255 bytes 2000 bytes in oracle,
default size is 7 byte,
supports Alphanumeric values
Ex. Char(40)
VARCHAR2(n) Character string,
Variable length,
Takes less space as compare to char,
Max size for n is 2000 bytes & 4000 bytes for oracle,
supports Alphanumeric values
Ex. Varchar2(80)
NUMBER(o,d) or NUMERIC Exact numerical for integers & real numbers,
O= Overall no. of digit, d= decimal point,
Can store +ve or –ve no.s, zeros, fixed point & floats,
Max size O= 38, d=(-84 to 127)
Ex, number(8), number(5,2) i.e. 123.45
DATE Stores year, month, and day values
Default format is dd-mon-yy,
Fixed length of 7 bytes

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 3


Data Base Management System 2021
Ex. 13-oct-11, 05-aug-16
LONG Stores variable character length,
Max size 2GB,
In a table only one LONG column is allowed
Ex. Long Address

 Components of SQL- DDL,DML,DCL,DQL


A Database System provides a data definition language to specify the database schema and a data manipulation
language to express database queries and update.RDBMS provides following languages.
1. Data Definition Language (DDL)
 Specification notation for defining the database schema
 DDL compiler generates a set of tables stored in a data dictionary
 Data dictionary contains metadata (data about data)
 Data storage and definition language – special type of DDL in which the storage structure and access
methods used by the database system are specified
 Ex. Create, Alter, Drop, Truncate, Rename,DESC
2. Data Manipulation Language (DML)
 Language for accessing and manipulating the data organized by the appropriate data model
 Data Manipulation is-
 The retrieval of information stored in the database
 The insertion of new information into the database
 The deletion of information from the database
 The modification of information stored in the database
 There are basically two types of DML Language
 Procedural DML– user specifies what data is required and how to get those data
 Non Procedural DML – user specifies what data is required without specifying how to get those data
 Ex. Select, Insert, Update, Delete
3. Data Query Language (DQL)
 Used to retrieve certain records from one or more tables.
 e.g. Select
4. Data Control Language (DCL)
 Used to give a privilege to someone.
 Used to take back privileges granted to someone.
 Example. Grant, Revoke, Rollback, Savepoint, commit

2.4 DDL Commands:


1) CREATE :

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 4


Data Base Management System 2021
 Create is DDL command used to create the Table .
 The create table command defines each column of the table uniquely.
 Each column has minimum of three attributes: Name, Data type, Size (column width).
 Each table column definition is a single clause in the create table syntax.
 Each table column definition is separated from the other by a comma.
 Finally, the SQL statement is terminated with a semicolon.
Syntax :
SQL > CREATE TABLE <table_name > ( Column_name1 Data_type(Size), Column_name2
Data_type(Size), .........., Column_nameN Data_type(Size));

Example:
SQL>CREATE TABLE Student (Reg_no varchar2(10), Name char(30), DOB date, Address
varchar2(50));

 Notes:
1. Table names and column names must begin with letter
2. Table names and column names can be 1 to 30 characters long
3. Table names must contain only the characters A-Z, a-z, 0-9, underscore _, $ and #
4. Table name must not be a Oracle reserve word
5. Column name should not be duplicate within a table definition

2) ALTER

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 5


Data Base Management System 2021
 An Existing Table Or already Created table cab be Modified by using ALTER Table Statement.
 Alter Command have two Keywords Add & Modify .
a) Modify -
Change the Existing table Structure . Means By using Modify Clause one can change the Data type
size of column and Data type.

Syntax :
SQL> ALTER TABLE <table_name> modify column_name data_type(size) ;

E.g.
SQL> ALTER TABLE EMP modify ( EMPID number(10);

In Above Example the Old data type size of Column EMPID number(5) after the ALTER command the
size of EMPID number (10) .
b) ADD
Add Clause of the Alter command are used to add the New column in Existing table . New
column automatically add at the end of Table.
Syntax:
SQL> ALTER TABLE <table name> ADD ( column_name data_type(size) ) ;
E.g.
SQL> ALTER TABLE EMP add ( address varchar2(20) );

3) RENAME
 Rename command is used to rename the old table name to new table name
Syntax:
RENAME <OldTableName> TO <NewTableName> ;

Example:
RENAME Student TO stud_info ;
The old name table was Student now new name is the stud_info;

4) TRUNCATE
 To Delete the data inside the Table and release the Storage space
Syntax:
SQL> TRUNCATE TABLE <Table_name> ;

Example:
TRUNCATE TABLE Student;

5) DROP
 When Existing Object Or Table is Not Required for further use. It’s always better to eliminate it from database
 With drop table structure of table is removed permanently
 To Delete the existing Object or Table from the Database . The following command is used .
 When we drop a table the database loses all the data in the table .
Syntax :
SQL> DROP TABLE<Table_name>;

E.g.SQL> DROP TABLE EMP ;

6) Desc
 Provides a decription of the specified table or view.
Syntax:
SQL> Desc <table_name>;

E.g.
SQL> desc emp;

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 6


Data Base Management System 2021

2.5 DML Commands:


Data manipulation language (DML) statements access and manipulate data in existing tables.

1. INSERT:
 The INSERT statement inserts rows into an existing table.
 It’s Possible to Write INSERT INTO Statement in TWO forms.
1) To insert the values for all attributes in the order attributes declared in the table :
Syntax :
SQL> INSERT INTO <Table_name> Values (Value1 , Value2 , Value3 ,...,valueN);

Example:
SQL> insert into student values (12109, ‘Nirmal',‘Dey',‘Pune',789123,'c003');

2) To insert a row into a table by specifying all attributes and its value:
Syntax :
SQL> INSERT INTO <Table_name> (Column1,Column2,Column3,............, ColumnN) Values
(Value1,Value2,Value3,........, ValueN) ;
Example:
SQL> insert into student(ENAME, EID, SALARY, ADDRESS) Values(‘Amit’, 01,
4567, ’Nashik’);

3) To insert values for selected attributes in a table


SQL> INSERT INTO <Table_name> (Column1, Column2) Values (Value1,Value2)
Example:
SQL> INSERT INTO Student (EnrollmentID, FirstName) Values (121011,’Navin’) ;

4) It is possible to insert multiple records/Rows


Syntax : INSERT INTO <Table_name> Values (&Column1, ’&Column2’, &Column3,............,
&ColumnN);
Example:
INSERT Into Student values(‘&ENAME’, &EID, &SALARY, ‘&Address’);

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 7


Data Base Management System 2021
2. UPDATE
 The UPDATE statement updates (changes the values of) a set of existing table rows.
 The update Statement is used to update existing Records in Table.
Syntax :
SQL> Update <table_name> SET Column1=Value1 , Column2=Value2
Where column_name =Value ;
 WHERE clause is used for searching condition , where the Exact Record should updated . If we does
not specify the WHERE Clause ,all Record will be updated .
 Example
SQL> UPDATE Student SET Address=‘SATARA’ where EnrollmentID = 12100 ;

3. DELETE
 The DELETE statement deletes rows from a table.
 syntax:
SQL> DELETE FROM <table_name> [WHERE condition];

Example
SQL> DELETE FROM STUDENT WHERE EnrollmentID= 12100;

 If we include the WHERE clause, the statement deletes only rows that satisfy condition.
 If we omit the WHERE clause, the statement deletes all rows from the table, but the empty table still exists.

4.SELECT.
 The SELECT statement retrieves or extracts information from tables in the database.
 Using the SELECT statement, we can choose the rows in a table that we want to returned from a query by specifying
values to match the rows that we want to see (or don't want to see).
 We can use select statement to display all the data from table, to display particular data, to view distinct Data, to display
rows that matches particular condition.
 Syntax1-
SQL> Select * from <Table Name>;
Example: SQL> Select * from emp;
It will display all the data from emp Table
 Syntax2-
SQL> Select * from <Table Name> Where < Condition>;
Example: SELECT * FROM users WHERE name = 'john'
The example above retrieves all rows from the table 'users' where the 'name' column contains
the text 'john'.
 Syntax3- Select column Name1, Column Name2 from <Table Name>;
Example: Select eid, ename from emp;
It will display all the eid and ename from emp Table
 Syntax4- Select Distinct column Name from <Table Name>;
Example:Select Distinct ename from emp;
It will display all ename from emp Table excuding Duplicate values of Name.
It means duplicate values are displayed only ones.
Select Command is Also Called as DQL Command

2.6 DCL Commands:


 Data Control Statements are one of the SQL statement types which enforce database security at database
and object level.
 It deals with the access permissions and rights of a user.

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 8


Data Base Management System 2021
 DCL commands are used to assign security levels in database, which involves multiple user setups.
 They are used to grant defined role and access privileges to the users.
 There are two types of DCL commands in Oracle:
1. GRANT
2. REVOKE

1. Grant : A DBA or user can grant access permission on owned database objects to other user or roles using GRANT
command.
Syntax:
SQL> GRANT [privilege list ] ON [object] TO {user |PUBLIC | role} [WITH ADMIN | GRANT
OPTION];

WITH GRANT OPTION :


The user which has been granted permission of privileges, that also able to allow to grantrivileges to other user .
Privileges: Privilege is the permission name, which is granted to the user. It may be SELECT, INSERT, UPDATE,
DELETE, EXECUTE, ALL and many others, on a database object.
Examples:

SQL > GRANT ALL ON EMP TO Sachin ;

2. Grant INSERT,SELECT Privileges on Emp table to user Sachin.


SQL > GRANT INSERT, SELECTON EMP TO Sachin;

3. Grant all Privileges on Emp table to user Sachin WITH GRANT OPTION
SQL > GRANT ALL ON EMP TO Sachin WITH GRANT OPTION ;

2. REVOKE: This command is used to revoke an existing privilege from a user. It can revoke a system privilege,
object privilege or a role from a user. Only DBA or a user with ADMIN OPTION can revoke system privilege.
Syntax:
SQL> REVOKE [privilege ] ON [object] FROM {USER |PUBLIC | ROLE} ;

Examples:
1. Revoke all Privileges on Emp table FROM user Sachin.
SQL > REVOKE ALL ON EMP FROM Sachin;

2. REVOKE INSERT,SELECT Privileges on Emp table FROM user Sachin.


SQL > Revoke INSERT,SELECT ON EMP FROM Sachin;

3. COMMIT
Commit command is transactional command used to save permanent changes to the Database .
Syntax :
SQL> Commit;

4. SAVEPOINT
 Savepoint is point in a Transaction where we can rollback the transaction to certain point without rolling back the
entire transaction .
Syntax:
SQL> SAVEPOINT savepoint_name;
The above command create the savepoint among the Transaction statement .
 The ROllBACK is used to undo a group of transaction .

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 9


Data Base Management System 2021
SQL>ROLLBACK TO savepoint_name;

Examples:
If we want to delete the THREE record from EMP table . So we can Create a Savepoint Before each delete , so we can rollback
to each SAVEPOINT at any time to return the appropriate data.
Consider table “EMP “

EID ENAME ADDRESS

1 Nitin Nashik

2 Sachin Pune

3 Raj NashiK

4 Pooja Thane

5 minal Nashik

SQL> SAVEPOINT SP1;

Savepoint created.

SQL> DELETE FROM EMP WHERE EMPID=1;

1 row deleted.

SQL> SAVEPOINT SP2;

Savepoint created.

SQL> DELETE FROM EMP WHERE EMPID=2;

1 row deleted.

SQL> SAVEPOINT SP3;

Savepoint created.

SQL>DELETE FROM EMP WHERE EMPID=3;

We have deleted the THREE record from EMP table .

If we want to undo LAST TWO delete operation . Then we can ROLLBACK to SAVEPOINT upto

SP2. Then last two deletion are undo .

SQL> rollback to SP2;

Rollback complete.

So only fist record is deletion took place above rollback undo to SP2;

SQL> select * from emp;

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 10


Data Base Management System 2021

EID ENAME ADDRESS

2 Sachin Pune

3 Raj NashiK

4 Pooja Thane

5 minal Nashik

5. ROLLBACK Statement
 The rollback command can be used to undo the changes done in current transaction. We can either rollback the entire
transaction or till a particular savepoint transaction can be rolled back.
 If savepoint is given then rollback will be done till the savepoint.
Syntax:
SQL> rollback;
OR
SQL> rollback [to < savepoint>];
 IF we delete all Record from Database , if we want all record back to the Database then we use ROLLBACK command
. Who rollback all the Transactions. If Savepoint is given then it rollback till the save point.
SQL> delete from emp;
5 rows deleted.
SQL> rollback;
Rollback complete.
SQL> select * from emp;
EMPID ENAME ADDRESS
---------- ---------- ----------
1 nitin nashik
2 sachin pune
3 raj mumbai
4 pooja thane
5 minal dhule

2.7 SQL Operators:


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. Operators are used to specify conditions in an SQL statement and to serve as
conjunctions for multiple conditions in a statement.
Types of Operators are:
1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. SQL Set Operator

1. SQL Arithmetic Operators:


Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 11


Data Base Management System 2021
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand b / a will give 2
Modulus - Divides left hand operand by right hand operand and returns
% b % a will give 0
remainder

2. SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:

OperatorDescription Example
Checks if the values of two operands are equal or not, if yes then condition
= (a = b) is not true.
becomes true.
Checks if the values of two operands are equal or not, if values are not equal
!= (a != b) is true.
then condition becomes true.
Checks if the values of two operands are equal or not, if values are not equal
<> (a <> b) is true.
then condition becomes true.
Checks if the value of left operand is greater than the value of right operand, if
> (a > b) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if
< (a < b) is true.
yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right
>= (a >= b) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right
<= (a <= b) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is not less than the value of right operand,
!< (a !< b) is false.
if yes then condition becomes true.
Checks if the value of left operand is not greater than the value of right
!> (a !> b) is true.
operand, if yes then condition becomes true.
The BETWEEN operator is used to search for values that are within a set of
BETWEEN
values, given the minimum value and the maximum value.
The IN operator is used to compare a value to a list of literal values that have
IN
been specified.
The LIKE operator is used to compare a value to similar values using wildcard
LIKE
operators.
IS NULL The NULL operator is used to compare a value with a NULL value.

3. SQL Logical Operators:


Here is a list of all the logical operators available in SQL.
Operator Description
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
AND
clause.
The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT
NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
OR The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 12


Data Base Management System 2021
4. SQL Set Operators
Set operators combine the results of two component queries into a single result. Queries containing set operators are called
compound queries. Followigng Table lists SQL set operators.
Operator Returns
UNION All rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows selected by the first query but not the second

 Range Searching operators- Between


1. SQL BETWEEN Operator
 The BETWEEN operator is used to select values within a range.
 The BETWEEN operator selects values within a range. The values can be numbers, text, or dates
 Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

 PATTERN MATCHING OPERATORS-LIKE.


1. SQL LIKE Operator
 The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
 The LIKE operator is used to search for a specified pattern in a column.
 Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

Sample Example:
Consider "Customers" table:
CustomerIDCustomerName ContactName City PostalCode

1 Raj priti Nashik 12209

2 amit tushar Pune 05021

3 shruti rakesh Nashik 05023

4 sumit seema Nashik 234567

5 amit rahul pune 9585657

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 13


Data Base Management System 2021

 SQL LIKE Operator Examples


1. The following SQL statement selects all customers with a City starting with the letter "s":
SELECT * FROM Customers WHERE City LIKE 's%';

Note: The "%" sign is used to define wildcards (missing letters) both before and after the pattern.

2. The following SQL statement selects all customers with a City ending with the letter "s":
SELECT * FROM Customers WHERE City LIKE '%s';

3. The following SQL statement selects all customers with a Country containing the pattern "and":
SELECT * FROM Customers WHERE Country LIKE '%and%';

 Using the NOT keyword allows you to select records that does NOT match the pattern.
The following SQL statement selects all customers with a Country NOT containing the pattern "and":
SELECT * FROM Customers WHERE Country NOT LIKE '%and%';

2.8 Data Integrity constraints:


 An Integrity constraint ia a mechanisum used to prevent invalid Data Entry into the table
 Integrity constraints provide a way of ensuring that changes made to the database by authorized users do not result in a
loss of data consistency.
 An integrity constraint can be any rules or condition applied to the database.
 They may be costly to evaluate, so we will only consider integrity constraints that can be tested with Minimal overhead
 Purpose: prevent semantic inconsistencies in data.
 Types of Data Integrity Constraints are:
1) I/O Constraints-
a) Primary key
b) Foreign Key
c) Unique key
2) Business rule Constraint-
a) Null
b) Not Null
c) Check

1) I/O Constraints
a ) Primary Key constraint:
 It is use to avoid redundant/duplicate value entry within the row of specified column in table. It restricts null values
too.
 Syntax:
SQL> Create Table Table_Name (Column_Name1 Data_Type (Size) Constraint <Constraint_Name> Primary
Key ,Column_Name2 Data_Type (size));
Example:
Sql> Create Table Emp (Id Number (5) Constraint pk1 primary Key , Name char(10));

b) Unique Constraint:
 The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY
constraints both provide a guarantee for uniqueness for a column or set of columns.
Syntax:
Create Table Table_Name (Column_Name1 Data_Type, Column_Name2 Data_Type Constraint Constraint_Name
Unique);

Example:

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 14


Data Base Management System 2021
CREATE TABLE PERSONS (P_ID NUM CONSTRAINT P_UK UNIQUE , FIRSTNAME VARCHAR(20), CITY
VARCHAR(20) );

c) Foreign Key Constraint:


 A foreign key (FK) is a column that is used to join a table to other tables to ensure referential integrity of the data.
 A foreign key constraint requires that a column contain only values from the primary key column on a specific
dimension table.
 A FOREIGN KEY is a key used to link two tables together.
 A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
 The table containing the foreign key is called the child table, and the table containing the candidate key is called the
parent table.
 Syntax:
SQL > Create table Table_name ( Column_name Datatype(size) , Column_name Datatype(size), Constraint
constraint_name Foreign Key (column_name) References Parent_table_name (Column_name) );

Example:
SQL> Create table dept( dept_name char(10), dept_no number(10), eid number(10), constraint fk1 foreign
key(eid), refernces emp(eid));

1) Business Rule Constraints:


It is a type of integrity constraint. Itt is used to maintain the value according to user specification. It has three types:

a) NULL
-By default, a column can hold NULL values.
- Null means value for particular column is not known, or it is missing
-Syntax- Create table Table_name ( Column_name Datatype(size) , Column_name Datatype(size)NULL);
Example: SQL> create table sample (rno number(10) null ,name varchar2(10));

b) NOT NULL:
- By default all columns in tables allows null values.
-When a NOT NULL constraint is enforced on column or set of columns it will not allow null values
-Syntax: sql> create table <table_name> (column_name data_type(size), column_name data_type(size) not null);
-Example: sql>create table student (roll_no number (5), name varchar2 (20) not null);

c) CHECK:
-The constraint defines a condition that each row must satisfy. A single column can have multiple check
condition.
- Syntax:-SQL> create table <table_name> (column_name1 data_type(size),..., column_name n data_type(size)constraint
constraint_name check <condition>);
- Example:
SQL> create table emp (id number(5), name varchar2(10), sal number(10) constraint chk_sal check (sal>15000));

2.9 Normalization
If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator.
Managing a database with anomalies is next to impossible.
 Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange
situations. For example, when we try to update one data item having its copies scattered over several places, a few
instances get updated properly while a few others are left with old values. Such instances leave the database in an
inconsistent state.

 Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is
also saved somewhere else.

 Insert anomalies − We tried to insert data in a record that does not exist at all.
 Normalization is a method to remove all these anomalies and bring the database to a consistent state

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 15


Data Base Management System 2021
 In relational database design, the process of organizing data to minimize redundancy is known as Normalization
 Normalization is a database design technique which organizes tables in a manner that reduces redundancy and
dependency of data.
 It divides larger tables to smaller tables and links them using relationships.
 There are two goals of normalization process
- Eliminating Redundant(Duplicate) Data.
- Ensuring data Consistency
 Normalization works through a series of stages called normal forms:
– First normal form (1NF)
– Second normal form (2NF)
– Third normal form (3NF)
– Fourth normal form (4NF)

1. FIRST NORMAL FORM (1 NF):


 First Normal Form is defined in the definition of relations (tables) itself.
 This rule defines that all the attributes in a relation must have atomic domains.
 The values in an atomic domain are indivisible units
 Consider Folowing Relation in which content column is having multiple values for single row.

 We re-arrange the relation (table) as below, to convert it to First Normal Form.

2. SECOND NORMAL FORM (2 NF):


 Before we learn about the second normal form, we need to understand the following −
 Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.

 Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.

 If we follow second normal form, then

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 16


Data Base Management System 2021
a) relation should be in first normal form
b) every non-prime attribute should be fully functionally dependent on prime key attribute.
 That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true.

 Consider Student_Project relation that the prime key attributes are Stu_ID and Proj_ID.
 According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any
of the prime key attribute individually.
 But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently.
This is called partial dependency, which is not allowed in Second Normal Form.

 We broke the relation in two as depicted in the above picture. So there exists no partial dependency.
 Now the relation is in 1NF And there is no partial dependencies so we can say above relations are in 2NF.

3. THIRD NORMAL FORM (3 NF):


 For a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −
 No non-prime attribute is transitively dependent on prime key attribute.
 For any non-trivial functional dependency, X → A, then either − X is a superkey or, A is prime attribute

 We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute.
 We find that City can be identified by Stu_ID as well as Zip itself.
 Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists
transitive dependency
 To bring this relation into third normal form, we break the relation into two relations as follows

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 17


Data Base Management System 2021

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 18

You might also like