You are on page 1of 102

NEED FOR A DATABASE MANAGEMENT SYSTEM.

1. To store, manipulate, and manage the information.

2. To reduce the repeated storage of the data (Data Redundancy) and


improve the disk optimization

3. To keep up-to-date and correct information (Data consistency)

4. To automate the overall process of managing and processing the


system.

5 To centralize the data and improve the security of the data.


RELATIONAL DATABASE MANAGEMENT SYSTEM
(RDBMS)

 The information that is stored in the database is related with each other.

 A relational database is the one in which data is stored in the form of tables i.e.
rows and columns.

 The major functions performed by RDBMS are creating, editing and deleting
tables and inserting, deleting and editing data into that tables.

The examples of RDBMS are Oracle, SQL server, DBase.


DBMS DATABASE MODELS

 Defines the logical design and structure of a database.

 Defines how data will be stored, accessed and updated.

 Defines how data are connected to each other


TYPES OF DATABASE MODELS

 Hierarchical Model

 Network Model

 Entity-Relationship Model

 Relational Model

 Object oriented Model


TYPES OF RELATIONS

One-to-Many

One-to-one

Many-to-many
ONE-TO-MANY

One-to-many mappings are used to represent the relationship between a


single source object and a collection of target objects.
ONE-TO-MANY
ONE-TO-ONE

One-to-One mappings are used to represent the relationship between a single objects.
ONE-TO-ONE
MANY-TO-MANY

Many-to-many mappings represent the relationships between a collection of source


objects and a collection of target objects

They require the creation of an intermediate table for managing the associations between
the source and target records.
MANY-TO-MANY
WHAT IS NORMALIZATION ?

Database Normalization is a technique of organizing the data in the database.

Normalization is a systematic approach of decomposing tables to eliminate data


redundancy and undesirable characteristics like Insertion, Update and Deletion
Anomalies.

It is a multi-step process that puts data into tabular form by removing duplicated data
from the relation tables.

It was first proposed by Edgar F. Codd in 1970, as an essential part of a relational model.
NORMALIZATION RULE ARE DIVIDED INTO FOLLOWING
NORMAL FORM

 First Normal Form (1NF)


 Second Normal Form (2NF)
 Third Normal Form(3NF)
FIRST NORMAL FORM (1NF)

First Norma Form was introduced by Edgar Codd in 1970. 1NF sets the very basic rules for an
organized database.

First normal form enforces these criteria:

 Each column should atomic value(no multiple and no composite attributes)


Eg :Entries like X,Y and W,X violate this rule
 Each Column Should have unique name
Eg: multiple name field in a table.
 A column should contain values that are of the same type.
Eg: ‘Name’ in Name column and ‘date’ value in date column.
FIRST NORMAL FORM (1NF) EXAMPLE

Before Normalization (Unnormalized Form)

StudentName Address Subject


Krishna Bahadur Shrestha Kalimait-02,Kathmandu Networking,Java
Kumar Koirala Kalanki-05,Kathmandu DBMS,JAVA,HTML
Resham Shrestha Butwal-03,Rupandehi Programming,Designing
Pradeep kumar Bista Dharan-02, Sunsari .Net,C++,JAVA

First Normalization (Table in 1NF)


FirstName MiddleName Lastname muncipality WardNo District Subject
Krishna Bahadur Shrestha Kalimati 2 Kathmandu Networking
Krishna Bahadur Shrestha Kalimati 2 Kathmandu Java
Kumar Koirala Kalanki 5 Kathmandu DBMS
Kumar Koirala Kalanki 5 Kathmandu JAVA
Kumar Koirala Kalanki 5 Kathmandu HTML
Resham Shrestha Butwal 3 Rupandehi Programming
Resham Shrestha Butwal 3 Rupandehi Designing
Pradeep Kumar Bista Dharan 2 Sunsari .NET
Pradeep Kumar Bista Dharan 2 Sunsari C++
Pradeep Kumar Bista Dharan 2 Sunsari JAVA
SECOND NORMAL FORM (2NF)

Second normal form (2NF) further addresses the concept of removing duplicative data. It
was originally defined by Edgar Codd in 1971.

 Meet all the requirements of the first normal form.


 Remove subsets of data that apply to multiple rows of a table and place them in separate
tables.

Example : Student information and Subjects are in separated tables


SECOND NORMAL FORM (2NF)
Table in 1NF
FirstName MiddleName Lastname muncipality WardNo District Subject
Krishna Bahadur Shrestha Kalimati 2 Kathmandu Networking
Krishna Bahadur Shrestha Kalimati 2 Kathmandu Java
Kumar Koirala Kalanki 5 Kathmandu DBMS
Kumar Koirala Kalanki 5 Kathmandu JAVA
Kumar Koirala Kalanki 5 Kathmandu HTML
Resham Shrestha Butwal 3 Rupandehi Programming
Resham Shrestha Butwal 3 Rupandehi Designing
Pradeep Kumar Bista Dharan 2 Sunsari .NET
Pradeep Kumar Bista Dharan 2 Sunsari C++
Pradeep Kumar Bista Dharan 2 Sunsari JAVA

