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

B06Y5W4P8L

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 155

SQL for Beginners:

Create Your Own Database FAST!


The Most Important and Core Functions to
Mastering SQL

Gary Mitnick
Copyright © 2017 by Gary Mitnick
All Rights Reserved.

No part of this book may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or by any information storage or retrieval system
without prior written permission from the author or copyright holder except in the case of brief
quotations embodied in reviews.

Although the author has exhaustively researched all sources to ensure the accuracy and completeness
of the information contained in this book, we assume no responsibility for errors, inaccuracies,
omissions, or any inconsistency herein. Any slights of people or organizations are unintentional.
Reader should use their own judgment and/or consult a programming expert for specific applications
to their individual needs.

This eBook was posted by AlenMiler on AvaxHome!

Many New eBooks in my Blog: http://avxhome.in/blogs/AlenMiler

Mirror: https://avxhome.unblocked.tw/blogs/AlenMiler
Table of Contents
Introduction
Introduction to Databases
Guide to SQL Server Editions
Summary
Free Video Course + Programming Newsletter
SQL Server Express setup
Creating a new database
Tables
Columns
Rows
Creating a table in SQL Server
Deleting a Table in SQL Server
Table Design
Keys
Primary Key
Foreign Key
Relationships
Types of relationships
One is to One
One is to Many
Many is to Many
Referential Integrity
Normalization
First Normal Form
Second Normal Form
Third Normal Form
Indexes
Clustered Index
Nonclustered Index
Unique
Adding an index in SQL Server
Queries
Select
SELECT FROM Clause
The WHERE clause
The ORDER BY Clause
Joins
Inner Joins
Outer Joins
Left Outer Join
Right Outer Join
Full Outer Join
Cross Join
Set Operators
Union
Intersect
Except
Modifying data
Transactions
Insert statement
Update statement
Delete statement
Truncate statement
Merge statement
Stored Procedures and Functions
T-SQL
Creating a Stored Procedure
Controlling the execution of the Stored Procedure
IF ELSE
BEGIN END
WHILE BREAK
CASE
Functions
Scalar Functions
Table-Valued Functions
Notes on Functions
Database Administration
Setting up a maintenance plan in SQL Server
Define Back Up Database (Full) Task
Define Database Check Integrity Task
Define Shrink Database Task
Define Reorganize Index Task
Define Rebuild Index Task
Define Update Statistics Task
Define History Cleanup Task
Define Back up Database (Differential) Task
Define Back Up Database (Transaction Log) Task
Define Execute SQL Server Agent Job Task
Define Maintenance Cleanup Task
Report Options
Complete the Wizard
Running the maintenance plan
Emailing the reports.
Setting up Database Mail.
SQL Server Agent
Summary
Database Backup and Recovery
The Transaction Log
Recovery
Recovery Models
Simple Recovery
Full Recovery
Bulk Logged
Changing the Recovery Model
Backups
Full Backup
Differential Backup
Transaction Log Backup
Backup strategy
Full Backup
Full Backup and Log Backup
Full, Differential and Log Backup
Performing a backup
Restoring a Database
Database Security – Logins
Server Roles
Logins
Mixed Mode Authentication
Database Roles
Database Security – Encryption
Master keys
Transparent Data Encryption
Implementing Transparent Data Encryption
Views
Encrypting the View
Creating a view
Indexing a view
Triggers
DDL Triggers
Logon Triggers
DML Trigger
Trigger order
Advanced T-SQL queries
Sequence
Subqueries
IN Clause
EXISTS Clause
Summary
Conclusion
Introduction

This EBook is written for anyone who is new to SQL and databases and wants to learn how to deploy
and use a database, understand and use SQL and possibly take on the role of a database
administrator. SQL is a big and important topic and the main goal of this EBook is to cover the its
most important queries and uses. This EBook aims to have a database up and running for you as
quickly as possible, then go on to cover all of the major SQL queries which you can use to query the
database and cover some of the more advanced queries later. Also covered is the important work of
a database administrator and database security. The importance of database security and data
integrity is paramount for companies of any size and even for individual use.

One of the biggest selling points about computing in the latter half of the 20th century, long before the
internet, was the increasing ability to collect and store larger and larger amounts of data. Progression
in computing revolved around how much extra data could be stored and retrieved and the relative
speed it could be accessed compared to what came before. With better computing speeds, cheaper
technology and larger databases the digital revolution was becoming more widespread. One of the
biggest changes in databases was the way in which data is stored. It went from data being stored in a
physical location to data being stored in a logical location. This was to become the relational
database model. Another significant change came in the late 1970's with a new database model
called Entity Relationship. This turned the focus from a database with a logical collection of tables
to a database based on an entity model which modelled the real world.

SQL was initially developed in the 1970's by IBM and was called SEQUEL (Structure English Query
Language) to manage IBM's database. Later IBM saw it changed it to SQL and started to use the
language commercially in the 1980's. Oracle saw the potential in relational databases in the late
1970's and developed their own SQL based relational database. It wasn't until the late 1980's that
Microsoft took a variant of IBM's SQL and developed SQL Server to compete against Oracle.

The rise of the personal computer and the Internet led to an explosion in use of databases in the
1990’s, even with the dot com slump in the early 2000’s database applications continued to grow.
Although the focus has changed from larger organisations like the defence industry and medical
industry to online business and front end development and database connections. The development of
point of sale technology has led to a huge demand on databases.

The future bodes well for any SQL developer or database administrator looking to develop their SQL
skills with the widespread use of databases today and future of data in the cloud. By the time to finish
reading this EBook you will have gained in demand SQL skills from manipulating data to
understanding why your database might be running slow and how to manage it. Now is an excellent
time to start learning.
Free Video Course + Programming Newsletter
Join my FREE programming newsletter to start receiving more information related to programming
languages, hacking and technology. It will help you keep on track. You will also be notified about my
new books (at a special discounted price)

The best part? When you subscribe, you will immediately receive a FREE video course about how to
secure your online identity right now. (guaranteed you have never seen anything like this before).
You can call it a step by step action course It’s just my way of saying thank you for your readership!

Follow this link to subscribe and get Free Instant Access:


http://bonus.iloveprogrammingtech.com/offer/
Introduction to Databases

When you write a software application it is extremely likely that you’ll want to connect to a
database. A database is simply a collection of stored information which is organised to allow easy
access and updates. This information is organised into rows, columns and tables. It is from these
tables that database queries are performed based on some specific criteria.

There are numerous ways in which these tables can be accessed and organised. One of the most
popular ways is the relational model. The relational model uses a unique key to identify each row
and column in order to group tables together and thus into relations. This is known as a relational
database.

A database management system (DBMS) sits on top of a database and it will facilitate you to create
and manage your databases. You can utilize the graphical user interface instead of a command
prompt to create databases and tables.

There are numerous database offerings on the market today, for example you may own a copy of
Microsoft Access. Like the rest of Office, it’s easy to use and install but has a number of limitations
in terms of speed, flexibility, scalability and also, it’s not the most robust of databases.

The other two major players apart from Microsoft are Oracle and Sybase. Oracle has perhaps the
largest market share in the DBMS market excluding the cloud. It’s very powerful, scalable, flexible
and offers great performance but it’s not very user friendly and it gets very complicated when dealing
with a large database.

Sybase is one of the other major competitors. It’s where SQL Server originally came from. A lot of
the SQL commands and database statements between the two are the same. However, SQL Server is
a lot more feature rich than Sybase and Sybase is mostly used on Linux/Unix platforms.
Coming from a .NET background SQL Server is probably the best choice from a developer’s point of
view. The database itself performs comparatively well, is very powerful and is easy to use. There
are a number of different SQL Server versions depending on your needs, from a small business, to
developer to large enterprise. Some versions are completely free and all share the exact same
interface and are very similar in terms of functionality.
Guide to SQL Server Editions

When you visit the Microsoft download page there are essentially three editions on offer:
Enterprise Edition: This is Microsoft’s top offering. It’s designed for large companies and
corporations with large amounts of user data.

Developer Edition: This is identical to the enterprise edition except it is completely free for
individual users/developers with the understanding that it is not for production.

Express Edition: This is the entry level database designed for small companies. Some Enterprise
features are not available (like remote connections) but this edition is also free.
Summary

In addition to the three main editions there are also number of other in between editions with different
memory and functionality offerings. It is however unlikely that you will be using them or the
Enterprise edition as they are primarily aimed at large organizations, so you can select either the
developer edition or SQL Server Express. This eBook will use the Express edition as although the
developer edition has more features, we won’t be using them & Express is perfect for small size
development and can be used in a commercial environment. You can install both if you wish.

Also of note is that you can install SQL Server on both macOS and various flavours of Linux
including Red Hat, Ubuntu and SUSE and even install via a Docker image.
Free Video Course + Programming Newsletter
Join my FREE programming newsletter to start receiving more information related to programming
languages, hacking and technology. It will help you keep on track. You will also be notified about my
new books (at a special discounted price)

The best part? When you subscribe, you will immediately receive a FREE video course about how to
secure your online identity right now. (guaranteed you have never seen anything like this before).
You can call it a step by step action course It’s just my way of saying thank you for your readership!

Follow this link to subscribe and get Free Instant Access:

http://bonus.iloveprogrammingtech.com/offer/
SQL Server Express setup
The installation is relatively straightforward but there are some issues. To install Microsoft SQL
Server Express 2016, visit this webpage:
https://www.microsoft.com/en-us/sql-server/sql-server-downloads
You will see the following. Select the icon on the right – Express Edition:

When it has finished downloading, double click on the file and you will get the following:

Selecting basic will install SQL Express to the default location, if you want to change the direction
location you need to select custom. The install will begin downloading the install package – this will
take a few minutes. Once that’s complete you will get the following screen:
Select the first option - New SQL Server stand-alone installation (you can use this option if you have
other versions of SQL Server on your machine). SQL Server will start the installation process and it
will progress through a number of screens. It will state if it has any problems when it reaches the
install rules as below (the firewall warning is fine):

