0% found this document useful (0 votes)
77 views21 pages

SQL Server 2008: Master

A database is a collection of objects stored on a SQL Server including tables, views, stored procedures and other objects. There are two types of objects - system objects which are created during SQL Server installation and user objects which are created by users. The master database contains login information and configuration settings. The model database acts as a template for new databases. The msdb database stores SQL Agent job information. The tempdb database is used for temporary storage and recreated each time SQL Server starts.

Uploaded by

chengavijay
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views21 pages

SQL Server 2008: Master

A database is a collection of objects stored on a SQL Server including tables, views, stored procedures and other objects. There are two types of objects - system objects which are created during SQL Server installation and user objects which are created by users. The master database contains login information and configuration settings. The model database acts as a template for new databases. The msdb database stores SQL Agent job information. The tempdb database is used for temporary storage and recreated each time SQL Server starts.

Uploaded by

chengavijay
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

SQL Server 2008

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.

There are two types of Objects in SQL SERVER. They are

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:

 All logins, or roles, that the user IDs belong to


 Every system configuration setting (e.g., data sorting information, securit implementaion, default
language)
 The name of and information about the databases within the server
 The location of databases
 How SQL Server is initialized
 Specific system tables holding the following information .
 How the cache is used
 Which character sets are available
 A list of the available languages
 System error and warning messages
 Special SQL Server objects called assemblies

The Master database is the security guard of SQL Server.

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 :

 Using the SQL Server Management Studio graphical interface


 Using T-SQL code

A minimum amount of information is required to create a database :

 The name of the database will be given


 How the data will be sorted
 The size of the database
 Where the database will be located
 The name of the files used to store the information contained within the databse
You have to give a Database name, the SQL Server will take default values to the remaining. If you want
to can change them.

Creating a database using the SQL Server Management Studio


1. Select Star t All Programs  Microsof SQL Server 2005/2008 SQL Server Management
Studio. Or Type ssms Run prompt.
2. Connect to the Server by providing User name and Password.
3. In Object Explorer, right click on the Databases node and select “New Database”
4. Specify a name to the database and click OK. It adds your database under the Databases node in
Object explorer.

Note :- Every database physically maintains two files internally, those are .mdf and .ldf file which are
located in the following location:

<drive>:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data

Creating a Database using T-SQL code in Query Pane


1. From the standard toolbar of SQL Server Management Studio, select New Query.
2. In the query pane, enter the following T-SQL script:

CREATE DATABASE <db_name>

E.g:- CREATE DATABASE Employee

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.

The syntax for creating a schema is as follows:

CREATE SCHEMA schema_name AUTHORIZATION owner_name

For Example,

CREATE SCHEMA EmployeeDetails AUTHORIZATION dbo

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.

The Rules of Tables

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.

The different Data Types are given in the following table :

Data Type Description Storage


TinyInt Stores whole numbers from 0 to 255 1 byte
smallInt A smaller version of int. Can store values 2 bytes
between -32,768 and 32,767
Int Can store whole from -2,147,483,648 to 4 bytes
2,147,483,647
BigInt Can hold numbers ranging from -263 to 263 8 bytes
Bit Can hold a value either 1 or o. Nulls not 8-bit fields take up 1 byte of data
allowed
Decimal/Numeric Used for numbers with fixed precision and Depends on precision. 1 – 9
scale. When maximum precision is used, 5bytes, 10-19 9 bytes, 20-28 13
values can range from -1038 +1 to 1038-1 bytes, 29-38 17 bytes
Float Can hold positive and negative numbers 8 bytes
from -1.79E + 308 to 1.79E+308
Money Can store decimal data ranging from -263 to 8 bytes
263, scaled to four digits of precision. It
offers accuracy to 1/10000 of a monetary
unit
SmallMoney A smaller version of money. Can store 4 bytes
decimal data scaled to four digits of
precision. Can store values from -
214,748.3648 to 214,748.3647
DateTime Holds valid dates from January 1, 1753 to 4 bytes
December 31, 9999.

SmallDateTime Consists of two 2-byte integers. Can store 4 bytes


dates only between 1/1/1900 and 6/6/2079.

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

VarBinary(MAX) 231-1 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.

TimeStamp Generates a unique binary value that SQL 8 bytes


Server automatically creates when a row is
inserted and that SQL Server updates every
time that the row is edited
UniqueIdentifier A globally unique identifier (GUID) that is 16 bytes
automatically generated when the
NEWID() function is used.

Xml Stores Xml data. You can store xml Cannot exceed 2 GB
instances in a column, or a variable of xml
type

Creating a Table in Management Studio

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.

Creating a Table using T-SQL code in Query Pane


The basic syntax for creating a Table:

CREATE TABLE <database_name>.<schema_name>.<table_name>(

Column_name1 <dtype> [width],

Column_name2 <dtype>[width],
…………………………

Column_namen <dtype>[width])

For example,

CREATE TABLE Employee.EmployeeDetails.Emp(EmployeeId int, EmployeeName varchar(20),


Designation varchar(20), DateOfJoin datetime, Salary decimal(8,2), DepartmentNo int)

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.