Break 1NF Table into two 2nf tables


Table2: StudentSubject
Table1: Student
StudentID Subject
StudentID FirstName MiddleName Lastname Muncipality WardNo District 1 Networking
1 Java
1 Krishna Bahadur Shrestha Kalimati 2 Kathmandu 2 DBMS
2 JAVA
2 Kumar Koirala Kalanki 5 Kathmandu 2 HTML
3 Programming
3 Resham Shrestha Butwal 3 Rupandehi
3 Designing
4 Pradeep Kumar Bista Dharan 2 Sunsari 4 .NET
4 C++
4 JAVA
THIRD NORMAL FORM (3NF)

Third normal form (3NF) goes one large step further:


- Meet all the requirements of the second normal form.
- Remove columns that are not dependent upon the primary key.
- Create the relationship between the tables

Eg (Customer’s/student’s address in different table)


THIRD NORMAL FORM (3NF)

Student Table in 2NF

StudentID FirstName MiddleName Lastname Muncipality WardNo District

1 Krishna Bahadur Shrestha Kalimati 2 Kathmandu

2 Kumar Koirala Kalanki 5 Kathmandu

3 Resham Shrestha Butwal 3 Rupandehi

4 Pradeep Kumar Bista Dharan 2 Sunsari

Removed the address info which are not dependent on student

Table1 : Student Table2 : Address

StudentID FirstName MiddleName Lastname AddressId AddressID muncipality WardNo District


1 Krishna Bahadur Shrestha 101 101 Kalimati 2 Kathmandu
2 Kumar Koirala 102 102 Kalanki 5 Kathmandu
3 Resham Shrestha 103 103 Butwal 3 Rupandehi
4 Pradeep Kumar Bista 104 104 Dharan 2 Sunsari
SQL SERVER DATABASE OVERVIEW

Instances : A instance of the database is copy of the SQLserver.exe executables that runs as
an operating system.

There are two types of database in a single instance


1. System Databases
2. User Databases

System Databases: By default, there are following four system database

 Master Database
 Model Database
 MSDB Database
 TempDB Database
Master Database : Contains all of the system level information for sql server.
For example : Logins, userdatabases, Linked server etc.

Note: We should not create any objects in master database.


Model Database : SQL server use this database whenever new user database
is created.

If we create any objects like tables, stored procedures, functions


it will automatically created in new users databases too.

Do not create any object in this database until it is require.


MSDB Database : MSDB is used by the SQL server agent, database mail, jobs etc.

It holds the backup history.

Do not create any object in this database until it is require.


TemDB Database : The tempdb system database is a global resource that is
available to all users connected to the instance

It is re-created every time the SQL Server service is started.

Any objects that you have created in tempdb will be gone once
the server restarts
ARCHITECTURE OF MSSQL DATABASE SERVER

Every SQL server has at least two operating system files

• Data Files

• Log Files
• Data Files :It contains data and objects such as tables, indexes, stored
procedures, and views

• Log Files : It contains the information that is required to recover all


transactions in the database
Types of Datafiles
I. Primary Data Files
II. Secondary Data Files
Primary Data Files : It contains the startup information for the database and
points to the other files in the database

The recommended file name extension for primary data


files is .mdf

Secondary Data Files : It is an optional data files. We can put multiple secondary
files in single database in different disk drives.

It helps to improve disk I/O.

The recommended file name extension for secondary data files is .ndf.
SQL
 Stands for Structure Query Language

 Used to perform task like:


• Insert Data into Database
• Update data into Database
• Retrieve data from Database

 SQL is used on some common RDBMS database, like:


• Oracle
• Microsoft SQL Server
• Sybase
• Access etc.
SQL
 Standard SQL commands are:

o “Insert”
o “Update”
o “Select”
o “Delete”
o “Create”
o “Drop”
TYPES OF SQL COMMANDS

 DDL (Data Definition Language)

 DML (Data Manipulation Language)

 DCL (Data Control Language)


TYPES OF SQL COMMANDS

 DDL (Data Definition Language)

DDL, is the part of SQL that allows a database user to create and restructure
database objects, such as the creation or the deletion of a table.
• CREATE
• ALTER
• DROP
CREATE TABLE STATEMENT
The CREATE TABLE statement is used to create a new table in a database.
Syntax:

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
)