Click next on the above page and next again on the following page - Perform a new installation of
SQL Server 2016 - and next again to accept the licence terms.
In feature selection, you can add LocalDB. It is a lightweight version of SQL Server Express which
you can use for some programming features. The next screen will ask you for a named instance of the
database:

You can leave it as SQLEXPRESS and click next but if you change it then make a note of it. Often
you will need to remember your database name without a context. Click next on the Server
Configuration page, these options are only useful if you are installing on a remote server.
The following page is the Database Engine Configuration. It’s best to use Windows authentication
mode as you won’t forget the username and password to your windows account. Also, make sure you
are listed in the SQL Server administrators so you won’t have any trouble editing/deleting databases
later:

You may also include an additional user in case you have problems with your account. The next page
sets up the report server database - Install and configure is fine – it is used to store server metadata
and objects, used for the running of a server.

The installation will then ask you to consent to the configuration rules. Once you agree and click next
the installation will start. You will get the following screenshot on successful completion:
They should be all green. Click close. Your machine will probably need a restart. That is SQL
Server Express installed but you will also need to install the SQL Server Management Studio. It is
the GUI which you will use to interact with the databases.

To install SQL Server Management Studio (SSMS). Visit this page:


https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms
You will see the following:

Select the current release for production use.


It’s straightforward to install, just click install and wait till all is finished. Now you are all set to
start up SQL Server. Click Start – navigate to Microsoft SQL Server 2016 – select Microsoft SQL
Server Management Studio (SSMS). You will be prompted with the following dialogue box:

If you are using


Windows authentication you just have to click connect - some folders should appear on the right-hand
side.
Services will load up, navigate to SQL Server (SQLEXPRESS), right click on it and select start

You should now be able to log in on SSMS.


Creating a new database

When you log into SSMS you should see a list on the left-hand side like so:

Select Database, then right click on databases and then select new database. Enter in a name, for
example SQLEbook and press ok. The standard settings are fine.

Congratulations, you have created a new database in SQL Server. It’s empty at the moment but you
can view it by clicking the + on the right side of Databases.

The next task is to learn about tables and add some into your database.
Tables
When you first set out to create a new database you essentially are creating a number of new tables.
Tables are where all data is stored in a database. They are pretty much identical to what you can see
in an Excel spreadsheet, however there are major difference as to what is actually allowed into a
table compared to a spreadsheet. The following shows an example of a table in SQL Server:

You can see the column name (DepartmentID, Name etc.) along the top and 10 rows of user data on
the vertical. If this was an excel spreadsheet you could have almost anything placed in the rows, the
cells could actually refer to other cells and cells can carry out processing on other cells. However, a
row in a database table must have a specific data type, each table has its own name with named
rows.
Columns

The following table illustrates te datatypes that are available for each column of data in SQL Server:

Data type Description


Char or nchar Character string. Or Fixed-length n.
Max length of 8,000 characters
Varchar(n) or Character string. Variable length.
Character varying(n) Maximum length n. Max length of
8,000 characters
Binary(n) Binary string. Fixed-length n. Max
length of 8,000 bytes
Boolean Stores TRUE or FALSE values
Varbinary(n) or Binary string. Variable length.
Binary varying(n) Maximum length n
Integer(p) Integer numerical (no decimal).
Precision p
Smallint From 32,768 to -32,767
Integer From 2,147,483,648 to -
2,147,483,647
Bigint From 9,223,372,036,854,775,808
to -
9,223,372,036,854,775,807
Decimal(p,s) Exact numerical, precision p, scale s.
E.g. decimal (5,2) is a number that
has 3 digits before the decimal and 2
digits after the decimal
Numeric(p,s) Exact numerical, precision p, scale s.
Real From 3.40E + 38 to -3.40E + 38,
mantissa precision 7
Float From 1.79E + 308 to -1.79E + 308,
mantissa precision 16
Double precision Approximate numerical, mantissa
precision 16
Date Stores year, month, and day values
Time Stores hour, minute, and second
values
Timestamp Stores database wide unique number.
year, month, day, hour, minute, and
second values
Interval Is the time between two date times.
Either year/month or day/time – no
mixing both.
Array Specified length & ordered collection
of elements
Multiset Unspecified length & unordered
collection of elements
XML Stores XML data

You assign a datatype as close to what you expect to hold in a row to a column. There are a few
other things you can do with columns. For example, you can set a default value - which can be over
written at a later date. You can define a column null or not null. A null value can be used to
determine if a value there or not. You can give a row a unique identity value to link it to another row
in another table.
Rows

A row consists of one cell from every column in the table. You can have as many rows as you wish
in a table (the only limit is physical space and computer memory). A cell in a row will hold one
piece of information of the above column.

Typically, when you are designing a database you would use one table to represent a group like
Customers or transactions. You would then specify the particulars of the group in columns and fill
out the details in rows.
Creating a table in SQL Server

To create a table in SQL Server – click the + to the right of the SQLEbook database that was just
created, then left click on Tables, then right click on Tables and New - > Table. You should get the
follow on the right-hand side of the screen:

From here you can create columns based on a data type. When you wish to save a table name you can
either click on the X (in the yellow table menu bar) or click on the save icon below Project and
Debug. You will be then prompted for a table name.

Sometimes when you save a table (or anything in the database) you will not automatically see it under
the tables. You need to click on the refresh button (second icon from right).

Before creating tables in a database, you need to design the database first and understand
relationships and normalisation.
Deleting a Table in SQL Server

Often in SQL Server you will want to delete a table, sometimes just to recreate it and get rid of its
data. In SQL, this deletion is known as dropping a table. You can drop a table in SQL Server by
selecting the table you want to delete in the object browser, right clicking on it and then selecting
delete. A message box will appear asking you to confirm if you want to delete the table.

Writing queries are covered later in this EBook but you can achieve the same result by running the
following query:

DROP TABLE table_name


Table Design
When you first start to design your database, you begin by gathering as much information as you can
on the real-world problem. You want to create a database solution as accurately as possible to your
real-world model. You take this information you have gathered and work out what information you
are going to store in the database.

As an example, take a coffee shop which sells products to customers. You might come with three
database tables to model the grouping of activities like Coffee Shop Products, Customers and
Transactions.

Coffee Shop Products


Coffee Product(K) - unique identifier of coffee shop product
Coffee Product Name – name of product purchased in shop
item price – price of product purchased in coffee shop

Customers
Customer id (k) – unique identifier of customer
Title – customers title
First Name – first name of customer
Last Name – last name of customer
Address – address of customer

Transactions
Coffee shop transaction id(k) – unique id for each purchase
customer id – this is the unique id of customer defined above
Date of transaction – when the sale took place
coffee product – name of the product purchased in the coffee shop
amount – Total sales amount
This is an initial draft of the three tables and their attributes. This database is not trying to record
every and all information in order to keep the example simple and straightforward.

As yet there is no relationships drawn up yet between the tables. One of the reasons why
relationships are created is to ensure that changes made in one table won’t cause errors in another
table.
Keys

You can use keys to identify records inside a table. You can define a key on one or more record and
there are different types of keys. One of the most important keys is the primary key.
Primary Key

A Primary key is like a table key – it is used to identify individual records - however a primary key is
much more powerful and is used to link one table with another in a relational database.

Without a primary key in a table, a relational database would not work. It is designed to identify all
table records as unique items. A primary key must contain a unique value for each row of data and it
cannot contain null (or empty) values.

Sometimes you will have a conflict when linking two or more primary keys together. In such cases,
you can use a foreign key.
Foreign Key

A foreign key is a column or group of columns in a relational database table which enforces a link
between data in two tables. It acts like a constraint to join tables together. To create a foreign key,
you create a link between two tables, one having a primary key and the other having a corresponding
matching column. This column is known as the foreign key.
Relationships
A database relationship is a means of connecting two tables together based on a logical link (i.e. they
contain related data). Relationships facilitate database queries to be executed on two or more tables
and they also ensure data integrity.

Types of relationships

There are three main types of relationships in a database:


One is to One
One is to Many
Many is to Many
One is to One

This type of relationship is pretty rare in databases. A row in table X can only have a matching row
in table Y. Equally a row in table Y can only have a matching row in table X. An example of a one
is to one relationship is one person having one passport.
One is to Many

This is probably one of the most common relationships found in databases. A row in table X can
have many matching rows in table Y, however a row in table Y can have only one matching row in
table X. An example of a one is to many relationship is Houses in a street. One street had multiple
houses and a house belongs to one street.
Many is to Many

A row in table X can have many matching rows in table Y and vice versa. This type of relationship
is quite frequent where there are zero, one or even many records in the master table related to zero,
one or many records in the child table. An example of a many to many relationship is a school where
teachers teach students. A teacher can teach many students and each student can be taught by many
teachers.
Referential Integrity

When two tables are connected in a database and have the same information, it is necessary that the
data in both the tables is kept consistent, i.e. either the information in both tables change or neither
table changes. This is known as referential integrity. It is not possible to have referential integrity
with tables that are in separate databases.

When enforcing referential integrity, it isn’t possible to enter a record in a (address) table which
doesn’t exist in the other (customer) linked table (i.e. the one with the primary key). You need to first
create the customer table and then use its details to create the address table.

Also, you can use what is known as a trigger and stored procedures to enforce referential integrity as
well as using relationships.
Normalization
When you start designing your database it is important to avoid data redundancy and having
anomalies when updating data. It is important to have as little duplicate data as possible and have a
smaller more compact database. This process is call normalization.

Even though normalization makes the database more efficient and will improve performance, over
normalization will create too many slim tables where you can’t retrieve any significant piece of data.
It’s more of an art form and a general rule, some developers even de-normalize where they introduce
redundancy within a table to reduce the number of table joins and speed up important queries.

