Professional Documents
Culture Documents
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.
Hierarchical Model
Network Model
Entity-Relationship Model
Relational Model
One-to-Many
One-to-one
Many-to-many
ONE-TO-MANY
One-to-One mappings are used to represent the relationship between a single objects.
ONE-TO-ONE
MANY-TO-MANY
They require the creation of an intermediate table for managing the associations between
the source and target records.
MANY-TO-MANY
WHAT IS NORMALIZATION ?
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 Norma Form was introduced by Edgar Codd in 1970. 1NF sets the very basic rules for an
organized database.
Second normal form (2NF) further addresses the concept of removing duplicative data. It
was originally defined by Edgar Codd in 1971.
Instances : A instance of the database is copy of the SQLserver.exe executables that runs as
an operating system.
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.
Any objects that you have created in tempdb will be gone once
the server restarts
ARCHITECTURE OF MSSQL DATABASE SERVER
• Data Files
• Log Files
• Data Files :It contains data and objects such as tables, indexes, stored
procedures, and views
Secondary Data Files : It is an optional data files. We can put multiple secondary
files in single database in different disk drives.
The recommended file name extension for secondary data files is .ndf.
SQL
Stands for Structure Query Language
o “Insert”
o “Update”
o “Select”
o “Delete”
o “Create”
o “Drop”
TYPES OF SQL COMMANDS
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:
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;
Examples:
ALTER TABLE StudentInfo
ADD StudentAge INT
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:
Example:
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Syntax:
Example:
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.
Syntax:
Example:
Data control commands in SQL allow you to control access to data within the
database.
• Grant
• Revoke
• Alter Password
DATA TYPES
-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)
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
-Table
-Cursor
-XML
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
- (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.
+= 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.
Count Function:
Average Function:
Sum Function:
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:
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:
Example:
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:
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 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 NOT NULL constraint enforces a column to NOT accept NULL values..
Example:
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
);
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
);
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)
);
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)
);
Delete Constraint :
ALTER TABLE Persons
DROP CONSTRAINT chk_age
DEFAULT CONSTRAINTS
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'
);
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.
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.
Example1 :
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:
Example:
Example:
Example:
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:
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.
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
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
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
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.
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
Serial record of all the transactions that have been performed against the database
since the transaction log was last backed up.
Only valuable under the full recovery model or bulk-logged recovery model
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.
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.
Example:
CREATE NONCLUSTERED INDEX IX_Sales_SalesDate ON
dbo.ProductSales (SalesDate);
OBJECT-ORIENTED DATABASE MANAGEMENT SYSTEM