Example:
CREATE TABLE [dbo].[StudentInfo]
(
[First Name] varchar(20) ,
[Middle Name] varchar(20) ,
[Last Name] varchar(20) ,
[section] char(1) ,
[Permanent Address] varchar(25) ,
[Email Address] varchar(30) ,
[Gender] char(6) ,
[DOB] date
)
DROP TABLE STATEMENT
The SQL Server (Transact-SQL) DROP TABLE statement allows you to remove or delete a
table from the SQL Server database

Syntax :
DROP TABLE table_name;

Example:
Drop TABLE StudentInfo;
ALTER TABLE STATEMENT
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table

Syntax :
ALTER TABLE table_name
ADD column_name datatype;

ALTER TABLE table_name


ALTER COLUMN column_name datatype;

Examples:
ALTER TABLE StudentInfo
ADD StudentAge INT

ALTER TABLE ProductSales


ALTER COLUMN BRAND VARCHAR(30)
TYPES OF SQL COMMANDS

 DML (Data Manipulation Language)

Data Manipulation Language, DML, is the part of SQL used to manipulate data
within objects of a relational database.
• Insert
• Update
• Delete
• Truncate
INSERT STATEMENT

The SQL Server (Transact-SQL) INSERT statement is used to insert a single record or
multiple records into a table in SQL Server.

Syntax:

INSERT INTO table


