SQL Server 2008: Master
SQL Server 2008: Master
What is a Database?
A client-server system is made up of two components: an application that is used to present the
application's data, and a database system that is used to store it. An application may be designed in Visual
Studio 2005, Microsoft Access, or some other graphical user interface.
A database is a collection of objects stored on a SQL Server. This collection of objects includes all the
tables, views, stored procedures, functions, and other objects necessary to build a database system. If
tables relate to one another, they should generally be in the same database.
1. System Objects
2. User Objects
System Objects
When the Sql Server is installed, the setup creates the System Objects. These include System Databases,
System Tables, Views, Stored Procedures and other Objects. The System Databases are Mater, Model,
Msdb, Tempdb. As the name implies, these databases are part of the system, and most of them are
required for Server to run properly.
User Objects
The User creates User Objects. User objects include the databases, stored procedures, functions,
and other database objects. The user can add and drop user objects as necessary.
master
The Master database is the most important database and heart of SQL Server. It should not be altered
directly. If it should become corrupted, there is a very good chance that SQL Server will not work
correctly. The Master database contains the following crucial information:
model
The model database acts as template database for the user databases. Whenever you create a
database, it has to be modeled on a predefined set of criteria. For example, if you want all your databases
to have a specific initial size, or to have a specific set of information, you would place this information
into the model database which acts as template database for further databases. If you wanted all your
databases to have a specific table , then you would put this table in the model database.
The model database is used as the basis for the tempdb database.
msdb
The msdb database provides the necessary information to run jobs to SQL Server Agent.
SQL Server Agent is a Windows service in SQL Server that runs any scheduled jobs that you set
up (e.g., jobs that contain backup processing). A job is a process defined in SQL Server that runs
automtically without any manual invervention to start it. You should not alter this database directly. Many
other processes use msdb. For example, when you create a backup or perform a restore, msdb is used to
store information about these tasks.
tempdb
The tempdb database is a temporary database whose lifetime is the duration of a SQL Server session;
once SQL Server stops, the tempdb database is lost. When the SQL Server starts up again, the tempdb
database is re-created, fresh and new, and ready for use. When you wish to store a certain set of data for
processing at a later time, you would put it in tempdb database.
Creating a Database
We can create a Database in two different ways in SQL Server :
Note :- Every database physically maintains two files internally, those are .mdf and .ldf file which are
located in the following location:
3. Execute the code by pressing F5 or Ctrl+E, or by clicking the Execute Query toolbar button.
4. The result will be shown in the result’s pane at bottom.
Schemas
Schema is a method of creating a group and objects within that group, which can then be used to grant
or revoke permissions as a group to SQL Server connections. Tables with shared information can be
grouped and placed in a Schema. So by having schema within our solution and assigning objects to the
schema not only are we improving securiy, but we are also grouping logical units of the database
together, making our solution easier to understand and use.
For Example,
Tables
Tables are generally the first thing we add to a SQL Server database.These are where the data is kept
within the database. Each table contains inforamation about a subject. For example, one table may contain
information about customers, whereas another table may contain information about order. Each table in a
database must have a unique name. A table is made up of rows and columns.
Columns
We refer columns as fields. Each field has a unique name and contains a specific piece of information
about the row. For example, within the Customers table, the fields included may be the CustomerID,
CompanyName, ContactFirstName, ContactLastName, and so on.
Rows
A row is made up of one cell from every column defined for the table. Each row contains an individual
occurance of the subject modelled by the table. For example, each in the Customer table contains
information about a specific customer. Rows are also called as Records.
1. A table must have a unique name. Each table in a system must store data about a single entity.
An entity usually represents a real-life object or even. Exampls of objects are customers,
employees, and inventory item. Examples of events include orders, appoiments, and doctor visits.
2. Each table must contain a unique identifier. Without a unique identifier, it becomes
programmatically impossible to address a row uniquely. It can be done by using a primary key
Creating a Table
Before creating a table in SQL Server, we would know about various data types that can be used in the
table.
Data Types
In a Database, each column, local variable, expression, and parameter has a related data type. A data type
is an attribute that specifies the type of data that the object can hold. For example, integer data, character
data, monetory data, date and time data, binary strings and so on.
Char Holds from 1 to 8,000 bytes of fixed- The number of bytes corresponds
length non-Unicode characters to the length of the field
(regardless of what is stored in it).
VarChar A variable-length string that can hold 1 to 1 byte per character stored.
VarChar(max) 8,000 non-Unicode characters. 231-1 bytes
Text Stores up to 2,147,483,647 characters of 1 byte for each character of storage
non-Unicode data
NChar Can contain from 1 to 4,000 Unicode Twice the amount of bytes of Char.
characters. Corresponds to the length of the
field (regardless of what is stored
in it).
NText Can hold data up to 1,073,741,823 Twice the amount of bytes of Char.
Unicode characters Corresponds to the length of the
field (regardless of what is stored
in it).
NvarVhar[(n|(max)] Can contain from 1 to 4,000 Unicode 2 bytes per character stored.
characters
231-1 for (max)
Real A smaller version of float. Contains a 4 bytes
single-precision floating-point number
from 3.40E + 38 to 3.40E + 38.
Binary Holds from 1 to 8,000 bytes of fixed- Whatever is in the column, plus 4
length binary data additional bytes.
VarBinary Can hold variable-length binary data from Varies from 1 to 8000 bytes.
1 to 8000 bytes
Image Consists of linked data pages of binary Depends on what is stored in it.
data. It can contain up to 2,147,483,647
bytes of binary data
SQL_Variant New to SQL 2000. Can store int, binary, Varies
and char values. Is a very inefficient data
type.
Xml Stores Xml data. You can store xml Cannot exceed 2 GB
instances in a column, or a variable of xml
type
1. In the Object explorer, right-click the Tables node of the database to which you want to add a
table and select New table. Table Designer appears
2. Enter the column names, data types, and length for each field in the table.
3. Designate whether each field allows nulls.
4. Enter the other properties for the table.
5. Click the Save button on tool bar and give a unique name to the Table.
Column_name2 <dtype>[width],
…………………………
Column_namen <dtype>[width])
For example,
Constraints
Constraints limit or control the type of data that the user can enter into tables. There are seven types of
constraints. They are Primary Key constraints, Foreign Key constraints, Default constrains, Not Null
constraints, Check constraints, Rules, and Unique constraints.
Short
Stable
Simple
We can create a Primary Key at two levels. One is at column level and another one is at table level.
Syntax is as follows:
Syntax is as follows:
Default Constraints
A default constraint is a value that SQL Server automatically places in a particular field in a table. A
default value can be a constraint, Null, or a function. All fields excepts identity and time stamp fields can
contain default values. Each column can have one default constraint. We can enter a default constraint
in the properties of the desired field.
CREATE TABLE BANK(CustomerID int, CustomerName varchar(10), Balance decimal(7,2) Default 1000)
If we assign Not Null constraint to column, then that column will not allow Null values.
Syntax :
CREATE TABLE BANK(CustomerID int Not Null, Cname varhcar(20), Balance decimal(7,2) Not Null)
Check Constraints
Check constraints limit the range of values that a user can enter into a column. We can enter as many
check constraints as we want for a particular column.
Unique Constraints
A Unique constraint requires that each entry in a particular column be unique. If we assign a Unique
constraint on a column, then that column will not allow duplicate values.
CREATE TABLE BANK(CustomerID int Unique, CustomerName Varchar(20), Balance decimal(7,2)
Identity Columns
Identity columns provide an autoincrementing value for a table. You should use an identity
column as the primary key field for any table that has no natural primary key that is short, stable,
and simple. Identity columns are often of the int data type. You use the properties of the field to
designate a column as an identity column. Notice that after you designate a column as an identity
column, you can designate both the identity seed and the identity increment. The identity seed is
the starting value for the field. The identity increment is the value by which each automatically
assigned value is incremented. For example, an identity field with an identity seed of 100 and an
identity increment of 5 assigns the values 100, 105, 110, and so on.
Identity seed is the starting value for the column. The identity increment is the value by which
each automatically assigned value is incremented.
E.g:
A foreign key constraint consists of a column or a set of columns that participates in a relationship with
primary key table. The Primary key is on the ONE SIDE of the relationship, wheereas the foreign key is
one the MANY SIDE of the relationship. A table can have only one primary key, but it can have multiple
foreign key. Each foreign key relates to a different primary key in a separate table.
Relationships
Three types of relationships can exist between tables in a database:
1. One-to-Many
2. One-to-One
3. Many-to-Many
One-to-Many
One-to-One
In a one-to-one relationship, each record in the table on the one side of the relationship can have
only one matching record in the table on the other side of the relationship. This relationship is
not common and is used only in special circumstances
Many-to-Many
In a many-to-many relationship, records in both tables have matching records in the other table. You
cannot directly define a many-to-many relationship; you must develop this type of relationship by
adding a table called a junction table. You relate the junction table to each of the two tables in one-to-
many relationships. An example is an Orders table and a Products table. Each order probably contains
multiple products, and each product is found on many different orders. The solution is to create a third
table called Order Details. You relate the Order Details table to the Orders table in a one-to-many
relationship based on the OrderID field. You relate the Order Details table to the Products table in a one-
to-many relationship based on the ProductID field.
The foreign key constraint enforces referential integrity by guaranteeing that changes cannot made to
data in te primary key table if those changes invalidate the link to data in the foreign key table. If an
attempt is made to delete the row in a primary key table or to change a primary key value, the action
will fail when the deleted or changed primary key value corresponds to a value in the foreign key
constraint of another table. To successfully change or delete a row in a Primary key table, you first either
delete or change the foreign key data in the foreign key table.
Cascading Rules
By using cascading referential integrity constrains, you can deifne the actions that the SQL Server takes
when a user tries to delete or update a key in the MASTER table to which existing child table point.
ON DELETE NO ACTION
ON DELTE CASCADE
ON UPDATE NO ACTION
ON UPDATE CASCADE
E.g:
INSERT Command
This command is used to insert records into a table.
E.g :
After creating a table, if we want to make any modifications to the structure of the table we use the
ALTER TABLE command. Using this command we can perform the following:
The syntax to increase/decrease, Change data type and Change NULL to NOT NULL and NOT NULL to
NULL
ALTER TABLE <table_name> ALTER COLUMN <col_name> <data_type> [width] [NULL|NOT NULL]
DROP Command :
If we want to destroy the existing tables present in a database permanently we use the Drop Command
Syntax:
E.g:
TRUNCATE Command
Removes all rows from a table. We cannot use WHERE clause.
Syntax:
DELETE Command
If we want to Delte all rows or required rows based on a condition from a table, we use DELETE
command.
Syntax:
E.g:
SELECT Statement
We use SELECT statemet to retrieve data from one or more tables. The basic Syntax is:
E.g:
It retrieves only the EmployeeNo, EmployeeName, Salary data From Emp table.
E.g:
The above statement will not get any result because no two NULL values can be compared so to get the
data based on NULL values we should use the IS NULL Operator as Following:
CLAUSES
There are different clauses that can be used in the SELECT Statement. They are
1. WHERE
2. GROUP BY
3. HAVING
4. ORDER BY
The complete syntax of the SELECT statement looks like the following:
[GROUP BY group_by_list]
[HAVING search_condition]
[ORDER BY order_expression[ASC|DESC]]
WHERE Clause
The WHERE clause limits the records retrieved by the SELECT statement. A WHERE clause can include
columns combined by the keywords AND , OR, BETWEEN, IN and NOT IN.
E.g:
GROUP BY Clause
The GROUP BY clause partitions the result set into groups based on the values in the columns of the
group_by_list. For example, say the Emp table has 3 values in DepartmentNO column, then a GROUP BY
DepartmentNO clause partitions the result set into 3 groups, one for each value of DepartmentNo.
E.g:
HAVING Clause
The HAVING clause is an additional filter that is applied to the result set. Logically, the HAVING clause
filters rows from the intermediate result built from applying any FROM, WHERE, or GROUP BY clauses in
SELECT statement. HAVING clause is mainly used with GROUP BY Clause.
E.g:
ORDER BY clause
The ORDER BY clause defines the order in which rows in the result set are sorted. Order_list specifies
the result set columns that make up the sort list. The ASC and DESC keywords are used to specify if the
rows are sorted in an ascending order or descending order. By defalut rows are sorted in ascending
order.
E.g:
With the RAW option, SQL Server takes the result of the query and transforms each row in the result set
into an XML element with a generic identifier.
E.g:
SELECT EmployeeID, EmployeeName, Designation,Salary FROM Emp ORDER BY EmployeeID FOR XML
RAW
E.g:
It show the 10 highest freight amounts along with their corresponding order dates.
SELECT TOP 10 PERCENT OrdeDate, Freight FROM Orders ORDER BY Freight DESC
SUB QUERIES
A sub query is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside
another sub query. A sub query can be used anywhere in an expression. Execution of the subquery is like
that – first inner query executes and based upon the result generated by it the outer query will execute
to give the output finally.
E.g:2 To find the details of employees who are earning more than the highest salary of department no
30
SELECT * FROM Emp WHERE Salary>(SELECT MAX(Salary) FROM Emp WHERE DepatmentNO=30)
OR
SELECT * FROM Emp WHERE Salary>ALL(SELECT Salary FROM Emp WHERE DepatmentNO=30)
The ALL operator compares an expression with set of values, where the expression has to satisfy the
condition with all the values.
E.g: To find the details of employees who are earning the highest salary in each department.
SELECT * FROM Emp WHERE Salary IN(SELECT MAX(Salary) FROM EmP GROUP BY DepartmentNO)
SELECT * FROM Emp WHERE DatoOfJoin IN(SELECT MIN(DateOfJoin) FROM Emp GROUP BY
DepartmentNO)
Inner Joins
An inner join is the most common type of join. When you use an inner join, only rows on the one side of
the relationship that have matching rows on the mandy side of the relationship are included in the output.
E.g:
SELECT E.EmployeeName, E.Salary, E.DepartmentNo, D.DepartmentNO, D.Dname, D.Dlocation
FROM Emp E INNER JOIN Dept D ON E.DepartmentNo = D.DepartmentNO