As previously discussed, the tables designed in the Coffee Shop example were modelling on group of
activities that take place there. This method of modelling is known as logical modelling. The
purpose of the logical model is to ensure that the data which the application will store will satisfy the
business requirements.

In logical modelling the table is known as an entity and the column of data is known as an attribute.
To build a logical model, you would take information gathered on the coffee shop example and
implement the attributes and entities. When deciding what, an entity should contain you should note
the following principles:

Ensure each entity has a unique identifier


Store only information that directly relates to that entity
Avoid repeating values or columns

Once you know what should be in an entity the next step is to normalize the data into normal form.
There are three main normal forms:
First normal form (1NF)
Second normal form (2NF)
Third normal form (2NF)
Just to note, there are other normal forms but while they make the database more efficient, they can
also make it too complex because of all the tables.
First Normal Form

To get your entities to first normal form it is necessary to get rid of all duplicate pieces of
information. If any information is repeating, then you place it into another table. If you take the
customers table from the coffee shop example earlier you can see it repeating values in title (e.g. Mr,
Mrs, Miss, Dr etc.) which could be place in another table. Also, the Address line could be split up
into several lines and placed in another table.
Second Normal Form

To get to second normal form you first need meet first normal form and secondly ensure that each
column in the entity must depend on the whole primary key. This means that when you look at any
single column in a table you get this information by using the whole of the primary key. Should you
be able to retrieve information you wanted with only half of the primary key you would be breaking
the second rule of second normal form.

If only part of the key is needed, then you can divide the tables up so every column does indeed need
the whole key to retrieve data.

As an example of a table violating second normal form look at the following entity:

This breaks second normal form because there are a number of non key attributes which don’t need
the full key in order to retrieve data. For example, you could find out order date, customer id and the
company name from only one primary key – order id. To bring this table to 2NF you would need to
split it up into two tables and into two relations as shown here:

The first entity Order would contain the attributes of order id, order date, customer id and company
name with the primary key of order id. The second entity Order details would contain attributes
order id, product id and quantity with the primary key being order id. There would be no possibility
of retrieving information contained in a column with just using part of a key.
Third Normal Form

In order to satisfy the criteria for third normal form you must first meet the requirements of second
normal form. Also, you must ensure that any column which is independent of a primary key is not
dependent on another column within the table.

In the above example both customer id and company name both rely on the primary key – order id.
However, they also depend on each other to find company name and who the customer is. You need
to remove one from order, in this case the customer’s name, like so:

Now you can see that there are no column references that are not dependent on a primary key. Also,
you won’t have multiple rows in the same order.
Indexes
Once you learn how to create tables along with normalization you are pretty much set to work with
the data. However, in saying that should your database contain any significant amount of data and you
wished to find a particular record then SQL Server make take quite a while to do so. There is no
cross-reference capability to get a large amount of data back quickly.

SQL Server offers indexes which are a much smaller subset of data to find the column specified in a
database quicker. If you don’t define an index, SQL Server has to perform a table scan which is very
slow. You can create an index on most table columns (except for images, varchar(max) and the like).

An index is composed of a number of pages – known as index nodes which are organized into a
Binary tree structure (a hierarchical structure) with root node at the top and leaf nodes at the bottom.
You start your query at the top of the index and it works its way down to the leaf node which will
either contain an entire row of data or point to a row.

There are three main types of indexes: Clustered, Nonclustered and unique.
Clustered Index

Also, known as a clustered table. A clustered index stores data rows at the leaf end of the index
based on a clustered index key. It is implemented via a very fast Binary tree. Clustered index means
that rows are stored in the same order as the index. There can be only one clustered index. It can be
sorted in either ascending or descending order.
Nonclustered Index

A nonclustered index differs to a clustered index in that it does not store the table data itself, rather it
points to the physical rows. So, it takes an extra step to locate the actual data. You can have
numerous nonclustered indexes and can store them on a separate physical disk if needed.
Unique

You can define an index either unique or nonunique. A unique index ensures that there are no
duplicate values (including the value of null) in the unique index columns. It is typical to implement
unique indexes for constraints like primary key and clustered indexes and non unique indexes for
locating rows using a non key column.

Adding an index in SQL Server

Now that you have covered what indexes are you can add one in SQL Server via the graphical tools.
Load up SQL Server Management Studio – left click on the + icon beside databases – select the +
icon beside a database which you have been working on – select the + icon on Tables – right click a
table you have created and select design. The table should appear on the right hand side in design
view. On the menu bar click on Manage Indexes and keys as shown in the picture below:

The Indexs/Keys dialogue box will appear. It’s best to give a unique name to the identity (Name) – it
usually starts with IX_ by convention. You can select which columns you want to index by left
clicking the field to the right of Columns in (General) and then clicking on the ‘...’. You can then
change the sort order – ascending or descending (screen below).
You can add column to the index columns as well. It’s very straightforward to add an index but it can
seriously speed up a large database.
Queries
Once you have a database set up and with data entered in it the next thing you will want to do is to
retrieve data from it based on some specific criteria. SQL is the language for storing, retrieving and
manipulating data on databases. To run a query in SQL Server, load up the SQL Server Management
Studio, connect to a server, open databases, then select the database you will be working on, right
click on it and then select New Query. You can run all queries here.
Select

The SQL Select statement is used when you want to pick or select the data to be returned from the
database. Select has numerous different options and extensions which provide great flexibility in
getting the data we need. The fullest syntax of a Select statement is the following:
SELECT FROM WHERE ORDERBY
Each of the above words is a keyword. Typically, you will write them in uppercase but you can use
lowercase if you wish. The above statement is broken down into different clauses.
SELECT FROM Clause

SELECT * FROM [AdventureWorks2014].[Person].[Address]


The first part of the above selects or retrieves all (using the *) from a database. The second part
states the table and database where the columns will come from. In this case the database is called
AdventureWorks2014 (freely available for developers online). The last part states the name of the
actual tables name is Person.Address. Providing you have selected the same database in SQL Server
you can write the following and get the same results:
SELECT * FROM Person.Address

The above picture illustrates the output when the select query is executed. Everything from this table
is retrieved.
The WHERE clause

Should you wish to limit or filter the amount of data you retrieve from the database then you specify
the WHERE clause along with the SELECT statement. You can specify one or more conditions must
be met. An example of a where clause is the following:

SELECT AddressID, AddressLine1, AddressLine2, City FROM Person.Address WHERE City ='San
Francisco'

This query retrieves all records from the current database where the city matches San Francisco.
Note the single ‘ in SQL to denote a text string to match. The subsequent columns retrieved are
AddressID, AddressLine1, AddressLine2 and City as the following shows:

To exclude everyone from San Francisco you can use the <> before ‘San Francisco’.

To return a list based on or after a certain date you can use the >= before the matching date. To have
multiple where both clauses are true you can use the AND statement. You can use the NOT operator
to exclude the subsequent clause. To test whether one or another value is true you can use the OR
operator

SELECT AddressID, AddressLine1, AddressLine2, City FROM Person.Address WHERE City ='San
Francisco' OR City ='Seattle'
You can use the LIKE operator to retrieve data using wild card characters. For example you can use
the WHERE clause on a column followed by LIKE and underscore ‘_isco’ in single quotes to retrieve
all cities that end with isco (like san Francisco): WHERE city LIKE ‘_isco’.

Other wild cards include (enclosed in ‘ ‘ ):


‘ % ’ matches a string.
‘[ ]’ matches single character,
‘[^]’ matches a single character that’s not within the specified range.
The ORDER BY Clause

So far, the queries have been picking or filtering the data, i.e. deciding which rows to take and
placing specific matching criteria on them. Once we have the columns we actually want the next step
is to arrange the data. To sort rows you use the ORDER BY clause on one or more columns. The
following code orders by city:

SELECT AddressID, AddressLine1, AddressLine2, City FROM Person.Address ORDER BY City

It returns the query as before but arranged alphabetically on City. If you wanted it in reverse order
you would include the keyword DESC immediately after City. You can order by more than one
column by placing a comma between the two columns.
Joins
A Join is a relationship of one or more tables which is used to retrieve common information. When
you want to combine rows from two or more tables you can use the JOIN keyword. There are
essentially three different kinds of joins available in SQL Server:

Inner Join
Outer Join
Cross Join
Inner Joins

An inner join or also known as a simple join returns all rows from numerous tables where the join
condition is set to be true. The syntax for the inner join is as follows:

SELECT columnName FROM TableX


INNER JOIN TableY
ON TableX.columnName=TableY.columnName

This will return all matching rows between two columns in two tables.
Outer Joins

An outer join is a join which includes columns even if they do not have related rows in the joined
table. There are three different outer joins (left, right and full):
Left Outer Join

The left outer join will return all items or rows from the table on the left while only the matched
records are returned from the right table. Should there be no matching records in the right table then
the NULL value is returned. The syntax for a left outer join is the following:

SELECT columnName FROM TableX as x1


LEFT OUTER JOIN TableY as x2
on x1.xcolumnName = x2.xid

Right Outer Join

The right outer join will return all rows from the table on the right while only the matched records are
returned from the right table. Likewise, should there be no matching records in the right table then the
NULL value is returned. The syntax for a right outer join is the following:
SELECT columnName FROM TableX as x1
RIGHT OUTER JOIN TableY as x2
on x1.xcolumnName = x2.xid

Full Outer Join

The full outer join will return all rows from both left outer join and right outer join. If there are no
matching columns in both tables then the value NULL is returned. The syntax for a full outer join is
the following:

SELECT columnName FROM TableX as x1


FULL OUTER JOIN TableY as x2
on x1.xcolumnName = x2.xid
Cross Join