(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;

Example:

insert into StudentInfo


Values ('Kedar',null,'shrestha','F','baneshwor','kedar@gmail.com','Male','1994-02-08'),
('Trisha','','pathak','F','kalimati','trishakalimati@hotmail.com','Female','1996-07-09'),
('Sonu','Kumari','Moktan','F','Kalanki','','Female','1997-04-13')
UPDATE STATEMENT

The UPDATE statement is used to modify the existing records in a table.

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example:

Update StudentInfo set Gender = 'Female' where FirstName in ('sita','Mina')


DELETE STATEMENT

The DELETE statement is used to delete existing records in a table.

Syntax:

DELETE FROM table_name


WHERE condition;

Example:

DELETE FROM StudentInfo where section IS NULL


TRUNCATE STATEMENT

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.
Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE StudentInfo


TYPES OF SQL COMMANDS

 DCL (Data Control Language)

Data control commands in SQL allow you to control access to data within the
database.
• Grant
• Revoke
• Alter Password
DATA TYPES

In database, Data Type is type of data that object can holds.


For example : Numeric data, character data, monetary data, data and time data etc.

There are three main categories of data type below:

Numeric Data AlphaNmeric data DateTime

-TinyInt - Varchar - Date


-SmallInt - Char - DateTime
-Int - Text - DateTime2
-BigInt - NVarchar - DateTimeOffset
-Bit - NChar - SmalldateTime
-Money - Ntext - Time
-Float
-Decimal
NUMERIC DATA TYPES
Data type Range Storage
TinyInt 0 to 255 1 Byte
SmallInt -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
Int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes

-2^63 (-9,223,372,036,854,775,808) to 2^63-1


BigInt (9,223,372,036,854,775,807) 8 Bytes
Decimal Upto 38 Digit, <(Decimal (P,S)> 5-17 Bytes Depending on
Precision and Scale

8 Bytes, round up after 15


Float - 3.40e38 to -1.18e-38, 0 and 2.23e-308 to 1.79e308 digit
Bit 1 Byte
0 or 1
Money 8 Bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807
CHARACTER DATA TYPES

Data type Range (n= number of character that is defined) Storage(1character = 1 Byte)

Char Fixed length, syntax = Char(n), eg: Char(5) n Bytes, 5 bytes


Variable length, syntax = varchar(n), eg: Varchar(5) up to 8000 Depends on how many
Varchar bytes. character are stored
Depends on how many
Same as Varchar but it can hold up to 2 GB data character are stored
Varchar(max) Syntax = Varchar(max)

Text Same as varchar(max). Not recommended


Nchar For unicode data, behaviour same as char but use 2 bytes to up to 8000 bytes
store single character. Syntax = Nchar(n).

- Unicode data, behavior same as varchar but use 2 bytes to store


Nvarchar single character. Syntax = Nvarchar(n) up to 8000 bytes
NVarchar(max)
Syntax = Nvarchar(Max). Up to 2 GB
CHARACTER DATA TYPES

 Use char when the sizes of the column data entries are consistent.

 Use varchar when the sizes of the column data entries vary considerably.

 Use varchar(max) when the sizes of the column data entries are extensively high,
and the size might exceed 8,000 bytes.
DATE AND TIME DATA TYPES

Data type Range Storage(1character = 1 Byte)


‘0001-01-01’ to ‘9999-12-31’, default format YYYY-MM-DD,
Date syntax : date 3 Bytes
Date : ‘1753-01-01’ to ‘9999-12-31’. Time : 00:00:00 to
23:59:59.997
DateTime Syntax : dateTime, default format YYYY-MM-DD HH:MM:SS 8 Bytes
0001-01-01 To 9999-12-31, Time :00:00:00 through
23:59:59.9999999 TimeZone :-14:00 through +14:00
10 Bytes
DateTimeOffset

Date : ‘0001-01-01’ to ‘9999-12-31’, Time : ‘00:00:00 through


DateTime2 23:59:59.9999999’ 8 Bytes
smallDateTime 1900-01-01 through 2079-06-06, Time : 00:00:00 to 4 Bytes
23:59:59
Other DataTypes

-Table
-Cursor
-XML
OPERATORS

An operator is a symbol specifying an action that is performed on one or more expressions.


Following are the main categories of operators

 Comparison Operators
 Logical Operator
 Arithmetic Operators
 Compound Operators
COMPARISON OPERATORS

Comparison operators are used in the WHERE clause to determine which records to
select. Here is a list of the comparison operators that you can use in SQL Server
(Transact-SQL):
Comparison Operator Description
= Equal
<> Not Equal
!= Not Equal
> Greater Than
>= Greater Than or Equal
< Less Than
<= Less Than or Equal
!> Not Greater Than
!< Not Less Than
IS NULL NULL value
IS NOT NULL Non-NULL value
LIKE Pattern matching with %
LOGICAL OPERATORS

The Logical operators are those that are true or false. They return a true or false values to
combine one or more true or false values
Comparison Operator Description
Logical AND compares between two Booleans as expression and returns true when both expressions are
AND
true.
Logical OR compares between two Booleans as expression and returns true when one of the expression is
OR
true.

NOT Not takes a single Boolean as an argument and changes its value from false to true or from true to false....

The IN operator checks a value within a set of values separated by commas and retrieve the rows from the
IN
table which are matching....
The SQL BETWEEN operator tests an expression against a range. The range consists of a beginning,
BETWEEN
followed by an AND keyword and an end expression....

The EXISTS checks the existence of a result of a subquery. The EXISTS subquery tests whether a
EXISTS
subquery fetches at least one row. When no data is returned then this operator returns 'FALSE'...

ANY compares a value to each value in a list or results from a query and evaluates to true if the result of an
ANY
inner query contains at least one row
ALL is used to select all records of a SELECT STATEMENT. It compares a value to every value in a list or
ALL results from a query. The ALL must be preceded by the comparison operators and evaluates to TRUE if the
query returns no rows...
SOME compare a value to each value in a list or results from a query and evaluate to true if the result of an
SOME
inner query contains at least one row
ARITHMETIC OPERATORS

Arithmetic operators perform mathematical operations on two expressions of one or


more of the data types of the numeric data type category
Comparison Operator Description
+ (Add) Addition

- (Subtract) Subtraction

* (Multiply) Multiplication

/ (Divide) Division

% (Modulo) Returns the integer remainder of a division. For example, 12 % 5 = 2 because the remainder of 12
divided by 5 is 2.
COMPOUND OPERATORS

Compound operators execute some operation and set an original value to the result of the
operation.

Comparison Operator Description

+= Adds some amount to the original value and sets the original value to the result.

-= Subtracts some amount from the original value and sets the original value to the result.

*= Multiplies by an amount and sets the original value to the result.

/= Divides by an amount and sets the original value to the result.

For example, if a variable @x equals 35, then


@x += 2 takes the original value of @x, add 2
and sets @x to that new value (37).
AGGREGATE FUNCTION

An aggregate function allows you to perform a calculation on a set of values to return a


single scalar value.

•AVG – calculates the average of a set of values.

•COUNT – counts rows in a specified table or view.

•MIN – gets the minimum value in a set of values.

•MAX – gets the maximum value in a set of values.

•SUM – calculates the sum of values.


EXAMPLES

Count Function:

SELECT COUNT(*) AS TotalRecords FROM ProductSales

Average Function:

Select AVG(Amount) FROM ProductSales WHERE ProductName = 'LAPTOP'

MIN & MAX Function:

Select MIN(Amount) As Minimum, Max(Amount) As Maximum FROM ProductSales WHERE ProductName =


'LAPTOP'

Sum Function:

SELECT SUM(AMOUNT) TotalSales FROM ProductSales WHERE ProductName = 'LAPTOP'


HAVING CLAUSE

The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.

Syntax:

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

Example:

SELECT ProductName, Brand, COUNT(*) AS TotalRecord, SUM(AMOUNT) AS Amount


FROM ProductSales
WHERE ProductName = 'LAPTOP’
GROUP BY ProductName, BRAND
HAVING COUNT(*) > 1
ORDER BY ProductName DESC
GROUP BY CLAUSE

The SQL GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.

Syntax:

SELECT Column1, Column2, ... Column_n,


aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY Column1, Column2, ... Column_n

Example:

SELECT ProductName,SUM(AMOUNT) AS TotalAmount FROM ProductSales


GROUP BY ProductName
ORDER BY KEYWORD

The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

Syntax:

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Example 1:
SELECT ProductName,SUM(AMOUNT) AS TotalSales FROM ProductSales
GROUP BY ProductName ORDER BY ProductName desc

Example 2:
SELECT * FROM ProductSales order by ProductName ASC,Brand desc
CONSTRAINTS

Constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column when no value is specified
INDEX - Used to create and retrieve data from the database very quickly
NOT NULL CONSTRAINTS

The NOT NULL constraint enforces a column to NOT accept NULL values..

Example:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

To remove NOT NULL CONSTRAINT

ALTER TABLE PERSONS


ALTER COLUMN LASTNAME VARCHAR(255) NULL
UNIQUE CONSTRAINTS

The UNIQUE constraint ensures that all values in a column are different.

Example1:
CREATE TABLE Persons (
ID int UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

Example2 (if table is already created):


ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID);

Remove Unique Constraint

ALTER TABLE Persons


DROP CONSTRAINT UC_Person;
PRIMARY KEY CONSTRAINTS

The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values, and cannot contain NULL values. A table
can have only one primary key, which may consist of single or multiple fields.

Example1:
CREATE TABLE PERSONS (
ID INT PRIMARY KEY,
LASTNAME VARCHAR(255) NOT NULL,
FIRSTNAME VARCHAR(255) NOT NULL,
AGE INT
);

Example and Syntax (if table is already created):


Syntax : ALTER TABLE <table name>
ADD CONSTRAINT <Constraint Name> PRIMARY KEY (ID);
Example :ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID);

Remove Primary Key constraint


ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
FOREIGN KEY CONSTRAINTS

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.
Example1:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (ID)
REFERENCES Persons(PersonID)
);