Primary Key Constraints


A primary key constraint is a column or set of columns that uniquely identify a row in the table.
Although you can designate more than one field as primary key, each table can have onley one primary
key. Every Primary Key should meet the following criteria:

 Short
 Stable
 Simple

We can create a Primary Key at two levels. One is at column level and another one is at table level.

Creating a Primary Key at Column level

Syntax is as follows:

CREATE TABLE EmployeeDetails.Emp(EmployeeID int Constraint EmpID_PK Primary Key, …..)

Creating a Primary Key at Table level

Syntax is as follows:

CREATE TABLE EmployeeDetails.Emp(EmployeeId int, EmployeeName varchar(20), Designation


varchar(20), DateOfJoin datetime, Salary decimal(8,2), DepartmentNo int, Constraint EmpID_PK
Primary Key(EmployeeID))

Creating a Composite Primary Key at Table Level


CREATE TABLE BankDetails(CityCode varchar(10), Branhcode varchar(10), Location varchar(10),
Constraint CC_BC_PK Primary Key(CityCode, Branchcode)

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.

Creating a default value is as follows:

CREATE TABLE BANK(CustomerID int, CustomerName varchar(10), Balance decimal(7,2) Default 1000)

Table 4.2. Examples of Default Constraints


Expressio Result
n
GeTDate() Sets the default value to the current date
Null Sets the default value to Null
7 Sets the default value to the number 7
'Hello' Sets the default value to the string "Hello"

Not Null Constraints

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.

Creating Check constraint at Column level

CREATE TABLE BANK(CustomerID int, CustomerName varchar(20), Balance decimal(7,2) Constraint


Balance_CK Check(Balance>=1000)

Creating Check Constraint at Table level

CREATE TABLE BANK(CustomerID int, CustomerName varchar(20), Balance decimal7,2), Constraint


Balance_CK Check(Balance Between 1000 and 9999)

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.

The syntax is as follows:

ColumnName <data_type>[width] Identiy[(identity seed, identity increment)]

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:

CREATE TABLE BANK(CustomerID int identiy(101, 1), Cname varchar(20), Balance


decimal(7,2))

Foreign Key Constraints

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

A one-to-many relationship is by far the most common type of relationship. In a one-to-many


relationship, a record in one table can have many related records in another table. A common
example is a relationship set up between a Customers table and an Orders table. For each
customer in the Customers table, you want to have more than one order in the Orders table. On
the other hand, each order in the Orders table can belong to only one customer. The Customers
table is on the one side of the relationship, and the Orders table is on the many side. For this
relationship to be implemented, the field joining the two tables on the one side of the relationship
must be unique.

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.

E.g: One-to-Many Relationship

Creating a foreign key at column level


CREATE TABLE EMP(EmployeeID int constraint EmpID_PK Primary Key, EmployeeName varchar(20),
Designation varchar(20),DateOfJoin datetime, Salary decimal(7,2), DepartmentNO int Constraint
DepartmentNO_Ref References Dept(DepartmentNO))

Creating a Foreign key at table level


CREATE TABLE EMP(EmployeeID int constraint EmpID_PK Primary Key, EmployeeName varchar(20),
Designation varchar(20),DateOfJoin datetime, Salary decimal(7,2), DepartmentNO int, Constraint
DepartmentNO_Ref Foreign Key(DepartmentNO) References Dept(DepartmentNO)

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.

The constraints are :

ON DELETE NO ACTION

ON DELTE CASCADE

ON DELETE SET NUL

ON DELETE SET DEFAULT

ON UPDATE NO ACTION

ON UPDATE CASCADE

ON UPDATE SET NULL

ON UPDATE SET DEFAULT

NO ACTION is default if ON DELETE or ON UPDATE is not specified.

E.g:

DepartmentNO int constaint DepartmentNO_Ref Reference Dept(DepartmentNO) ON DELETE CASCADE


ON UPDATE CASCADE

INSERT Command
This command is used to insert records into a table.

The syntax for inserting Records into a Table is as follows:

INSERT INTO <schema_name>.<table_name> [(col1, col2,….coln)] values(val1, val2,…..valn)

E.g :

INSERT INTO EmployeeDetails.Emp(EmployeeID, EmployeeName, Designation, DateOfJoin, Salary,


DepartmentNo) VALUES(101,’Vijay’,’Programmer’,’01/01/2008’, 20000,10)

ALTER TABLE Command

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:

Increase or Decrease the width of a column


Change data type of a column
Change NULL to NOT NULL and NOT NULL to NULL
Add a new column to a table
Drop an existing column from the table.
Add a constraint to a column of the table
Drop an existing constraint on a column of the table

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]

Synatax to Add a new column to the table:

ALTER TABLE <table_name> ADD <column_name> <data_type>[width]

Syntax to add a column with a constraint:

ALTER TABLE <table_name> ADD <column_name> <data_type>[width] Constraint <const_name>


<cons_type>

Syntax to Drop an existing column:

ALTER TABLE <table_name> DROP COLUMN <col_name>

Syntax to Add a Constraint to a column:

ALTER TABLE <table_name> ADD Constraint <const_name> <const_type>(column_name)

Syntax to drop an existing constraint on a column:

ALTER TABLE <table_name> DROP Constraint <const_name>

DROP Command :
If we want to destroy the existing tables present in a database permanently we use the Drop Command

Syntax:

DROP TABLE <table_name>

E.g:

DROP TABLE Emp

TRUNCATE Command
Removes all rows from a table. We cannot use WHERE clause.

Syntax:

TRUNCATE TABLE <table_name>

TRUNCATE TABLE Emp

DELETE Command
If we want to Delte all rows or required rows based on a condition from a table, we use DELETE
command.

Syntax:

DELETE FROM <table_name>[conditions]

E.g:

DELETE FROM Emp

It deletes all rows present in the table.

DELETE FROM Emp where EmployeeNo=105

It deletes only the row that contain 105 in EmployeeNo column.

SELECT Statement
We use SELECT statemet to retrieve data from one or more tables. The basic Syntax is:

SELECT <*|column_list> FROM <table_list> [conditions]

E.g:

SELECT * from Emp

It retrieves all columns from the Emp table.

SELECT EmployeeNO, EmployeeName,Salary FROM Emp

It retrieves only the EmployeeNo, EmployeeName, Salary data From Emp table.

SELECT * FROM Emp WHERE Emp=101

It retrieves only the Employee Record with EmployeeNo =101


Column Alias and Table Alias
If we specify an Alias name to a column then it is called as column Alias. If we specify an Alias name to a
table, then it is called as Table Alias.

E.g: Column Alias

SELECT EmployeeNO AS Empno, EmployeeName, Salary FROM Emp

E.g: Table Alias

SELECT EmployeeNO, EmployeeName FROM Emp AS Employees

Handling Null values


The value NULL means the data value for the column is unknown or not available, so we cannot use
equality condition while getting the data based on NULL values.

E.g:

SELECT * FROM Emp WHERE EmployeeName=NULL

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:

SELECT * FROM Emp WHERE EmployeeName IS NULL

Using Expressions in SELECT statement


We can include expressions in a SELECT Statemet. For example.

SELECT CustomerID, City +’, ‘ + Region +’ ‘+PostalCode AS Address FROM Customers.

SELECT EmployeeID, EmployeeName+’ ‘+Designation+’ ‘+DepartmentNO AS CompanyDetails FROM


Emp

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:

SELECT <select_list> FROM <table_name>


[WHERE searcg_expression]

[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:

SELECT * FROM Emp WHERE Designation=’Programmer’

SELECT * FROM Emp WHERE EmployeeID IN(101,104)

SELECT * FROM Emp WHERE EmployeeID NOT IN(101,103

SELECT * FROM Emp WHERE EmployeeName=’Vijay’ AND Salary=20000

SELECT * FROM Emp WHERE EmployeeName=’Vijay’ OR DepartmentNO=10

SELECT * FROM Emp WHERE EmployeeID Between 101 and 105

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:

SELECT DepartmentNO, MAX(Salary) FROM Emp GROUP BY DepartmentNO

It gives the highest salaries for each department.

SELECT DepartmentNO, COUNT(*) FROM Emp GROUP BY DEPTNO

It gives the Number of employees working for each department.

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:

SELECT DepartmentNO, COUNT(*) FROM Emp WHERE Designation=’Clerak’ GROUP BY DepartmentNO


HAVING COUNT(*)>1

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:

SELECT * FROM Emp ORDER BY Salary

SELECT * FROM Emp ORDER BY Salary, Commission

SELECT * FROM Emp ORDER BY Salary DESC

FOR XML clause


We can use the FOR XML clause to return data as an XML document. The various modes that can be
specify are RAW, AUTO, EXPLICIT.

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

Creating Top Value Queries


We use the TOP clause to limit the number of rows hat SQL Server includes in the output.

E.g:

SELECT TOP 10 OrderDate, Freight FROM Orders ORDER BY Freight DESC

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 : To find the details of employees earning the highest salary.

SELECT * FROM Emp WHERE Salary=(SELECT MAX(Salary) FROM Emp)

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.

Multiple Row Sub Queries


The sub queries that returns more than one row are called Multiple Sub Queries. Here we use Multiple
Row operators to get multiple rows in result set. They are IN, ANY, ALL. In place of ANY we can use
SOME operator also.

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)

E.g : To find the details of seniors in each department.

SELECT * FROM Emp WHERE DatoOfJoin IN(SELECT MIN(DateOfJoin) FROM Emp GROUP BY
DepartmentNO)

Correlated Sub Queries


.
.
.
.
.
.
.
.
.
.
JOINS
Joins can be used to retrieve data from two or more tables based on logical relationships between the
tables. When you build a system based on normalized table structures, you must join the tables back
together to see the data in useable format. For example, if you have separated customers, orders, and
order details, you need to join these tables in a query to see the name of the customer who placed an order
for a particular item. The various types of joins are
1. Inner Joins
2. Outer Joins
I. Left Outer Join
II. Right Outer Join
3. Self Joins
4. Cartesian Joins(Full Joins)

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

You might also like