You can use cross join to join a database to itself. It’s particularly useful when a table has a foreign
key which references its own primary key. You can use cross join to return records in a table which
have some kind of relation or are similar to other records in the same table. The syntax for a cross
join is the following:
SELECT x.columnX, y.columnY
FROM TableX x, TableX y
WHERE x.columnField = y.columnField
Set Operators
Joins take two (or one the case of cross join) or more tables in a single query to retrieve common
information. You can add extra tables and select columns from them. You tend to use joins for a
broad result set. However, set operators differ in that you take the rows from numerous queries and
combine them into one result set. With set operators, there is strong number of preconditions with the
select statement, you must return the same number of columns and the data types of corresponding
columns must match each other or be convertible. You tend to use set operators to retrieve results in
depth. There are three set operators: Union, Intersect and Except
Union

The union operator takes the two input queries and unifies the result. Each SELECT statement needs
to contain the exact same number of fields, also the data types have to be compatible. Should any row
appear in one of the input sets then it will appear in the results of the union operator. However, if
there are duplicate records in the input sets then they will not appear in the results. There is a set
operator call UNION ALL which does not remove the duplicate rows. The syntax for union operator
is the following:

SELECT * FROM tableX


UNION
SELECT * FROM tableY

You can use UNION ALL with the exact same syntax to return all duplicate rows.
Intersect

The intersect operator returns the distinct rows of two or more queries that are common to both, i.e.
rows which exist in both select statements. If a row exists in one select query and not in the other it
will not be displayed. Intersect like Union returns all unique rows. The syntax for intersect is the
following:

SELECT * FROM tableX


INTERSECT
SELECT * FROM tableY

SQL Server doesn’t support an INTERSECT ALL but it can be coded.


Except

The except operator returns only the distinct rows which are in the first select statement but not in the
second select statement. Essentially the query will get all records in the first dataset and then get rid
of the results from the entire second dataset. The syntax for the except is the following:

SELECT columnName1, columnName2, columnName3 FROM tableX


Except
SELECT columnName1, columnName2, columnName3 FROM tableY
Modifying data
SQL Server has a number of commands which you can use to modify the data in your database to
insert, update, delete, truncate and merge along with the select statement. Before you make any
changes to your database it is important to surround the statements with the transaction statements to
offer some fall back if a mistake was made.
Transactions

A transaction is like a method which is represented as a single piece of work. If the transaction is
successful it will leave the database in a new state, if it is unsuccessful it will cancel and roll back
leaving the database in the previous state. In order to get a transaction to succeed you must follow the
ACID acronym:

Atomicity - each & every transaction must be both accepted & inserted into the database or none
of the transactions will be performed
Consistency – data must remain in a consistent state before & after a transaction including a
rollback and keep its integrity.
Isolation – any modification to one transaction must be isolated from all others.
Durability – after a transaction is complete, it can be modified by another transaction.

The transaction commands are BEGIN TRAN, COMMIT TRAN and ROLLBACK TRAN. Begin
Tran notes the start of the transaction processing. You need to close it with a Commit or Rollback.
You can place logic between the commands and check that certain conditions are met. The commit
Tran is permanent and you can’t retrieve your data after it is executed. If you wish to roll back the
changes that you have made since the start of the Begin you can use the Rollback Tran command.
Insert statement

The insert statement is one of the more straightforward statements in SQL Server and is used to insert
a record or records into a table. The syntax for the Insert statement is the following:

INSERT INTO tableNameX(val1, val2, val2)


VALUES (1, 'text', 2, 'text2')
Update statement

If you want to update rows in a table, you can use the update statement. You can also use join criteria
to add multiple tables. The UPDATE statement is similar to the SELECT statement in that you go and
look for rows to update. In order to identify the subset of rows that you want to update you can use the
WHERE clause. The syntax for the UPDATE statement is the following:

UPDATE tablenameX
SET columnY='San Francisco'
WHERE rowValueY =1;

The table is selected with the update statement, then the column is selected with the set statement and
the new value is enclosed in quotes. Finally, the individual record is looked up with the WHERE
statement and changed.
Delete statement

Deleting data is very straightforward in SQL Server and unless you use a transaction the data is gone
very quickly and in most cases for good unless there is a backup. Even with a transaction the data
will be gone on completion of the commit statement. If you make a mistake in your delete command it
is pretty likely to be unrecoverable. So, it is best to test all joins and filter only the data you want to
delete with the SELECT statement before going ahead with the delete.

The syntax for the DELETE statement is as following:

DELETE
[FROM] tablenameX
WHERE where_condition_is_true
If you forget to include the WHERE clause all data in that table will be deleted.
Truncate statement

Truncate is similar to DELETE in that it deletes all rows from a table in the database. However,
every time you use a DELETE statement it is recorded in the transaction log in SQL Server. This is
known as fully logged. Truncate on the other hand is minimally logged. If you have a large table it’s
a lot quicker (a few seconds) to use the TRUNCATE statement compared to the DELETE statement
(same task could take minutes). The syntax for the TRUNCATE statement is the following:
TRUNCATE TABLE tablenameX
Merge statement

You can use the MERGE statement to merge data from one source to a target and then perform a
number of different types of data modification such as DELETE, INSERT OR UPDATE based on
conditional logic. They syntax for the MERGE statement is the following:

MERGE INTO tableNameX as Target1


USING tableNameY as Sources1
WHEN MATCHED THEN
UPDATE SET
Target1.columnName1 = Source1.columnName1,
Target1.columnName2 = Source1.columnName2
WHEN NOT MATCHED THEN
INSERT(ColumnE, ColumnF, ColumnG)
VALUES (Source1.ColumnE, Source1.ColumnF, Source1.ColumnG)

The first MERGE clause is triggered with MATCHED, this will update or delete rows in the Target1
table that are matched in the Sources1 table. The next Merge is triggered with the NOT MATCHED
statement, these rows are copied into the table that don’t have a matching row in the target.
Stored Procedures and Functions
So far in this EBook we have covered how to build queries as single executable lines. However, you
can place a number of lines into what is known as a stored procedure or function within SQL Server
and call them whenever it is required.

There are a number of benefits to stored procedure and functions not just code reuse including: better
security, reduced development cost, consistent and safe data, use of modularization and sharing
application logic.

Stored procedures and functions are similar in that the both store and run code but functions are
executed within the context of another unit of work.
T-SQL

T-SQL or Transact Structure Query Language is an extension of the SQL commands that have been
executed thus far in this EBook. T-SQL offers a number of extra features that are not available in
SQL. These features include local variables and programming elements which are used a lot in
stored procedures.
Creating a Stored Procedure

To create a stored procedure, you begin with the CREATE PROCEDURE statement. After which you
will have access to the (as mentioned) additional programming commands in T-SQL. The following
is the syntax for creating a stored procedure:

CREATE PROCEDURE procedureName


[ { @parameterName} datatype [= default_value] [OUTPUT]]
WITH RECOMPILE, ENCRYPTION, EXECUTE AS Clause
AS
BEGIN
SELECT * FROM tableName1
END

It’s best practice to include a procedure name so it can be referenced later, it is common to use the
sp_ prefix.

Next thing to do is to define optional input and output parameter names. Parameters are used to pass
in information to a stored procedure. These are prefixed by the @ symbol, must have a data type
specified and you place them in parentheses separate by commas. For example @customerID
varchar(50).

There are a number of different ways in which you can execute the query. You can specify Recompile
to indicate that the database engine doesn’t cache this stored procedure so it must be recompiled
every time its executed. You can use the encryption keyword to hide the stored procedure so it’s not
readily readable. The EXECUTE AS Clause identifies the specific security context under which the
procedure will execute, i.e. control which user account is used to validate the stored procedure.

After you declare the optional parameters you use the mandatory keyword AS which defines the start
of the T-SQL code and finishes with END. You can use a stored procedure for more than just regular
SQL statements like SELECT, you can return a value which is useful for error checking.
Controlling the execution of the Stored Procedure
When you create a Stored Procedure often you need to control T-SQL in between the BEGIN and
END statements when dealing with more than one T-SQL statement. You can use the following: IF
ELSE, BEGIN END, WHILE BREAK and CASE STATEMENT
IF ELSE

Often you will use statements in a Stored Procedure which you need a logical true or false answer
before you can proceed to the next statement. The IF ELSE statement can facilitate. To test for a true
or false statement you can use the >, <, = and NOT along with testing variables. The syntax for the IF
ELSE statement is the following, note there is only one statement allowed between each IF ELSE:
IF X=Y
Statement when True
ELSE
Statement when False
BEGIN END

If you need to execute more than one statement in the IF or ELSE block, then you case use the BEGIN
END statement. You can put together a series of statements which will run after each other no matter
what tested for previous to it. The syntax for BEGIN END is the following:

IF X=Y
BEGIN
statement1
statement2
END
WHILE BREAK

When you need to perform a loop around a piece of code X number of times you can use the WHILE
BREAK statement. It will keep looping until you either break the Boolean test condition or the code
hits the BREAK statement. The first WHILE statement will continue to execute as long as the
Boolean expression returns true. Once its False it triggers the break and the next statement is
executed. You can use the CONTINUE statement which is optional, it moves the processing right
back to the WHILE statement. The syntax for the WHILE BREAK command is the following:

WHILE booleanExpression
SQL_statement1 | statementBlock1
BREAK
SQL_statement2 | statementBlock2
Continue
SQL_statement3 | statementBlock3
CASE

When you have to evaluate a number of conditions and a number of answers you can use the CASE
statement. The decision making is carried out with the initial SELECT or an UPDATE statement.
Then a CASE expression (not a statement) is stated, after which you need to determine with a WHEN
clause. You can use a CASE statement as part of a SELECT, UPDATE or INSERT statement.

There are two forms of CASE, you can use the simple form of CASE to compare one value or scalar
expression to a list of possible values and return a value for the first match - or you can use the
searched CASE form when you need a more flexibility to specify a predicate or mini function as
opposed to an equality comparison. The following code illustrates the simple form:

SELECT column1
CASE expression
WHEN valueMatched THEN
statements to be executed
WHEN valueMatched THEN
statements to be executed
ELSE
statements to catch all other possibilities
END

The following code illustrate the more complex form, it is useful for computing a value depending on
the condition:

SELECT column1
CASE
WHEN valueX_is_matched THEN
resulting_expression1
WHEN valueY_is_matched THEN
resulting_ expression 2
WHEN valueZ_is_matched THEN
resulting_ expression 3
ELSE
statements to catch all other possibilities
END
The CASE statement works like so, each table row is put through each CASE statement and instead of
the column value being returned, the value from the computation is returned instead.
Functions

As mentioned functions are similar to stored procedures but they differ in that functions (or User
Defined Functions UDF) can execute within another piece of work – you can use them anywhere you
would use a table or column. They are like methods, small and quick to run. You simply pass it
some information and it returns a result. There are two types of functions, scalar and table valued.
The difference between the two is what you can return from the function.
Scalar Functions

A scalar function can only return a single value of the type defined in the RETURN clause. You can
use scalar functions anywhere the scalar matches the same data type as being used in the T-SQL
statements. When calling them, you can omit a number of the functions parameters. You need to
include a return statement if you want the function to complete and return control to the calling code.
The syntax for the scalar function is the following:

CREATE FUNCTION schema_Name function_Name


-- Parameters
RETURNS dataType
AS
BEGIN
-- function code goes here
RETURN scalar_Expression
END
Table-Valued Functions

A table-valued function (TVF) lets you return a table of data rather than the single value in a scalar
function. You can use the table-valued function anywhere you would normally use a table, usually
from the FROM clause in a query. With table-valued functions it is possible to create reusable code
framework in a database. The syntax of a TVF is the following