Example and Syntax (if table is already created):


Syntax : ALTER TABLE <TableName>
ADD FOREIGN KEY (<ColumnName>) REFERENCES <MasterTableN ame>(<ColumnName from master
table>);

Example : ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(ID);
CHECK CONSTRAINTS

The CHECK constraint is used to limit the value range that can be placed in a column

Example1:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

Example and Syntax (if table is already created):


Syntax : ALTER TABLE <TableName> ADD CONSTRAINT <constraintName> CHECK
(Check Condition);

Example : ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City=‘San dnes');

Delete Constraint :
ALTER TABLE Persons
DROP CONSTRAINT chk_age
DEFAULT CONSTRAINTS

The DEFAULT constraint is used to provide a default value for a column.

The default value will be added to all new records IF no other value is specified.

Example1:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Kathmandu'
);

Example and Syntax (if table is already created):


Syntax : ALTER TABLE <tableName>
ADD DEFAULT <Default value> FOR <ColumnName>;

Example : ALTER TABLE Persons ADD DEFAULT 'Kathmandu' FOR City

Delete Constraint :
ALTER TABLE Persons
DROP DF__Persons__City__336AA144; --Constraint Name
JOINS

JOINS are used to retrieve data from multiple tables. A SQL Server JOIN is performed
whenever two or more tables are joined in a SQL statement.

There are 4 different types of joins

SQL Server INNER JOIN (or sometimes called simple join)

SQL Server LEFT OUTER JOIN (or sometimes called LEFT JOIN)

SQL Server RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

SQL Server FULL OUTER JOIN (or sometimes called FULL JOIN)
INNER JOIN

It is the most common type of join. INNER JOINS return all rows from multiple tables
where the join condition is met.

Visual Illustration

In this visual diagram, the SQL Server INNER JOIN returns the shaded area:
INNER JOIN

Syntax

SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Example:

SELECT
Student.FirstName,student.MiddelName,student.Lastname,
Course.[Name]
FROM student
INNER JOIN Course ON student.CourseId= course.CourseID
LEFT OUTER JOIN

This type of join returns all rows from the LEFT-hand table specified in the ON
condition and only those rows from the other table where the joined fields are equal (join
condition is met).

Visual Illustration:

In this visual diagram, the SQL Server LEFT OUTER JOIN returns the shaded area:
LEFT OUTER JOIN

Syntax

SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;

Example:

SELECT
Student.FirstName,student.MiddelName,student.Lastname,
Course.[Name]
FROM student
LEFT JOIN Course ON student.CourseId= course.CourseID
RIGHT OUTER JOIN

This type of join returns all rows from the RIGHT-hand table specified in the ON
condition and only those rows from the other table where the joined fields are equal (join
condition is met).

Visual Illustration:

In this visual diagram, the SQL Server RIGHT OUTER JOIN returns the shaded area:
RIGHT OUTER JOIN

Syntax

SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;

Example:

SELECT
Student.FirstName,student.MiddelName,student.Lastname,
Course.[Name]
FROM student
RIGHT JOIN Course ON student.CourseId= course.CourseID
FULL OUTER JOIN

This type of join returns all rows from the LEFT-hand table and RIGHT-hand table with
nulls in place where the join condition is not met.

Visual Illustration:

In this visual diagram, the SQL Server FULL OUTER JOIN returns the shaded area:
FULL OUTER JOIN

Syntax

SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;

Example:

SELECT
Student.FirstName,student.MiddelName,student.Lastname,
Course.[Name]
FROM student
FULL JOIN Course ON student.CourseId= course.CourseID
DATA INTEGRITY

Integrity or consistency stands for the quality and reliability of data of a database system.
A database is consistent if the data reflects the referenced objects correctly. It is
inconsistent if there exist ambiguous or contradictory tuples, relations or tables in the
database.

Types of integrity
 Domain integrity
 Entity integrity
 Referential integrity
DOMAIN INTEGRITY

Domain integrity specifies that all columns in a relational database must be declared
upon a defined domain.

The primary unit of data in the relational data model is the data item. Such data items are
said to be non-decomposable or atomic.

A domain is a set of values of the same type. Domains are therefore pools of values
from which actual values appearing in the columns of a table are drawn
ENTITY INTEGRITY

Relations are defined as a unique set of tuples(row) where no two tuples have the same
combination of values for all their attributes. To be distinct, they must have some
primary key that allows to reference each tuple.

Entity Integrity is the mechanism the system provides to maintain primary keys. The
primary key serves as a unique identifier for rows in the table. Entity Integrity ensures two
properties for primary keys:

• The primary key for a row is unique; it does not match the primary key of any other row
in the table.
• The primary key is not null, no component of the primary key may be set to null.
REFERENTIAL INTEGRITY

Referential Integrity is the mechanism the system provides to maintain foreign keys. The
definition of a foreign key must specify the table whose primary key is being referenced.
Referential Integrity ensures only one property for foreign keys:

• A valid foreign key value must always reference an existing primary key.

• No operation (INSERT, UPDATE) can create a non-null foreign key unless a corresponding
primary key exists.

• No operation (UPDATE, DELETE) can remove or change a primary key while a referencing
foreign keys exist.
REFERENTIAL INTEGRITY
DML Restrictions with Respect to Referential Actions
DML Statement Issued Against Parent Table Issued Against Child Table

INSERT Always OK if the parent key value is OK only if the foreign key value exists
unique. in the parent key or is partially or all
null.

UPDATE No Action Allowed if the statement does not leave Allowed if the new foreign key value
any rows in the child table without a still references a referenced key value.
referenced parent key value.

DELETE No Action Allowed if no rows in the child table Always OK.


reference the parent key value.

DELETE Cascade Always OK. Always OK.

DELETE Set Null Always OK. Always OK.


REFERENTIAL INTEGRITY -DML OPERATION
Syntax:
ALTER TABLE <TableName>
ADD FOREIGN KEY (<ColumnName>) REFERENCES
MasterTableName(<ColumnName>) ON DELETE CASCADE

Example1 :

ALTER TABLE student


ADD FOREIGN KEY (courseID) REFERENCES
course(Courseid) ON DELETE CASCADE
Example2 :
ALTER TABLE student
ADD FOREIGN KEY (courseID) REFERENCES
course(Courseid) ON UPDATE CASCADE
Example3 :
ALTER TABLE student
ADD FOREIGN KEY (courseID) REFERENCES
course(Courseid) ON DELETE SET NULL
USER-DEFINED FUNCTIONS
Microsoft SQL Server user-defined functions are routines that accept parameters, perform an
action, such as a complex calculation, and return the result of that action as a value. The
return value can either be a single scalar value or a result set.

These functions are created by user in system database or in user defined database. There are
three types of user-defined function

1. Scalar-valued Functions
2. Inline Table-valued function
3. Multi-Statement Table-Valued Function
SCALAR-VALUED FUNCTIONS
User defined scalar function returns single value as a result of actions perform by function.
We return any datatype value from function.

Example:

CREATE FUNCTION <FunctionName>(<@Parameter> <DataType>)


RETURNS <DataType>
AS
BEGIN
DECLARE <@Variable> <DataType>
//Sql Code
RETURN <@Variable>
END
SCALAR-VALUED FUNCTIONS

Example:

CREATE FUNCTION [dbo].[UFN_GETAVERAGEPRICE](@PRODUCTID INT)


RETURNS INT
AS
BEGIN
DECLARE @AVERAGEPRICE FLOAT
SELECT @AVERAGEPRICE = AVG(PURCHASERATE) FROM PURCHASEDETAILS
WHERE PRODUCTID = @PRODUCTID
RETURN @AVERAGEPRICE
END
INLINE TABLE VALUED FUNCTION
User defined inline table-valued function returns a table variable as a result of actions
perform by function. The value of table variable should be derived from a single SELECT
statement.