CREATE FUNCTION function_Name (@variableName


RETURNS TABLE
AS
RETURN
SELECT columnName1, columnName2
FROM Table1
WHERE columnName > @variableName
Notes on Functions

A function cannot alter any external resource like a table for example. A function needs to be robust
and if there is an error generate inside it either from invalid data being passed or the logic then it will
stop executing and control will return to the T-SQL which called it.
Database Administration
Once you have your database up and running with tables and queries it is up you to keep the
production database running smoothly. The database will have to be regularly looked at in order to
ensure that it continues to perform as originally intended. If a database is poorly maintained it can
easily result in a website connected to it performing poorly or worse still result in down time or even
data loss. There is usually a person designated to look after the database and their job is titled
Database Administrator or DBA. However, it’s usually a non-DBA person who needs help with the
database.

There are a number of different tasks which you can perform when carrying out maintenance which
include the following:

Database Integrity: When you check the integrity of the database you are running checks on the data
to make sure that both the physical and logical structure of the database is consistent and accurate.

Index Reorganization: Once you start to insert and delete data on your database there is going to be
fragmentation (or a scattering) of indexes. Reorganizing the index will bring everything back together
again and increase speed.

Rebuild Index: You don’t have to perform an index reorganization, you can drop an index and then
recreate them.

Database Backup: One of the most important tasks to perform. There are a number of different
ways in which you can back up the database, these include: Full which backs up the database entirely,
Differential which backs up the database since the last full backup and Transaction log which only
backs up the transactional log.
Check Database Statistics: You can check the statistics of the database which are kept on queries.
If you update the statistics, which can get out of date, you can help aid the queries being run.
Data and Log File: In general, make sure the data and log files are kept separate from each other.
These files will grow when your database is being used and its best to allocate them an appropriate
size going forward (and not just enable them to grow).

Depending on your database some tasks may be more useful than others. Apart from database backup
which probably mandatory if it’s in production you can pick through the other tasks depending on the
state of the database.

For example, should the fragmentation of the database be below 30% then you can choose to perform
an index reorganization. However, if the database fragmentation is greater than 30% then you should
rebuild the index. You can rebuild the index on a weekly basis or more often if possible.

You can run a maintenance plan on SQL Server via its Server Agent depending on database
requirements. It’s important to set the times right not when your application is expected to be busy.
You can choose a time or you can run it when the server CPU is not busy. Choosing to run when the
server is not busy is a more preferred option for larger databases than selecting a particular time as
there is no guaranteed time which the CPU will be idle. However, it is usually only a concern if your
application is quite big and has a lot of requests.

When you do rebuild the indexes, it is important that you have the results sorted in tempdb. When
using tempdb the old indexes are kept until new ones are added. Normally rebuilding the indexes
uses the fixed space which the database was allocated. So, if you run out of disk space then you
would not be able to complete the rebuilding of indexes. It’s possible to use the tempdb and not have
to increase the database disk size. The database maintenance can be run both synchronous (wait for
task completion) or asynchronous (together) to speed things up however you must make sure that the
tasks run in the right order.
Setting up a maintenance plan in SQL Server

To set up a maintenance plan in SQL Server you first must get the server to show advanced options.
This is done by running the following code in a new query in SQL Server:

sp_configure 'show advanced options', 1


GO
RECONFIGURE
GO
sp_configure 'Agent XPs', 1
GO
RECONFIGURE
GO

SQL Server will now display the advanced options. Left click the + icon to the left of Management
which is on the left-hand side of SQL Server Management Studio. Now left click Maintenance Plans
and then right click Maintenance Plans. Select New Maintenance Plan Wizard.

Enter an appropriate maintenance plan name and description. From here you can either run one or all
tasks in one plan and have as many plans as you want. After you have given a name, choose single
schedule and click next.

You will see a number of options which you can pick for your maintenance including: Check
Database Integrity, Shrink Database, Reorganize Index, Rebuild Index, Update Statistics, Clean
up History, Execute SQL Server Agent Job, Back Up – full, differential or transaction log and
Maintenance Cleanup Task. Select which you want to perform (in this example select all) This
wizard will bring you through each of the items you have selected to fine tune them.

Once you select the items you want in your plan click next, you can now rearrange them in the order
you wish them to complete. It’s best to have Database Backup first in case of power failure, so select
it and move it to the top of the list. Click next.
Define Back Up Database (Full) Task

This screen allows you to pick which full database backup you wish to perform it on. Best practice
is to keep one plan per database, select one database and select next.

Define Database Check Integrity Task

This screen – the integrity task is a SQL Server command which checks the integrity of the database
to see if everything is not corrupt and stable. Select a database and click next.

Define Shrink Database Task

You can now configure to shrink the database in order to free up space in the next screen. It will only
shrink space if available but should you need space in the future you will have to re allocate it.
However, this step will help backup speeds. Most developers don’t use this feature that much. Click
next after selecting a database to shrink.
Define Reorganize Index Task

The next screen is the Define Reorganize Index Tag screen. When you add, modify and delete
indexes you will, like tables, need to reorganize them. The process is the same as a hard disk where
you have there are fragmented files and space scattered across the disk. Best practice is to perform
this task once per week for a busy database. You can choose to compact large object which compacts
any index which has large binary object data. Click next to proceed to the next screen.

Define Rebuild Index Task

This screen covers individual index rows. As mentioned either reorganize or reindexing. Doing both
together in one plan is pointless. Depending on your fragmentation level pick one or the other. In this
example select your database and sort results in tempdb. Click next to proceed.
Define Update Statistics Task

The update statistics task helps developer keep track of data retrieval as its created, modified and
deleted. You can keep the statistics up to date by performing this plan. Both statistics for index and
statistics for individual columns are kept. Select your database and click next to proceed.

Define History Cleanup Task

You should now see the Define maintenance cleanup task screen which specifies the historical data to
delete. You can specify a shorter time frame to keep the backup and recovery, agent job history and
maintenance place for on the drop down. Click next to proceed.

Define Back up Database (Differential) Task

This screen allows you to back up every page in the database which has been changed since the last
full backup. Select a database you wish to use and click next.

Define Back Up Database (Transaction Log) Task

The transaction log backup backs up all the log records since the last backup. You can choose a
folder to store it. Performing this type of backup is the least resource intensive backup. Select a
database and storage location and click next.

Define Execute SQL Server Agent Job Task

The SQL Server Agent Job Task deals with jobs that are outside the wizard, for example it could be
to check for nulls, check whether the database meets specified standards etc. Any jobs that are
specified in SQL Server Agent Job Task are listed here. Click next to proceed.

Define Maintenance Cleanup Task


This screen defines the clean-up action of the maintenance task i.e. to ensure that the they are not
taking up unnecessary space, so you can specify where to store them. You can delete specific backup
files. Click next to proceed.

Report Options

The next screen covers where you want to store the report of the maintenance plan. Make a note of
where you are going to store it. You need to have email set up on SQL Server in order to email it.
Click next to proceed.
Complete the Wizard

The final screen is a complete review of the wizard. You can review the summary of the plan and
which options were selected. Clicking finishes ends the wizard and creates the plan. You should
now see a success screen with the tasks completed.
Running the maintenance plan

Once you successfully complete the maintenance wizard the next step is to run the plan you created.
In order to get the plan to run you need to have the SQL Server Agent running. It is visible two down
from where Management is on SQL Server Management Studio. You can left click SQL Server Agent
and then right click and select Start.

Also, you can press the windows key + and press the letter r, then type in services.msc and hit return.
Once Services appear scroll down and look for SQL Server Agent (MSSQLEXPRESS). SQL Server
Express was installed in this EBook but you can select the other versions like (MSSQLSERVER) if
you installed that. Left click it, then right click it and select Start.

You can go back to SSMS and right click on the maintenance plan you created under maintenance
plans and then select Execute. This will now run your plan. One successful completion of the plan
click ok and close the dialogue box. You can view the reports by right clicking the maintenance plan
you created and selecting View history. On the left-hand side are all the different plans in SQL
Server while on the right is the results of the specific plan.
Emailing the reports.

A lot of DBA’s like to get their database reports via email. What you need to do is to set up a
database mail before you can fire off emails and then set up a Server agent to send the email.

Setting up Database Mail.

The first step is to right click Database mail in SSMS and select configure database mail. A wizard
screen will appear, click next. Now select the first choice – set up Database Mail and click next.
Enter a profile name optional description of the profile. Now click on the Add button to the right.

This will bring you to an add New Database Mail Account – SMTP. You need to enter the STMP
details for an email account. Maybe you can set up a new email account for this service. You can
search online for SMTP details, Gmail works quite well (server name: smtp.gmail.com, port number
587, SSL required, tick basic authentication & confirm password). Click on ok. Click next, click on
public (important: so it can be used by the rest of the database). Set it as default profile, click next,
click next again. You should now get a success screen. Click close.
SQL Server Agent

To send off the database email you need to set up a Server Agent. Start by right clicking on SQL
Server Agent – New – Operator. Give the operator a name like Maintenance Plan Operator and enter
in the email address you wish to send the report to and click ok.

Now right the maintenance plan that you have successfully executed and select modify. The
maintenance plan design screen will appear on the right-hand side where you can see some graphics
of the tasks completed in it. Now click on Reporting and Logging – it is an icon situated on the menu
bar of the design plan - to the left of Manage Connections…

The Reporting and Logging window will appear. Select the tick box – Send report to an email
recipient and select the Maintenance plan operator you just created. The next time you run the plan an
email will be sent to the email address.
Summary

The running and maintenance of a database is an important job. Having the right plan for your
database means it will continue to work as originally designed and you can quickly identify database
errors or slowdowns early on and fix them quickly.
Database Backup and Recovery
As mentioned, the most important task a DBA can perform is to back up the database. When you
create, a maintenance plan it’s important to have it top of the maintenance list in case the job doesn’t
get fully completed. Firstly, it is important to understand the transaction log and why it is important.
The Transaction Log

Whenever a change is made to the database, be it a transaction or modification, it is stored in the


transaction log. The transaction log is the most important file in a SQL Server database and
everything resolves around either saving it or using it.

Every transaction log can facilitate transaction recovery, recovery of all incomplete transactions,
rolling forward a restored file, filegroup or page to a point of failure, transactional replication,
disaster recovery.
Recovery

The first step in backing up a database is choosing a recovery option for the database. You can
perform the three types of backups when SQL Server is online and even while users are making
requests from the database.
Recovery Models

When you backup and restore in SQL Server you do so in the context of the recovery model which are
models designed to control the maintenance of the transactional log. The recovery model is a
database property that controls how transactions are logged.
There are three different recovery options: Simple, Full and Bulk Logged.

Simple Recovery

You cannot back up the transactional log when utilizing the simple recovery model. Usually this
model is used where updates are infrequent. Transactions are logged to a minimum and the log will
be truncated.

Full Recovery

In the full recovery model the transaction log backup must be taken. Only when the backup process
begins will the transactional log be truncated. You can recover to any point in time. However, you
also need the full chain of log files to restore the database to the nearest time possible.

Bulk Logged

This model is designed to be utilized for short term use when you use a bulk import operation. You
use it along with full recovery model whenever you don’t need a certain point in time recovery. It has
performance gains and also doesn’t fill up the transaction log.
Changing the Recovery Model

To change the recovery model, you can right click on a database in SQL Server Management Studio
and selecting properties, then select options and then selecting the recovery model from the drop-
down box. Or you can use one of the following three:

ALTER DATABASE SQLEbook SET RECOVERY SIMPLE


GO
ALTER DATABASE SQLEbook SET RECOVERY FULL
GO
ALTER DATABASE SQLEbook SET RECOVERY BULK_LOGGED
GO
Backups

There are three types of backup: full, differential and transaction log:

Full Backup

When you create a full backup, SQL Server creates a CHECKPOINT which ensures than any dirty
page that exist are written to disk. Then SQL Server backs up each and every page on the database.
It then backs up the majority of the transaction log to ensure there is transactional consistency. What
all of this means is that you are able to restore your database to a most recent point and have all the
transactions including those right up to the very beginning of the backup.

Differential Backup

The differential backup as it name suggests backs up every page in the database which has since been
modified since the last backup. SQL Server keeps track of all the different pages that have been
modified via flags and DIFF pages.

Transaction Log Backup

With the log backup SQL Server backs up the data in the transaction log only, i.e. only the
transactions that were recently committed to the database. The transaction log is not as resource
hungry and is considered important because it can perform backups more often without having an
impact on database performance
Backup strategy

When Database Administrator set out a backup plan they base their plan on two measures: Recovery
Time Objective (or RTO) and Recovery Point Objective (RPO). RTO is the amount of time it takes
to recover after a notification of a disruption in the business process. RPO is the amount of time that
might pass during a disruption before the size of data that has been loss exceeds the maximum limit of
the business process.

If there was an RPO of 60 minutes you couldn’t achieve this goal if the backup was set to every 24
hours. You need to set your backup plan based on these two measure.

Full Backup

Exercising this alone is the least flexible option. Essentially your only able to restore your database
back to one point of time which the is the last full back up. So, if the database went corrupt two hours
from midnight (and you backup at midnight) your RPO would be twenty-two hours. Also, if a user
truncated a table two hours from midnight you would have the same twenty-two-hour loss of business
transactions.

Full Backup and Log Backup

If you have selected Full Recovery mode, you can run both full backups and transactional log file
backups. You can run more frequent backups since running Transaction Log backup takes less
resources. This is a very good choice if your database is updated throughout the day.

When you are scheduling transactional log backups its best to follow the RPO. So, if you have an
RPO of 60 minutes then set the log file backups to 60 minutes. However, you must check the RTO for
such a backup. If you had a RPO of 60 minutes and are only performing a full back up one a week
you might not be able to restore all 330 backups in allotted time.

Full, Differential and Log Backup


To get around the problem mentioned above you can add differential backups to the plan. A
differential backup is cumulative which mean a serious reduction in the number of backups you would
have to restore to recover your database to the point just before failure.
Performing a backup
To back up a database right click the database in SSMS then select Tasks-> Backup. You can select
what kind of backup (full, differential or transaction log) to perform and when to perform a backup.
The copy-only backup allows you to perform a backup which doesn’t affect the restore sequence.
Restoring a Database
When you want to restore a database in SSMS right click the database then select Tasks -> Restore ->
Database. You can select the database from the drop down and thus the rest of the tabs will be
populated.

If you click on Timeline you will see a graphical diagram of when the last backup was created which
shows how much data was lost. You can recover to the end of log or a specific date and time.

The Verify Backup Timeline media button enables you to verify the backup media before you actually
restore it. If you want to change where you are going to store the backup you can click on the Files to
select a different location. You can specify the restore options that you are going to use in the
Options page. Either overwrite the existing database or keep it. The recovery state either bring the
database online or allows further backups to be applied.

Once you click OK on the bottom the database will be Restored.


Database Security – Logins
The security of the database is very important for both the company hosting the database and
customers using it, especially so when there are potential customer transactions, customer financial
information and employee information stored on it. It’s up to the DBA to manage and counter the
threats.

You have two options to ensure database security, first is essentially a security hierarchy via
Windows authentication where users are restricted to accessing sensitive data through views by
specifically creating users with certain levels of access. The second option is to encrypt the
database, the logs and files.

Instance: On every given server, you can run multiple SQL Server services with their own ports,
logins & databases. An ‘instance’ refers to a unique service running on SQL Server.
Server Roles

There are a number of different server roles available with SQL Server that you can use to manage
permissions at the instance level. Server roles are like groups in Windows and help you manage
permissions on a server. They are:

sysadmin – any user of this group can perform any action within the instance of SQL Server.
blkadmin – allows users to import data from a file using BULK INSERT statement.
dcreator – allows members to create new databases within the instance.
diskadmin – allows members to manage backup devices in SQL Server.
processadmin – members are allowed to kill running processes or stop instances.
public – all logins added to this group and used for internal operations like authentication.
securityadmin – members can manage logins at the instance level, e.g. assign permissions
serveradmin – combines both diskadmin and processadmin plus can shut down the instance (i.e.
the option of no checkpoint).
setupadmin – members can create and manage linked servers.

You can also create your own server roles with a specific number of permissions. To add a new
server role: right click on Security in the object browser, click new and then click Server role. Enter
a server role name and then tick the boxes for explicit permissions.
Logins

The security hierarchy starts at the Windows domain (or all accounts) and flows down to Windows
groups and Windows users, down to local server, down to database and right down to object (e.g. a
table) level. The model is based on three concepts: Principles – entities which permissions are
granted/denied/revoked, Securables – objects which can have permissions granted on them and
Permissions – what are you allowed to do. Essentially you permit a permission on a securable to a
principle.

You can create a group which groups of users can belong to and have a designated level of access to
the database. Whenever you originally create a new database, only the database owner or system
administrator has complete access to it. It’s up to them to create groups and specify access.

Mixed Mode Authentication


In addition to windows authentication to log in there is also mixed mode authentication where you can
connect to the database through a secondary tier of authentication. These users and passwords are
stored on the database. Also, when you enable mixed mode authentication a special user called SA
(or System Administrator) is created which has complete administrator rights. This can be a security
risk as hackers will try to target this password first. Best practice is to rename this account and also
ensure it has a very strong password. To rename the account create a new query and execute the
following:

You can give the SA account any name of your choosing but this simple step will really help the
database security. Best practice is to stick to Windows authentication. You can change to Windows
authentication by right clicking the server in object explorer in SSMS and then selecting properties
and the selecting properties. You can choose server authentication here and restart SQL Server to
make changes take effect.
Database Roles

While server roles manage permissions at the server level, database roles can group principals
together to assign common permissions. The main database roles are:
db_accessadmin - can add and remove database users from the database.
db_backupoperator - gives users the permissions they need to back up the database.
db_datareader - can run SELECT statements against any table in the database.
db_datawriter - can perform Data Manipulation Language statements against any table in the
database.
db_denydatareader - denies the SELECT permission against every table in the database.
db_denydatawriter - denies its members the permissions to perform DLM statements against every
table in the database.
db_ddladmin - able to run CREATE, ALTER, and DROP statements against any object in the
database.
db_owner - can perform any action within the database that has not been specifically denied.
db_securityadmin - can grant, deny, and revoke a user’s permissions to securables. Can also add
or remove role memberships, with the exception of the db_owner role.

To create a database role in SSMS: click the + on the left of your database, then right click on
Security -> New -> Database role.
Database Security – Encryption
Encryption is the second option you can utilise to ensure the security of the database and while it adds
another layer of security to your database it does not replace the need for controlling access to the
database. There are some side effects to encryption like a reduction in performance so best practice
is to implement encryption when needs arise and is not a mandatory task for a DBA to perform on
each and every database.

There are a number of ways in which you can encrypt some data. The weakest form is to use a
symmetric key which uses the same key for encryption and decryption. This has the least performance
overhead.

An asymmetric key uses a pair of keys, one for encryption and one for decryption. To encrypt the
data, you use the private key and to decrypt the data you use the public key. This method is strong but
they keys are slow.

A certificate is issued by recognized Certificate Authority. It uses an asymmetric key and provides a
digitally signed statement and is associated with an individual or device.
Master keys

SQL Server uses service master keys as the root of SQL Server encryption. Its automatically created
once a new instance is built and you can use it to encrypt database master keys, credentials, linked
server’s passwords. You can authorize a user to unlock subsequent keys. Its stored in the Master
database and there is always only one per instance. To generate a new master key, execute the
following in a new query:
ALTER SERVICE MASTER KEY REGENERATE

It’s important that you take a backup (and choose a suitable password). You can do so with the
following:

BACKUP SERVICE MASTER KEY


TO FILE = 'c:\sqlServerKeys\serviceMasterKey'
ENCRYPTION BY PASSWORD = 'Password1'

To restore to a previous master key, you use the following:

RESTORE SERVICE MASTER KEY


FROM FILE = 'c:\ sqlServerKeys \serviceMasterKey'
DECRYPTION BY PASSWORD = 'Password1'

There are database master keys which also should be backed up. To create a database master key,
you use the following:

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Password1'

To back up a database master key you use the following:

BACKUP MASTER KEY TO FILE = 'c:\ sqlServerKeys \serviceMasterKey'


ENCRYPTION BY PASSWORD = 'Password1';

To restore a database master key, you use:

RESTORE MASTER KEY


FROM FILE = 'c:\ sqlServerKeys \serviceMasterKey'
DECRYPTION BY PASSWORD = 'Password1'
ENCRYPTION BY PASSWORD = 'Password1'

To restore a database master key, you use:


Transparent Data Encryption

You can encrypt the data pages and log files of a database by storing the key (or database encryption
key) in the boot record of the database. It works by encrypting pages before they are written to disk
and decrypted before they are read into memory. This approach doesn’t cause unnecessary bloat
and the performance overhead is significantly less to that encrypting individual cells in a database. It
is also transparent to other application so developers don’t have to change their code.

Implementing Transparent Data Encryption

The first step is to create a database master key (as shown above). Once you have a key you can then
create a certificate. You need to use the Database Master key to encrypt the certificate - using just a
password would result in an error. Then you need to create the Database Encryption Key object
encrypt this using the certificate.

Once you implement a TDE for a database the database will continue to be accessible but
maintenance operations are stopped and you can’t: drop a file, drop a filegroup, drop a database,
detach a database, take a database offline, set the database as read_only.

The following uses the master key, create the service master key and creates a server certificate.
Right click on a database, new query type the following and execute:

USE Master

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Password1'

CREATE CERTIFICATE TDECertificate WITH SUBJECT = 'Certificate For TDE'

You can now encrypt the database. If you right click on the same database which you ran the above
query and select Tasks -> Manage Database Encryption, you will get the database encryption wizard.
You can select the ‘Certificate for TDE’ you just created in the Use Server Certificate drop down box
and click ok.

Once a database is encrypted you need to make sure that the SQL Server service account has the
proper permissions otherwise you will receive an error when trying to drop a table for example.
Views
To date in this EBook tables have been used to represent data and information. Views are like virtual
tables but they don’t hold any data and their contents are defined by a query. One of the biggest
advantages of a View is that it can be used as a security measure by restricting access to certain
columns or rows. Also, you can use views to return a selective amount of data instead of detailed
data. A view protects the data layer while allowing access to the necessary data. A view differs to
that of a stored procedure in that it doesn’t use parameters to carry out a function.
Encrypting the View

You can create a view without columns which contain sensitive data and thus hide data you don’t
want to share. You can also encrypt the view definition which returns data of a privileged nature.
Not only are you restricting certain columns in a view you are also restricting who has access to the
view. However, once you encrypt a view it is difficult to get back to the original view detail. Best
approach is to make a backup of the original view.
Creating a view

To create a view in SSMS expand the database you are working on, right click on Views and select
New View. The View Designer will appear showing all the tables that you can add. Add the tables
you want in the View. Now select which columns you want in the View. You can now change the
sort type for each column from ascending to descending and can also give column names aliases. On
the right side of sort type there is Filter. Filter restricts what a user can and cannot see. Once you set
a filter (e.g. sales > 1000) a user cannot retrieve more information than this view allows. In the T-
SQL code there is a line stating TOP (100) PERCENT which is the default. You can remove it (also
remove the order by statement) or change the value. Once you have made the changes save the view
with the save button and start the view with vw_ syntax. You can view the contents of the view if
you refresh the database, open views, right click on the view and select top 1000 rows.

Indexing a view

You can index a view just like you can index a table. The rules are very similar. When you build a
view the first index needs to be a unique clustered index. Subsequent non clustered indexes can then
be created. You need to have the following set to on, and one off:

SET ANSI_NULLS ON

SET ANSI_PADDING ON

SET ANSI_WARNINGS ON

SET CONCAT_NULL_YIELDS_NULL ON

SET ARITHABORT ON

SET QUOTED_IDENTIFIER ON

SET NUMERIC_ROUNDABORT OFF


Now type the following: CREATE UNIQUE CLUSTERED INDEX _ixCustProduct

ON table.vw_CusProd(col1,col2)
Triggers
Sometimes a modification to the data in your database will need an automatic action on data
somewhere else, be it in your database, another database or within SQL Server. A trigger is an
object that will do it. A trigger in SQL Server is essentially a Stored Procedure which will run
performing the action you want to achieve. Triggers are mostly used to ensure the business logic is
being adhered to in the database, performing cascading data modifications (i.e. change on one table
will result in changes in other tables) and keeping track of specific changes to a table. SQL Server
supports three types of triggers:

DDL (Data Definition Language) triggers which fire off in response to a DDL statement being
executed (e.g. CREATE, ALTER or DROP). DDL triggers can be used for auditing or limiting
DBA activity.
Logon triggers are triggers that fire off when a session to the instance is established. This trigger
can be used to stop users from establishing a connection to an instance.
DML triggers (Data Manipulation Language) are triggers which fire off as a result of a DML
statement (INSERT, UPDATE, DELETE) being executed.
DDL Triggers

You can create DDL triggers at either the instance level (server scoped) or the database level (e.g.
tables being changed or dropped). You can create DDL triggers that respond to all database level
events at server level so that they respond to events in all databases.

DDL triggers can provide a mechanism for auditing or limiting the DBA which is useful when you
have a team that needs certain (e.g. elevated) permissions to databases. You can use these DDL
triggers to carry out the function a DBA would, very useful if you had a junior DBA on your team.

When a trigger is executing you have access to a function called EVENTDATA(). This is well
formed XML document, this includes data of the user who executed the original statement. So, you
can check this to ensure everything is proper. DDL triggers can respond to CREATE, ALTER,
DROP, GRANT, DENY, REVOKE and UPDATE STATISTICS. To create a DDL trigger you use
the CREATE TRIGGER DDL statement.

The structure of a CREATE TRIGGER is the following:

CREATE TRIGGER <Name>


ON <Scope>
WITH <Options>
AFTER
AS

<code>

ON - specifies the scope of the DDL trigger, there is ALL SERVER (instance level) and
DATABASE(level)
WITH – either with ENCRYPTION (to hide the definition of the trigger) or EXECUTE AS.
EXECUE AS takes one of the following - LOGIN, USER, SELF, OWNER, CALLER. It allows you
to change the security context of the trigger, i.e. it allows you to change permission level.

FOR or AFTER – either the FOR or AFTER keyword. Both are interchangeable in this context. The
trigger will execute after the original statement completes.

AS – specifies that either the SQL statements that define the code body of the trigger or the
EXTERNAL NAME clause to point to a CLR trigger.

The following is an example of a DDL trigger which stops any user dropping or altering any table on
the server scope:

CREATE TRIGGER DDLTriggerExample


ON ALL SERVER
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'If you want to alter/delete this table you will need to disable this trigger'
ROLLBACK;

You can disable triggers using the DISABLE TRIGGER and enable triggers with the ENABLE
TRIGGER command. The following command disables all triggers on the server scope:

DISABLE TRIGGER ALL ON ALL SERVER


Logon Triggers

Logon triggers are like DDL triggers except that instead of firing off in response to a DDL event they
fire off when a LOGON event occurs in the instance. Logon triggers have an advantage over other
logon event handling in SQL Server in that they can stop the user from establishing a connection. This
is because it fires at the same time as the event as opposed to waiting for it to complete.
This type of trigger is very useful when you want to limit the number of users connecting to the
instance. Say for example the server would be very busy in the evening running jobs, the following
example illustrates how you can limit access to the instance from 6pm to midnight except for the
sysacc account:

CREATE TRIGGER StopNightLogin


ON ALL SERVER
FOR LOGON
AS
BEGIN
IF (CAST(GETDATE() AS TIME) >= CAST('18:00:00' AS TIME)
AND CAST(GETDATE() AS TIME) <= CAST('24:00:00' AS TIME)
AND UPPER(ORIGINAL_LOGIN()) <> 'SYSACC')
ROLLBACK ;
END
DML Trigger

The most popular use for a DML trigger is to enforce a business rule. An example of enforcing a
business rule would be to ensure that there is enough stock before a customer places an order or that
the customer has enough money in their account. You can use the DML trigger to enforce extra
validation like complex data checks that constraints can’t, or make changes in another table based on
what is about to happened in the original table. The syntax for creating a DML trigger is the
following:

CREATE TRIGGER triggerName


On Table
WITH ENCRYPTION
FOR INSERT, UPDATE, DELETE
AS
IF UPDATE column and UPDATE column
COLUMNS_UPDATE()
Sql statements()

The syntax largely follows the other trigger types except with the FOR statement. This part of the
syntax determines what action will execute. The DML trigger can only specifically act on a data
modification action which can be only INSERT, DELETE or INSERT. The trigger can fire on one,
two or three of these commands, depending on what you want the trigger to do.

The IF UPDATE column AND OR UPDATE column is used to test whether a specific column has
been modified. You will get a logical TRUE or FALSE statement returned depending on whether the
column has been updated. If you delete a record it will not set this UPDATE to TRUE as it is being
removed.

The COLUMNS_UPDATE() is similar to UPDATE() but instead tests multiple columns.

The SQL statement() is the code which you want to execute, like any other stored procedure.

The following is an example of a DML trigger which execute when there has been an INSERT,
UPDATE or DELETE on the PersonTable
CREATE TRIGGER DMLTriggerExample
ON PersonTable
FOR INSERT, UPDATE, DELETE
AS
BEGIN
PRINT 'AFTER Trigger DMLTriggerExample has been executed!'
END

Now if you execute the above trigger and try to insert some values into the table PersonTable with the
following:

INSERT INTO dbo.PersonTable ( FirstName, LastName )


VALUES('Dovid','Malthe')

The trigger will be executed and you will receive the following messages in SSMS

AFTER Trigger DMLTriggerExample has been executed!


Trigger order

You can create multiple triggers which respond to the same event and can control which order in
which they execute. You do this by using the sp_settriggerorder stored procedure. It takes the
following parameters:

@triggername – the trigger name which you want to execute first or last.
@order – takes values FIRST, LAST, NONE.
@stmttype – this is the type of statement that causes the trigger to fire. For logon triggers it is the
logon event, for DDL triggers it is any DDL event (but you are not allowed to specify an event class).
For DML triggers, the value can be INSERT, UPDATE or DELETE.

@namespace – specifies the scope of the trigger. This can be specified as SERVER, DATABASE or
NULL. If NULL is passed, then it indicates that the trigger is a DML trigger.

The following example sets off the EnsureLicence logon trigger before the StopNightLogin trigger
which was created in the previous example.

USE Master
GO
EXEC sp_settriggerorder @triggername='EnsureLicense', @order='First', stmttype='LOGON',
@namespace='SERVER'
EXEC sp_settriggerorder @triggername='StopNightLogin', @order='Last', @stmttype='LOGON',
@namespace='SERVER'
Advanced T-SQL queries
A lot of the main functions of SQL Server and administrative tasks a DBA performs have been
covered in this EBook. Some of the more advanced features which you can perform are mainly to do
with T-SQL programming and getting queries to do more than the bare essentials.

Sometimes when working with SQL you need a query inside another query. This is known as a
subquery. You may need to create a list before you go and search for that list. Or producing a value
from another table and then setting that column with it.
Sequence

The sequence statement is a new addition to SQL Server. A sequence is a user defined object that
generates a sequence of numeric values according to the properties with which it was created. It acts
as an alternative to the IDENTITY column. Like the identity columns are not specifically associated
with tables, applications refer to the sequence object to retrieve the next value. The syntax for
creating a sequence is the following:

CREATE SEQUENCE sequenceName


AS builtInTypeInteger or userDefinedIntegerType
START WITH constant
INCREMENT BY constant
MINVALUE or no MINVALUE
MAXVALUE or no MAXVALUE
CYCLE or NOCYCLE
CACHE or NOCACHE

The optional as creates the sequence as a data type for example, tinyint, smallint, int, bigint, decimal
and numeric. A user defined type based can be used either based on one of these.

The START WITH – is the number the sequence starts with; the default is 1
The INCREMENT BY – defines the amount which increment; the default is 1
The MINVALUE value or NO MINVALUE – is used with the cycle option. This defines the
minimum value of the sequence. The default is the minimum value of the sequence.

CYCLE or NOCYCLE – if you don’t define a cycle and you reach the max value you will get an
error. If you do define CYCLE the sequence will then go to the minimum value of the sequence.

CACHE or NOCACHE – SQL Server performs a disk read every time you go to the next value in the
sequence. You can cache a range of numbers in memory and thus speed things up a lot. The only set
back to using the cache is that if the server may need to be restarted then the cache will be wiped.
CACHE is very handy when you are inserting a large number of rows.

Once you create your sequence you can retrieve the next value using the following syntax:

NEXT VALUE FOR sequenceName


Subqueries

A subquery is a query in another query which can be used anywhere an expression (like SELECT,
INSERT, UPDATE and DELETE) is allowed. A subquery can be used to check or set a value of a
variable or column or used to test whether a row of data exists in a WHERE clause. A subquery is
one of the most versatile statements in T-SQL.

To implement a subquery, you need to ensure that:

The subquery is enclosed in { } parenthesis


The subquery includes a SELECT and FROM clause
The subquery doesn’t include COMPUTE or FOR BROWSE clauses
You only nest 32 levels maximum.

The following is an example of adding a subquery to the select clause. You must return only value for
each row returned by the outer query.

SELECT
column1,
column2,
column3,
(
SELECT SUM(orderQty
FROM Table.column1
WHERE column1 = 1234
) AS TotalQuantity
FROM
Sales.SalesOrder
WHERE SalesOrderID = 1234
The above subquery returns a query of four columns (column1, column2, column3 and SalesOrderID)
where SalesOrderID equals ‘1234’.
IN Clause

If you want to look for a number of values in the WHERE clause, like a list of values, then you can
use an IN clause. The form of the IN clause is the following:

Expression IN (multivalued subquery)

The expression returns true if it is equal to any of the values in the multivalued subquery. The
following is an example of the IN clause which returns orders placed by employees with a last name
starting with J:

SELECT orderid
FROM Sales.Orders
WHERE employeeid IN
(SELECT E. employeeid
FROM HR.Employees AS E
WHERE E.lastname LIKE N'J%');

EXISTS Clause

The EXISTS clause is very similar to the IN clause in that it tests a column value against a subset of
data from a subquery. The difference is that EXISTS uses a join to join values from a column to
another column within the subquery. The syntax for the exists query is the following:

WHERE EXISTS (subquery)

You can place NOT and IN before the EXISTS. The following code example finds all names of all
products in the Wheels subcategory

SELECT Name
FROM Production.Product
WHERE EXISTS
(SELECT *
FROM Production.ProductSubcategory
WHERE ProductSubcategoryID =
Production.Product.ProductSubcategoryID
AND Name = 'Wheels')

Summary

Sequences are frequently used in databases as numerous applications need each row in a table to
contain to contain a unique value. Subqueries are self-contained and are independent from outer
queries and correlated subqueries. They are probably the most widely used item in T-SQL.
Subqueries combined with joins are very powerful.
Conclusion
Congratulations on finishing this EBook on SQL Server. Now that you have reached the end of the
EBook you should be feeling much more confident about setting up a new database, querying a
database and managing a SQL Server database.

In the first chapter, you have seen how to download and install the appropriate version of SQL Server
to your local machine. SQL Server is a powerful and free (* on some editions) software, having it up
and running quickly and relatively easily on numerous platforms such as Mac, Linux and Windows is
very compelling.

You have seen how to create tables, how to connect them together with relationships to ensure data
integrity and data consistency. Together with normalisation you have created a database which
properly models the real-world applications.

With Indexes, you have seen how it is possible to retrieve particular records in your database quickly
and with minimal changes. Adding either a clustered or nonclustered Index is relatively straight
forward with the graphical user interface and you can simply speed up your database should it get
beyond a certain size.

A lot of SQL focuses on the SQL queries. You have covered the SELECT, SELECT FROM and
ORDER BY clause. By utilising these basic SQL queries, you have learnt how to retrieve and
manipulate data in a database and serves as a stepping stone for more advanced T-SQL queries.

With Joins you have learn how to combine data from two sets of tables and find the matching
information. Joins are a much more readable than a query and the purpose of a join is usually much
obvious.

In the later stages of this EBook both the tasks for advanced queries, programming and database
administration have been covered. You have covered the two main SQL jobs in this EBook, a SQL
Developer who creates and fixes SQL code and a Database Administrator who will take care
installing, maintaining the SQL database. Having a working knowledge of both of these tasks makes
you extremely useful and versatile.

I wish you the very best of luck with SQL and SQL Server, it is a fantastic language used around the
globe. The skills you have learnt in this EBook will give you a solid foundation to build on and help
you develop your own database solutions.

This eBook was posted by AlenMiler on AvaxHome!

Many New eBooks in my Blog: http://avxhome.in/blogs/AlenMiler

Mirror: https://avxhome.unblocked.tw/blogs/AlenMiler

You might also like