Example:

CREATE FUNCTION fnGetSupplier(@Address varchar(200))


RETURNS TABLE
As
RETURN (SELECT * FROM Supplier where SupplierAddress = @Address)
MULTI-STATEMENT TABLE VALUED FUNCTION
User defined inline table-valued function returns a table variable as a result of actions
perform by function. The value of table variable should be derived from a single SELECT
statement.

Example:

ALTER FUNCTION [dbo].[UDF_GetSupplierByProduct](@PRODUCTID INT)


RETURNS @Supplier Table
(SupplierName varchar(200),
SupplierAddress varchar(200)
)
as
Begin
insert into @Supplier
SELECT SUPPLERNAME,SUPPLIERADDRESS FROM SUPPLIER AS SP
INNER JOIN PURCHASEDETAILS PD ON SP.SUPPLIERID = PD.SUPPLIERID
WHERE PRODUCTID = isnull(@PRODUCTID,productid)

return
end
STORED PROCEDURE
A stored procedure is a set of Structured Query Language (SQL) statements with an
assigned name, which are stored in a relational database management system as a group, so it
can be reused and shared by multiple programs.

Create Syntax :
CREATE PROCEDURE <ProcedureName>
@Parameter1 <DataType>,
@Parameter2 <DataType>
AS
BEGIN
<SQL statement>
END

Alter Syntax :
ALTER PROCEDURE <ProcedureName>
@Parameter1 <DataType>,
@Parameter2 <DataType>
AS
BEGIN
<SQL statement>
END
STORED PROCEDURE
Example 1:

CREATE PROCEDURE USP_GetStockReport @productid INT


AS
BEGIN

SELECT P.PRODUCTNAME ,P.BRAND,UOM


,SUM(PD.PURCHASEQTY) AS TOTALSTOCK
,MINSTOCKLEVEL ,ISNULL(SUM(PS.SALESQTY),0) AS SOLDOUT
,SUM(PD.PURCHASEQTY)- ISNULL(SUM(PS.SALESQTY),0) AS
REMAININGSTOCK FROM PRODUCTS AS P
LEFT OUTER JOIN PURCHASEDETAILS AS PD
ON P.PRODUCTID = PD.PRODUCTID
LEFT OUTER JOIN PRODUCTSALES AS PS
ON P.PRODUCTID = PS.PRODUCTID
WHERE (p.ProductID = @productid OR @productid IS NULL)
GROUP BY P.PRODUCTNAME,P.BRAND,UOM, MINSTOCKLEVEL
HAVING SUM(PD.PURCHASEQTY)- ISNULL(SUM(PS.SALESQTY),0) >
MINSTOCKLEVEL
END
ENTITY RELATIONSHIP MODEL (ERM OR ER MODEL)

The entity-relationship model (or ER model) is a way of graphically representing the


logical relationships of entities (or objects) in order to create a database

The structure for a database is represented as a diagram, called an entity-relationship


diagram (or ER diagram).

Relationships are represented as lines connecting the points, polygons, circles, or ovals.
Any ER diagram has an equivalent relational table, and any relational table has an
equivalent ER diagram.

ER diagramming is an invaluable aid to engineers in the design, optimization, and


debugging of database programs.
SYMBOLS FOR ER-DIAGRAM

Symbol Symbol Name Representation Defination

Rectangle Strong Entity -Objects or items of


interest Like
student, Course etc
Oval Attributes - facts about, or properties
of an entity like
studentId ,Name etc

Diamond Relationship - links between entities

Rectangle Weak Entity - A weak entity is one that


with double can only exist when owned
Line by another one
Eg: Information of dependents of a person’s bank account or Insurance policy.
SYMBOLS FOR ER-DIAGRAM

Diamond Weak Relationship - links week entities


with double
line

Oval Multi valued - A multivalued attribute can have more than


Attribute one value at a time for an attribute.

For ex., skills of a surgeon is a multivalued attribute since a surgeon can have more than one skill.
RELATION SYMBOLS FOR ER-DIAGRAM

One To One

One To Many

Many To Many
ER-DIAGRAM

Purchase
Size SupplierID Qty
Brand SupplierID
Name
ProductID
Name
Address

Product Product
Supplier
Purchase
Product ID

er Name
d uct m Address
Pro us to
ID C ID

er
Qty s t om Contact
Sales Cu ID

Product
Sales Customer
DATA MODELING

Data modeling is a technique for defining business requirements for a database. It is


sometimes called database modeling because a data model is eventually implemented in a
database

Types of data Modeling

1. Conceptual Data Model


2. Logical Data Model
3. Physical Data Model
CONCEPTUAL DATA MODEL

Conceptual Data Model identifies the highest-level relationships between different entities. It
typically includes only the main concepts and the main relationships among entities.

Product Supplier
1 Purchase
ProductID SupplierID
1
ProductName N PurchaseID SupplierName N
Size N M PurchaseDate N Address N
M
Brand N PurchaseRate N SupplierContact N

UOM N PurchaseQTY N

MinStockLevel N

M
Product Sales Customer
SalesID CustomerID
SalesDate N M FirstName N
SalesQTY N 1 MiddleName N

LastName N

SupplierContact N

Addresss N
LOGICAL DATA MODEL

Logical ERD also models information gathered from business requirements. It is more
complex than conceptual model in that column types are set.

Product Supplier
1
ProductID Int Purchase SupplierID int
1
ProductName Varchar(50) N PurchaseID int SupplierName Varchar(200) N
Size Varchar(10) N M PurchaseDate DateTime N Address Varchar(50) N
M
Brand Varchar(50) N PurchaseRate Float N SupplierContact Varchar(50) N

UOM Varchar(10) N PurchaseQTY int N

MinStockLevel Int N

M
Product Sales Customer
SalesID int CustomerID int
SalesDate DateTime N M FirstName Varchar(50) N
SalesQTY INT N 1 MiddleName Varchar(50) N

LastName Varchar(50) N

SupplierContact Varchar(50) N

Addresss Varchar(50) N
PHYSICAL DATA MODEL

Physical ERD represents the actual design blueprint of a relational database. It represents how
data should be structured and related in a specific DBMS

Product Supplier
1
ProductID Int Purchase SupplierID int
1
ProductName Varchar(50) N PurchaseID int SupplierName Varchar(200) N
Size Varchar(10) N PurchaseDate DateTime N Address Varchar(50) N

Brand Varchar(50) N PurchaseRate Float N SupplierContact Varchar(50) N

UOM Varchar(10) N PurchaseQTY int N


M
MinStockLevel Int N ProductID Int
M
SupplierID int

Product Sales Customer


SalesID int 1 CustomerID int
SalesDate DateTime N FirstName Varchar(50) N
SalesQTY INT N MiddleName Varchar(50) N
M
CustomerID int LastName Varchar(50) N
ProductID Int SupplierContact Varchar(50) N

Addresss Varchar(50) N
DATA BACKUP

Database backup is the process of backing up the architecture and stored data of database
software. A backup is a copy of data from your database that can be used to reconstruct that
data. It enables the creation of a duplicate instance or copy of a database in case the primary
database crashes, is corrupted or is lost.

Major Types of Data backup

1. Full Backup
2. Differential Backup
3. Transaction Log Backup
DATABASE BACKUP

Full Backup
 Backs up the whole database
 Contains all the data in a specific files or set of files group
 Enough log to recover data
 Base of both Differential and Transactional log backup

Differential Backup

 It is not independent backup it must be based on latest full backup


 Contains only the data that has changed since the differential base
 smaller and faster to create backup than the full backup
 Require less disk storage
DATABASE BACKUP

Transaction Log Backup


 Contains all transaction log records that are created after last log backup or the first
full backup matching with log records.

 Serial record of all the transactions that have been performed against the database
since the transaction log was last backed up.

 Database can be recovered to a specific point in time.

 Only valuable under the full recovery model or bulk-logged recovery model
INDEX

A database index allows a query to efficiently retrieve data from a database.


Indexes can be created using one or more columns of a database table. Basically index is used
to improve search performance.

Major Types of Index

1. Clustered Index
2. Nonclustered Index
CLUSTERED INDEXES

Clustered indexes sort and store the data rows in the table or view based on their key
values. These are the columns included in the index definition. There can be only one
clustered index per table, because the data rows themselves can be sorted in only one
order.

 Data is stored in the order of the clustered index


 Only one clustered index per table
 It will be created automatically when a primary key is created
 No clustered index = Heap

Example:
CREATE CLUSTERED INDEX IX_TestTable_ProductId ON dbo.Product
(ProductID);
NONCLUSTERED INDEXES

Nonclustered indexes have a structure separate from the data rows. A nonclustered index
contains the nonclustered index key values and each key value entry has a pointer to the
data row that contains the key value.

 Data is not stored in the order on the non clustered index


 Multiple non clustered index can be created in single table
 Extra storage will be required for non clustered index

Example:
CREATE NONCLUSTERED INDEX IX_Sales_SalesDate ON
dbo.ProductSales (SalesDate);
OBJECT-ORIENTED DATABASE MANAGEMENT SYSTEM

An object-oriented database management system (OODBMS), sometimes shortened


to ODBMS for object database management system), is a database management system
(DBMS) that supports the modelling and creation of data as objects.

An object database is a database management system in which information is represented


in the form of objects as used in object-oriented programming. Object databases are
different from relational databases which are table-oriented

You might also like