SlideShare a Scribd company logo
Visit https://ebookultra.com to download the full version and
explore more ebooks
Essential SQL on SQL Server 2008 1st Edition Dr.
Sikha Bagui
_____ Click the link below to download _____
https://ebookultra.com/download/essential-sql-on-sql-
server-2008-1st-edition-dr-sikha-bagui/
Explore and download more ebooks at ebookultra.com
Here are some suggested products you might be interested in.
Click the link to download
Inside Microsoft SQL Server 2008 T SQL Querying 1st
Edition Itzik Ben-Gan
https://ebookultra.com/download/inside-microsoft-sql-
server-2008-t-sql-querying-1st-edition-itzik-ben-gan/
SQL Server 2008 Administration Instant Reference 1st
Edition Michael Lee
https://ebookultra.com/download/sql-server-2008-administration-
instant-reference-1st-edition-michael-lee/
Microsoft SQL Server 2008 Analysis Services Unleashed 1st
Edition Irina Gorbach
https://ebookultra.com/download/microsoft-sql-server-2008-analysis-
services-unleashed-1st-edition-irina-gorbach/
SQL Server T SQL Recipes 4th Edition Jason Brimhall
https://ebookultra.com/download/sql-server-t-sql-recipes-4th-edition-
jason-brimhall/
Microsoft SQL Server 2012 T SQL 1st Edition Tom Coffing
https://ebookultra.com/download/microsoft-sql-server-2012-t-sql-1st-
edition-tom-coffing/
Murach s SQL Server 2008 for Developers 3rd Edition Bryan
Syverson
https://ebookultra.com/download/murach-s-sql-server-2008-for-
developers-3rd-edition-bryan-syverson/
Microsoft SQL Server 2008 Administration with Windows
PowerShell 1st Edition Ananthakumar Muthusamy
https://ebookultra.com/download/microsoft-sql-
server-2008-administration-with-windows-powershell-1st-edition-
ananthakumar-muthusamy/
Protecting SQL Server Data John Magnabosco
https://ebookultra.com/download/protecting-sql-server-data-john-
magnabosco/
Professional Microsoft SQL Server 2008 Administration Wrox
Programmer to Programmer 1st Edition Brian Knight
https://ebookultra.com/download/professional-microsoft-sql-
server-2008-administration-wrox-programmer-to-programmer-1st-edition-
brian-knight/
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha
Bagui Digital Instant Download
Author(s): Dr. Sikha Bagui, Dr. Richard Earp
ISBN(s): 9780763781385, 076378138X
Edition: 1
File Details: PDF, 3.27 MB
Year: 2009
Language: english
Sikha Bagui | Richard Earp
2008
Essential SQL
on SQL Server®
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
Jones and Bartlett’s books and products are available through most bookstores and online booksellers. To con-
tact Jones and Bartlett Publishers directly, call 800-832-0034, fax 978-443-8000, or visit our website,
www.jbpub.com.
Substantial discounts on bulk quantities of Jones and Bartlett’s publications are available to corporations,
professional associations, and other qualified organizations. For details and specific discount information,
contact the special sales department at Jones and Bartlett via the above contact information or send an
email to specialsales@jbpub.com.
Copyright © 2011 by Jones and Bartlett Publishers, LLC
All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any
form, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval
system, without written permission from the copyright owner.
SQL Server 2008, Visual Studio, and Windows are registered trademarks of Microsoft Corporation in the
United States and other countries.
Production Credits
Publisher: David Pallai
Acquisitions Editor: Timothy McEvoy
Editorial Assistant: Melissa Potter
Associate Production Editor: Tiffany Sliter
Associate Marketing Manager: Lindsay Ruggiero
V.P., Manufacturing and Inventory Control: Therese Connell
Composition: Northeast Compositors, Inc.
Cover Design: Scott Moden
Cover Image: © Denis Babenko/ShutterStock, Inc.
Printing and Binding: Malloy, Inc.
Cover Printing: Malloy, Inc.
Library of Congress Cataloging-in-Publication Data
Bagui, Sikha, 1964-
Essential SQL on SQL server 2008 / Sikha Saha Bagui and Richard Walsh Earp.
p. cm.
Includes indexes.
ISBN-13: 978-0-7637-8138-5 (pbk.)
ISBN-10: 0-7637-8138-X
1. SQL (Computer program language) 2. SQL server. 3. Database design. 4. Database management. I. Earp,
Richard, 1940- II. Title.
QA76.73.S67B27 2010
005.75'85—dc22
2009033348
6048
Printed in the United States of America
13 12 11 10 09 10 9 8 7 6 5 4 3 2 1
World Headquarters
Jones and Bartlett Publishers
40 Tall Pine Drive
Sudbury, MA 01776
978-443-5000
info@jbpub.com
www.jbpub.com
Jones and Bartlett Publishers
Canada
6339 Ormindale Way
Mississauga, Ontario L5V 1J2
Canada
Jones and Bartlett Publishers
International
Barb House, Barb Mews
London W6 7PA
United Kingdom
Dedicated to my father, Santosh Saha, and mother, Ranu Saha,
and
my husband, Subhash Bagui
and
my sons, Sumon and Sudip
and
my brother, Pradeep, and nieces, Priyashi, and Piyali
S.B.
Dedicated to my wife, Brenda,
and
my children, Beryl, Rich, Gen, and Mary Jo
R.E.
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
c h a p t e r
11
Contents
Contents
Preface ix
Acknowledgments xiii
Chapter 1—Starting Microsoft® SQL Server® 2008 1
1.1 Starting Microsoft® SQL Server® 2008 and SQL Server
Management Studio 3
1.2 Creating a Database in Microsoft® SQL Server® 2008 5
1.3 The Query Editor 10
1.4 Creating Tables Using the Load Script 13
1.5 Viewing Table Designs 15
1.6 Modifying Table Designs 16
1.7 Viewing Table Data 19
1.8 Deleting a Table 19
1.9 Deleting a Database 20
1.10 Entering a SQL Query or Statement 20
1.11 Parsing a Query 21
1.12 Executing a Query 21
1.13 Saving a Query 22
1.14 Displaying the Results 22
1.15 Stopping Execution of a Long Query 22
1.16 Viewing Error Messages 25
1.17 Printing the Query and Results 25
1.18 Copying the Query and Results 25
1.19 Customizing Microsoft® SQL Server® 2008 25
Summary 27
Review Questions 27
Chapter 1 Exercises 27
v
vi Contents
Chapter 2—Beginning SQL Commands in Microsoft® SQL
Server® 29
2.1 Displaying Data with the SELECT Statement 30
2.2 Displaying or Selecting Columns from a Table 33
2.3 Displaying or SELECTing Rows from a Table 46
2.4 The COUNT Function 54
2.5 The ROWCOUNT Function 57
2.6 Using Aliases 58
2.7 Synonyms 63
2.8 Adding Comments to SQL Statements 65
2.9 Some Conventions for Writing SQL Statements 66
2.10 A Few Notes about Microsoft® SQL Server® 2008 Syntax 67
Summary 68
Review Questions 68
Chapter 2 Exercises 69
Chapter 3—Creating, Populating, Altering, and
Deleting Tables 71
3.1 Data Types in Microsoft® SQL Server® 2008 73
3.2 Creating a Table 81
3.3 Inserting Values into a Table 83
3.4 The UPDATE Command 91
3.5 The ALTER TABLE Command 93
3.6 The DELETE Command 97
3.7 Deleting a Table 98
Summary 98
Review Questions 98
Chapter 3 Exercises 99
References 100
Chapter 4—Joins 101
4.1 The JOIN 102
4.2 The Cartesian Product 110
4.3 Equi-Joins and Non-Equi-Joins 112
4.4 Self-Joins 113
4.5 Using ORDER BY with a Join 115
4.6 Joining More than Two Tables 116
4.7 The OUTER JOIN 118
Summary 123
Review Questions 123
Chapter 4 Exercises 123
Contents vii
Chapter 5—Functions 127
5.1 Aggregate Functions 130
5.2 Row-Level Functions 135
5.3 Other Functions 142
5.4 String Functions 148
5.5 Conversion Functions 164
5.6 Date Functions 167
Summary 174
Review Questions 174
Chapter 5 Exercises 175
Chapter 6—Query Development and Derived Structures 179
6.1 Query Development 180
6.2 Parentheses in SQL Expressions 185
6.3 Derived Structures 189
6.4 Query Development with Derived Structures 202
Summary 208
Review Questions 208
Chapter 6 Exercises 209
Chapter 7—Set Operations 213
7.1 Introducing Set Operations 214
7.2 The UNION Operation 216
7.3 The UNION ALL Operation 219
7.4 Handling UNION and/or UNION ALL Situations with an Unequal
Number of Columns 220
7.5 The IN and NOT ... IN Predicates 222
7.6 The Difference Operation 233
7.7 The Union and the JOIN 236
7.8 A UNION Used to Implement a Full Outer JOIN 242
Summary 243
Review Questions 244
Chapter 7 Exercises 244
Chapter 8—Joins Versus Subqueries 249
8.1 The IN Subquery 250
8.2 The Subquery as a JOIN 251
8.3 When the JOIN Cannot Be Turned into a Subquery 254
8.4 More Examples Involving Joins and IN 255
8.5 Using Subqueries with Operators 259
Summary 262
viii Contents
Review Questions 262
Chapter 8 Exercises 263
Chapter 9—Aggregation and GROUP BY 265
9.1 A SELECT in Modified BNF 266
9.2 The GROUP BY Clause 266
9.3 The HAVING Clause 272
9.4 GROUP BY and HAVING: Aggregates of Aggregates 274
9.5 Auditing in Subqueries 279
9.6 Nulls Revisited 283
Summary 286
Review Questions 287
Chapter 9 Exercises 287
Chapter 10—Correlated Subqueries 291
10.1 Noncorrelated Subqueries 292
10.2 Correlated Subqueries 293
10.3 Existence Queries and Correlation 295
10.4 SQL Universal and Existential Qualifiers 308
Summary 315
Review Questions 316
Chapter 10 Exercises 316
Chapter 11—Indexes and Constraints on Tables 321
11.1 The “Simple” CREATE TABLE 322
11.2 Indexes 323
11.3 Constraints 327
Summary 349
Review Questions 349
Chapter 11 Exercises 350
Appendix 1 355
Appendix 2 359
Glossary of Important Commands and Functions 373
Index 381
c h a p t e r
11
Preface
Preface
Why This Book?
SQL Server® database software is one of the most powerful database engines
used today. Microsoft’s latest release of SQL Server, SQL Server® 2008, is a
comprehensive database platform that provides secure and reliable storage
for both relational and structured data, enabling one to build and manage
high-performance data applications. SQL Server 2008’s close integration
with Microsoft® Visual Studio® development system, Microsoft® Office®
system, and a suite of new development tools sets it apart from previous
versions and from other database engines. This system allows one to build,
debug, and operate applications faster than ever before.
SQL Server 2008 can be installed on small machines using the Micro-
soft® Windows® operating system as well as large servers. In recent years,
the computer industry has seen a dramatic increase in the popularity of
relational databases and multiuser databases, and there is a great need for
application developers and people who can write SQL code efficiently and
correctly for relational and multiuser databases. This book focuses on SQL
programming using SQL Server 2008—a relational and multiuser database.
The book is aimed at students who wish to learn SQL using Microsoft’s
SQL Server 2008, and is expected to be used by schools and SQL training
organizations, as well as by database and IT professionals who are actively
working with SQL Server 2008.
This book is mainly intended to be a systematic learning guide to
learn SQL using SQL Server 2008. The book starts with very simple SQL
concepts, and slowly builds into more complex query development. The
purpose of this book is to present every topic, concept, and idea with ex-
amples of code and output. Exercises have also been included so the user
ix
x Preface
gains proficiency in SQL using SQL Server. The best approach to using this
book efficiently is to read with SQL Server open and active. As the book
is read, it will be advantageous to actually work through the examples.
If the book is being used for a beginning database course, students can
do the exercises over the course of one semester at a pace of one chapter
per week. The exercises are found at the ends of the respective chapters.
Due to the dramatic increase in the popularity of relational and mul-
tiuser databases, many schools and training organizations are using SQL
Server in their database courses to teach database principles and concepts.
This has generated a need for a concise book on SQL Server programming:
Essential SQL on SQL Server® 2008.
SQL and SQL Server
SQL (Structured Query Language) is a standard language used for query-
ing, updating, and managing relational databases, and lately SQL has be-
come the de facto standard “language” for accessing relational databases.
SQL is not really a language so much as it is a database query tool. In this
book, we concentrate on learning SQL using SQL Server 2008.
SQL allows us to define a relational database by creating and modifying
tables (in this sense, SQL is a data definition language, or DDL). SQL also
allows us to tell SQL Server which information we want to select (retrieve),
insert, update, or delete. That is, SQL also allows us to query the relational
database in a flexible way, as well as change the stored data (in this sense,
SQL is a data manipulation language, or DML).
This book is targeted at SQL Server users on the Windows operating
system, but is easily adaptable to other platforms.
Audience and Coverage
This book can be used as a standalone exercise to learn SQL using SQL
Server 2008. It can also be used to supplement a theoretical database text
in an introductory databases class. This book does not assume any prior
database knowledge.
This book consists of 11 chapters. Chapter 1 introduces the user to
SQL Server 2008, explaining how to open SQL Server, load the database,
and view and perform simple table manipulations. Chapter 1 also covers
how and where to enter a SQL query, how to customize SQL Server 2008’s
settings, and how to connect to other databases. Chapter 2 introduces
the user to some beginning SQL commands in SQL Server. Chapter 3
discusses creating, populating, altering, and deleting tables, as relational
databases are built on the idea of tabular data. Chapter 4 introduces and
covers all types of joins, which are a common database mechanism for
Preface xi
combining tables. Chapter 5 covers SQL Server 2008’s functions. Chapter
6 discusses query development as well as the use of views and other derived
structures. Chapter 7 covers simple set operations. Chapters 8, 9, and 10
cover subqueries, aggregate functions, and correlated subqueries. Chapter
11 addresses indexes and constraints that can be added to tables in SQL
Server 2008.
Appendix 1 describes the Student course database and other tables
that are used throughout the book. Appendix 2 contains the script that
loads the Student course database. A glossary of important commands
and functions has also been provided.
This book is complete enough for beginning SQL users to get an
overview of what SQL Server entails and how to use SQL. There are even
many SQL programmers who have based their employment on this mate-
rial. This book gives the user a very good feel for what SQL is, and how it
is used in SQL Server.
—Sikha Bagui and Richard Earp
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
c h a p t e r
11
Acknowledgments
Acknowledgments
Our special thanks to Tim McEvoy and the incredible staff at Jones and
Bartlett Publishers for their hard work putting this book together.
We would also like to thank President Judy Bense and Provost Chula
King for their inspiration, encouragement, and true leadership qualities,
and Dean Jane Halonen for her continuing support.
Our sincere appreciation also goes to Dr. Leo TerHaar, chair of the Com-
puter Science Department, for his advice, guidance, and support through
the completion of this book, as well as Dr. Norman Wilde and Dr. Ed
Rodgers for their continuing encouragement. And, last but not least, we
would like to thank our fellow faculty members and Diana Walker for their
continuous support.
xiii
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
c h a p t e r
1
Starting Microsoft SQL Server
2008
c h a p t e r
1
Starting Microsoft® SQL
Server® 2008
Topics covered in this chapter
Starting Microsoft® SQL Server® 2008 and SQL Server Management
Studio
Creating a Database in Microsoft® SQL Server® 2008
Objects in the Student course Database
Default Tables in the Student course Database
Default System Databases
The Query Editor
Opening the Query Editor by Right-Clicking
Opening the Query Editor Using the New Query Button
Opening (or Activating) the Database Using USE
Creating Tables Using the Load Script
Viewing Table Designs
Modifying Table Designs
Modifying Column Designs
Modifying the Table Design Directly
Viewing Table Data
1
2 CHAPTER 1 Starting Microsoft SQL Server 2008
Deleting a Table
Deleting a Database
Entering a SQL Query or Statement
Parsing a Query
Executing a Query
Color Coding
Saving a Query
Displaying the Results
Viewing Results in Grid Form
Viewing Results in Text Form
Saving Results to File
Stopping Execution of a Long Query
Viewing Error Messages
Printing the Query and Results
Copying the Query and Results
Customizing Microsoft® SQL Server® 2008
The Environment Tab
The Text Editor Tab
The Query Execution Tab
The Query Results Tab
The SQL Server Query Explorer Tab
The Designers Tab
The Source Control Tab
Summary
Review Questions
Chapter 1 Exercises
In this chapter, you will learn about the basic workings of Microsoft®
SQL Server® 2008 and SQL Server 2008’s Management Studio. You will
learn how to create a database, view the objects and default tables in a
database, use the query editor, activate the database in different ways, and
create tables in the database using a load script. The load script is available
1.1 STARTING MICROSOFT SQL SERVER 2008 3
at http://www.cs.uwf.edu/∼sbagui. When run from SQL Server, the
load script creates the Student course database that is used throughout
this text. At this point, copy the load script, SQLServer2008 load.sql, by
right-clicking on the script on the website, selecting Save Target As, and
saving it to your working directory.
You will also learn how to view and modify a table design; delete a table
and a database; type, parse, execute, and save a query; display results in
different forms; stop execution of a query; and print a query and its results.
The final section of this chapter discusses customizing SQL Server 2008’s
settings.
1.1 Starting Microsoft® SQL Server® 2008 and SQL Server Man-
agement Studio
In this section, we will show you how to start Microsoft SQL Server 2008
and open up SQL Server 2008’s Management Studio.
From the Start menu, go to All Programs, select Microsoft SQL
Server 2008, and then select SQL Server Management Studio, as
shown in Figure 1.1.
Figure 1.1 Opening Microsoft SQL Server 2008 and SQL Server Management
Studio
4 CHAPTER 1 Starting Microsoft SQL Server 2008
You will see the dialog box shown in Figure 1.2. This dialog box will
allow you to connect to Microsoft SQL Server 2008. To connect to a server
other than the default, enter the appropriate Server type and Server
name, and select Windows Authentication. Then click Connect.
Figure 1.2 Connecting to Microsoft SQL Server 2008
You will now be connected to the server that you indicated, and you
will see the image shown in Figure 1.3. Figure 1.3 is the Microsoft SQL
Server Management Studio screen that we will be using throughout
the rest of the book.
Figure 1.3 Connected to Microsoft SQL Server 2008’s server
The Microsoft SQL Server Management Studio screen contains the
Object Explorer on the left portion of the screen. The Object Explorer
1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 5
provides a hierarchical view of objects. For example, you can drill down
into a database, table, column, or other object, as we will soon show you.
1.2 Creating a Database in Microsoft® SQL Server® 2008
Before we begin to work with Microsoft SQL Server 2008, we will create a
database. To create a database, right-click on Databases and select New
Database . . . as shown in Figure 1.4.
Figure 1.4 Creating a new database
You will see the screen shown in Figure 1.5. We will create a database
called Student course, type Student course as the Database name.
You may leave the Owner as <default> for now, as shown in Figure 1.5,
and click OK. You will see the screen shown in Figure 1.6.
6 CHAPTER 1 Starting Microsoft SQL Server 2008
Figure 1.5 Typing in the database name
Click here
Figure 1.6 Viewing the databases
1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 7
The Student course database has now been created. As shown in Fig-
ure 1.6, you may now expand the databases node by clicking on the + sign
beside Databases in the Object Explorer (on the left side of your screen).
You will also see the Student course database node under Databases,
as shown in Figure 1.7.
Click here
Figure 1.7 The Student course database in the Object Explorer
1.2.1 Objects in the Student_course Database
A SQL Server database is a collection of many objects, such as tables,
views, and synonyms that are defined to support activities performed with
data.
In Figure 1.7, expand the Student course database node by clicking
on the + sign beside the Student course node. You will see Figure 1.8,
which shows the default objects that are in the Student course database.
8 CHAPTER 1 Starting Microsoft SQL Server 2008
Figure 1.8 Viewing the objects in the Student course database
1.2.2 Default Tables in the Student_course database
A database is a collection of related tables. So far we have created the
Student course database, but we have not created any tables.
To view the default tables in the Student course database, expand
the Tables node, as shown in Figure 1.9. The only thing there right now
is a folder called System Tables. This folder will be populated by SQL
Server as we create and use our new database.
Click here
Figure 1.9 Default tables in the Student course database
1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 9
At this point you may click on the – sign beside the Tables node, and
then on the – sign beside the Student course node to close those up; your
screen will now look like Figure 1.7.
1.2.3 Default System Databases
SQL Server 2008 comes with some default system databases—master,
model, msdb, and tempdb. To view these default database nodes, expand
the Database node and then the System Databases node, as shown in
Figure 1.10.
First click
Second click
Figure 1.10 Default system databases
master is a database comprised of system tables that keeps track of
server installation as a whole and all other databases that are subsequently
created. SQL Server 2008 defaults to the master database.
model is a template database. Every time a new database is created,
SQL Server makes a copy of the model database to form the basis of the new
database. If you want all your new databases to inherit certain properties,
you could include these properties in your model database.
msdb is a database that performs scheduled activities such as backups
and replication tasks.
tempdb is a temporary database or workspace recreated every time
SQL Server is restarted. tempdb is used to hold temporary tables created
by users and intermediate results created internally by SQL Server during
query processing and sorting.
10 CHAPTER 1 Starting Microsoft SQL Server 2008
1.3 The Query Editor
The most important thing in SQL Server 2008, or any other database for
that matter, is querying the database—using the database to find informa-
tion about the data stored therein. Queries in SQL Server 2008 are typed
in the query editor. In this section, we will show you how to open the query
editor. The query editor can be opened in two ways: by right-clicking with
your mouse or by clicking the New Query button. We will illustrate both
ways.
1.3.1 Opening the Query Editor by Right-Clicking
Select the Student course database and right-click. Then select New
Query as shown in Figure 1.11.
Figure 1.11 Opening the query editor
You will see an image similar to Figure 1.12, which shows the query
editor. The query editor can be used to create queries and other SQL scripts
and to execute them against SQL Server databases. A script is a prewritten
series of queries as opposed to a single, ad hoc query. Scripts are stored in
text files and usually are created using an editor such as Notepad.
The first query will be called SQLQuery1.sql by default. Later we will
show you how to change the name of the query when saving it.
If the query editor is opened in this way, the Student course database
1.3 THE QUERY EDITOR 11
The Student_course database has been opened
Type your query here
The query editor screen
Figure 1.12 The query editor
is automatically activated. If we want to work in our Student course
database, we have to make sure it is active. If it is not active, we have
to activate it. We show you how to do this in the following sections.
1.3.2 Opening the Query Editor Using the New Query Button
You can also open the query editor by selecting the New Query button
from the toolbar (leftmost icon), as shown in Figure 1.13.
New Query button
Figure 1.13 The New Query button
If you used the New Query button in Figure 1.13 without selecting the
Student course database, you will see the screen shown in Figure 1.14.
12 CHAPTER 1 Starting Microsoft SQL Server 2008
Here, note that master is the active database rather than Student course.
master database is active
You type in a query here
Figure 1.14 The query screen
But we want to use the Student course database that we just created,
so we have to activate it. Click on the drop-down icon of the combo box
beside master and select Student course, as shown in Figure 1.15. This
activates (or opens) the Student course database.
Click here
Figure 1.15 Selecting the Student course database
1.3.3 Opening (or Activating) the Database Using USE
You can also activate or open the Student course database by typing the
following in the query editor, as shown in Figure 1.16:
USE Student course
1.4 CREATING TABLES USING THE LOAD SCRIPT 13
Then click on the Execute button in the menu bar above the query
editor screen.
You will get the following message in the results pane, as shown in
Figure 1.16:
Command(s) completed successfully
Execute button
Results pane
Figure 1.16 Using USE
1.4 Creating Tables Using the Load Script
After we activate the Student course database, we will create tables in the
database and insert data into the tables. To do this, we will run (execute)
the load script, SQLServer2008 load.sql, which you already downloaded
and saved to your working directory.
Go to the directory where you saved the load script, and double-click
the script to open it. Then select the entire script and copy it. This script
will have to be pasted into SQL Server 2008’s query editor.
Open the SQL Server 2008’s query editor as shown in Section 1.3.1.
Make sure the Student course database is active. Then paste the load
script into the query editor, as shown in Figure 1.17.
14 CHAPTER 1 Starting Microsoft SQL Server 2008
Figure 1.17 Pasting the load script into the query editor
Once the script has been pasted into the query editor, execute this
script by clicking the Execute button. This script only takes a few seconds
to execute. You should see the results shown in Figure 1.18.
Figure 1.18 Executed load script
This script creates the following tables in the Student course database
and inserts data into them: Course, Department to major, Dependent,
Grade report, Languages, Plants, Prereq, Room, Section, Student, and
teststu. The tables in the Student course database are presented in Ap-
pendix 1, and the load script is presented in Appendix 2.
1.5 VIEWING TABLE DESIGNS 15
To view the tables that were created by the load script, expand the
Student course node by clicking on the + sign beside Student course,
and then expand the Tables node by clicking on the + sign beside Tables.
(If you don’t see the tables you just created, you may need to close Man-
agement Studio and restart it.) You should see Figure 1.19. Every table
shows up as a node under Student course.
First click
Second click
Figure 1.19 Viewing the tables in the Student course database
1.5 Viewing Table Designs
Every table in SQL Server 2008 has a table design. The table design gives
us information about a table such as the column (or field) names, the data
types of the columns, and whether the columns allow null (missing) values.
To view the design of the Student table, for example, expand the
Student node by clicking on the + sign beside it, and then expand the
Columns node by clicking on the + sign beside it, as shown in Figure 1.20.
You will be able to view the columns in the Student table. The columns
in the Student table are stno, sname, major, class, and bdate.
16 CHAPTER 1 Starting Microsoft SQL Server 2008
First click
Second click
Figure 1.20 Viewing the table design of the Student table
1.6 Modifying Table Designs
If you wish to modify any of the column specifications, for example, if you
want to insert or delete columns, rename a column, change the data type
of a column, or allow or disallow null fields, you would need to modify the
table design. The table design can be modified in two ways by modifying
the column design or by modifying the table design. We illustrate both
ways to change a table design in the following sections.
1.6.1 Modifying Column Designs
To modify the column design, right-click on the column that you wish to
modify. For example, if you wish to modify the design of the sname column
in the Student table, right-click on SNAME, as shown in Figure 1.21, and
select one of the following options—New Column, Modify, Rename,
Delete, Refresh, or Properties.
1.6 MODIFYING TABLE DESIGNS 17
Figure 1.21 Modifying the column design
1.6.2 Modifying the Table Design Directly
Another way to view or modify the table design is to right-click on the
table. For example, select Student (as shown in Figure 1.22), and then
select Design.
18 CHAPTER 1 Starting Microsoft SQL Server 2008
Figure 1.22 Modifying/viewing the table design
The table design of the Student table is now displayed, as shown in
Figure 1.23.
Table design of Student table
Figure 1.23 Viewing the table design of the Student table using the Design
option
1.7 VIEWING TABLE DATA 19
Here, you can delete or insert columns, change the data types, and
allow or disallow null fields. Once you have finished making your changes
(or just viewing the table design, if that is what you intended to do), you
can close this window. You will be asked if you wish to save the changes;
select Yes or No, depending on whether or not you made changes to the
table design and you want to save the changes.
1.7 Viewing Table Data
To view the data in a table, right-click on the table, as shown in Figure
1.22, and select Select Top 1000 Rows. For example, to view the data of
the Student table, right-click on the Student table, and select Select Top
1000 Rows. You will see a screen similar to Figure 1.24. Note that the
query used by the system shows up on the top portion of the screen (the
query editor screen), and the results are presented in the results pane (on
the bottom portion of the screen).
Results in the results pane
Query used by system
Number of rows
Figure 1.24 Viewing the data in the Student table
This will show all 48 rows of the Student table. The number of rows
presented in the output is displayed at the bottom-right corner of the figure.
1.8 Deleting a Table
To delete a table, right-click on the table that you wish to delete (as shown
in Figure 1.22), and then select Delete. Deleting a table will delete the
table, the table design, and the data in the table. Once you delete a table,
there is no way to get the table or its data back. Be very careful to ensure
20 CHAPTER 1 Starting Microsoft SQL Server 2008
that you indeed intend to permanently dispose of data before selecting
Delete.
Note: Please do NOT delete any tables right now. Just note
this section for later, since you may have to delete tables at some
point.
1.9 Deleting a Database
To delete a database, right-click on the database that you would like to
delete, and select Delete, as shown in Figure 1.25.
Note: Please do NOT delete the database right now.
Figure 1.25 Deleting a database
1.10 Entering a SQL Query or Statement
A SQL query or statement is used to give instructions to the computer. A
query is a request for data stored in SQL Server. The computer analyzes
each instruction and interprets it. If the instruction is “understandable” to
the database engine, the program produces a result. If the computer cannot
figure out what the instruction means, it will display an error message.
In SQL Server 2008, the SQL query is entered in the query editor screen
as shown in Figure 1.12. But before you type your query, make sure the
1.11 PARSING A QUERY 21
database that you wish to work with is active or open. To type in or work
on the queries in this book, the Student course database should be active
or open.
Right-click on Student course and select New Query as shown in
Figure 1.11. Enter the following SQL query in the query editor screen:
USE Student course
SELECT *
FROM Student
“USE Student course” is used to activate the Student course data-
base, as shown in Figure 1.12. “SELECT” is the SQL keyword that means
“select data” or “retrieve the following data from the database.” The “*”
is interpreted to mean “show all columns in the result.” “FROM” is the
keyword that is used before a table name, and “Student” is the name of a
table. This is a simple SQL query that tells the system to display all the
rows and columns (all the data) in the Student table.
1.11 Parsing a Query
Before you execute your query, you may want to parse it to be sure it is
written correctly. The Parse Query button is shown in Figure 1.26.
1.12 Executing a Query
To execute a query, click the Execute button above the query editor screen.
If the query is correct, the Execute button will execute (run) the query
and the results will show on the Results pane (bottom partition) of the
screen, as shown in Figure 1.26. If the query is incorrect, an error message
will be presented on the Results pane of the screen as shown in Figure
1.26.
22 CHAPTER 1 Starting Microsoft SQL Server 2008
Execute button Parse Query button
Results pane
Figure 1.26 Displaying output
1.12.1 Color Coding
The automatic color coding of SQL code in the query editor will help you
enter your SQL query correctly as well as prevent and resolve errors. If you
are using the default color codes, for example, and you type in a keyword
that is not then displayed in blue, the keyword is probably misspelled. If
your code is displayed in red, you might have omitted a closing quotation
mark for a character string.
1.13 Saving a Query
To save a query while the query is on the query editor screen, select File
from the main menu, and then select Save SQLQuery1.sql As. . . . A
dialog box will open up and you will be able to type a name for your query
and navigate to a directory where you can save it.
1.14 Displaying the Results
Results in SQL Server 2008 are displayed in the Results pane. The Results
pane is shown in Figure 1.26. SQL queries can be executed to view results
in grid form or text form, or the results can be saved to a file. We discuss
each of the options to display or view the results in the following sections.
1.14 DISPLAYING THE RESULTS 23
Cancel query
execution
Results to
text
Results to
grid
Results to
file
Caption cut
off
Figure 1.27 Displaying the results icons
1.14.1 Viewing Results in Grid Form
The grid form displays the results in spreadsheet-like grids.
To execute a query and view query results in grid form, first click on
the Results to grid icon (this icon is shown in Figure 1.27) and then click
the Execute button. Note that the Results to grid option is the default
option.
You may also press <F5> on the keyboard to execute queries.
Your results will be in grid form, as shown in Figure 1.28.
Messages
tab
Number of rows
in result
Name of database
Figure 1.28 Viewing results in grid form
In Figure 1.28, the name of the database and the number of rows in
the result set are displayed at the bottom of the screen.
24 CHAPTER 1 Starting Microsoft SQL Server 2008
1.14.2 Viewing Results in Text Form
To execute a query and view query results in text form, click the Results
to text icon (this icon is shown in Figure 1.27) and then click the Execute
button.
You will now see the results in text form, as shown in Figure 1.26.
Viewing the output in text form may make it easier for you to copy and
paste the output into a word processor so that you can use it in a report or
print it. Figure 1.26 also displays the name of the database and the number
of rows in the result set at the bottom of the screen.
1.14.3 Saving Results to File
To save your query results to a file, select the Results to file icon (this
icon is shown in Figure 1.27), and then click the Execute button.
The Save Results window will come up and you will be able to se-
lect the appropriate directory, enter the appropriate filename, and save
the results to file for later use. The RESULTS TO FILE option saves the
results as a Crystal Reports file. It is beyond the scope of this book to
discuss Crystal Reports, but the report file can be opened with Notepad
by right-clicking it and using the Open With option if you navigate to
the appropriate directory outside of SQL Server.
To open this Crystal Report (or saved file) from within SQL Server,
select File from the main menu, and then Open, and select File (as shown
in Figure 1.29). Navigate to the directory where you saved your file and
select your file; your results will be displayed on the screen.
Figure 1.29 Opening Crystal Reports
1.19 Customizing Microsoft SQL Server 2008 25
1.15 Stopping Execution of a Long Query
If you want to stop or interrupt the execution of a long-running query, you
can click on the Cancel Query Execution button (shown in Figure 1.27)
or press Alt-Break. This option can be used for queries on very large tables
but may not be needed with the database used here.
1.16 Viewing Error Messages
To view error messages, click on the Messages tab (shown in Figure 1.28).
This displays any messages, including error messages, of the SQL query
output.
1.17 Printing the Query and Results
Once the SQL query is on the query editor screen, you can print the query
by selecting File from the main menu and then selecting Print.
To print the results displayed in the Results pane, place your cursor in
the Results pane by clicking anywhere in the pane (see Figure 1.26 for the
Results pane), and then select File from the main menu and then Print.
You can also right-click anywhere in the Results pane and select Print.
When the results are saved to file, they can, of course, be retrieved and
printed from the file.
1.18 Copying the Query and Results
Once the SQL query is on the query editor screen, you can select the entire
query by highlighting it and then right-clicking. Select Copy, and paste it
wherever you wish.
To copy a portion of the results, highlight the portion that you would
like to copy, right-click, and then select Copy. The Results to grid option
has an option of Copy with Headers, which copies the results along with
the headers.
1.19 Customizing Microsoft® SQL Server® 2008
You can customize some options in SQL Server 2008 by selecting Tools
from the main menu and then Options. Once you select Tools and Options,
you will see the following tabs: Environment, Text Editor, Query Ex-
ecution, Query Results, SQL Server Query Explorer, Designers,
and Source Control.
26 CHAPTER 1 Starting Microsoft SQL Server 2008
1.19.1 The Environment Tab
The Environment tab contains the General, Fonts and Colors, Key-
board, and Help options.
Among other options, the General option allows you to change the
default start-up window of SQL Server 2008.
The Fonts and Colors option allows you to change, among other things,
an item’s foreground and background colors.
The Keyboard option allows you to change keyboarding options like
Shortcuts.
1.19.2 The Text Editor Tab
The Text Editor tab allows you to change the default editor and set
language and text options.
1.19.3 The Query Execution Tab
The Query Execution tab allows you to change the default ROWCOUNT
options, TEXTSIZE options, execution time-out length, and other settings.
1.19.4 The Query Results Tab
The Query Results tab allows you to change the default type of results,
the default location for results to be saved, and other settings.
1.19.5 The SQL Server Query Explorer Tab
The SQL Server Query Explorer tab allows you to change table and
viewing options and scripting options.
1.19.6 The Designer Tab
The Designer tab allows you to change the default table and database
designer settings.
1.19.7 The Source Control Tab
The Source Control tab specifies the source control plug-in to use with
Microsoft SQL Server Management Studio and allows changes to plug-in-
specific options.
Chapter 1 Exercises 27
SUMMARY
In this chapter, we have shown you how to start Microsoft® SQL Server®
2008 and SQL Server 2008’s Management Studio. We have also shown
you how to create the Student course database that we will be using
throughout the rest of this book. In addition, we have demonstrated how
to work with tables, and how to type, parse, execute, and save a simple
query. In the process, we have also familiarized you with the main screens
and workings of SQL Server 2008’s Management Studio. Toward the end
of the chapter, we showed you how to change some of SQL Server 2008’s
default settings to suit your needs.
Review Questions
1. If you want to see what columns a table is made of and what the sizes
of the fields are, what option do you have to look for?
2. What is a query?
3. A SQL query is typed in the .
4. What is the purpose of the model database?
5. What is the purpose of the master database?
6. What is the purpose of the tempdb database?
7. What is the purpose of the USE command?
8. If you delete a table in the database, will the data in the table also be
deleted?
9. What is the Parse Query button used for? How does this help you?
10. Tables are created in a in SQL Server 2008.
Chapter 1 Exercises
The tables available in the Student_course database are shown in
Appendix 1. You may want to look at Appendix 1 before starting
this section.
1. The Student course database contains the following tables: Student,
Department to major, Grade report, Section, Dependent, Course,
Prereq, Room, Languages, Plants, and teststu.
a. View the table design of each of these tables. To save and print
your table design, we suggest that you copy and paste your table
design into a word processor where you can save it for later use or
print it out.
b. View the data of each of these tables. Save your results to file and
also print them out.
28 CHAPTER 1 Starting Microsoft SQL Server 2008
2. Write a SQL query to view all the columns and rows in the Student
table (Hint: To retrieve all columns, use “SELECT *” in your query;
the “*” means “all columns”).
a. View the results in grid form and print the results.
b. View the results in text form and print the results.
c. Save the results to file.
d. Save the query.
c h a p t e r
2
Beginning SQL Commands in
Microsoft SQL Server
c h a p t e r
2
Beginning SQL Commands
in Microsoft® SQL Server ®
Topics covered in this chapter
Displaying Data with the SELECT Statement
SELECT without the FROM
Displaying or Selecting Columns from a Table
Displaying or SELECTing One Column from a Table
Display or SELECTing More Than One Column from a Table
Displaying or SELECTing All Columns of a Table
ORDER BY
ORDER BY and NULLs
Ascending and Descending Order
Ordering Within an Order
Displaying or SELECTing Rows from a Table
Filtering with WHERE
The AND Operator
The OR Operator
The BETWEEN Operator
29
30 CHAPTER 2 Beginning SQL Commands in Microsoft SQL Server
Negating the BETWEEN Operator
The COUNT Function
IS NULL
IS NOT NULL
The ROWCOUNT Function
Using Aliases
Column Aliases
Table Aliases
Table Aliases Used as Table Qualifiers
Synonyms
Adding Comments to SQL Statements
Some Conventions for Writing SQL Statements
A Few Notes about Microsoft® SQL Server® 2008 Syntax
Summary
Review Questions
Chapter 2 Exercises
In Chapter 1, we introduced you to some of the basics of Microsoft®
SQL Server® 2008 and SQL Server 2008’s Management Studio. We provided
instructions on creating a database, the Student course database, which
we will be using in this chapter and throughout the rest of the book. We
also showed you how and where to enter and execute a query.
In this chapter, we discuss how to write (build) simple SQL query
statements in SQL Server 2008 using the SELECT statement. We examine
how to retrieve data from a table by the use of SELECT statements, how
to SELECT columns (fields) and rows from tables, how to use the ORDER
BY and WHERE clauses, and how to use the AND, OR, and BETWEEN
operators. The concepts of COUNT and null values are also introduced.
Then, to make writing queries clearer and simpler, we discuss how to use
table and column aliases, table qualifiers, and synonyms, and finally we
present a convention for writing SQL statements.
2.1 Displaying Data with the SELECT Statement
One of the first things that you will usually want to do with a database
containing a set of tables is to see what information the tables contain.
To display the information from a table using a query, you use a SELECT
Another Random Scribd Document
with Unrelated Content
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.
1.F.4. Except for the limited right of replacement or refund set
forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the
Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.
The Foundation’s business office is located at 809 North 1500
West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.
The Foundation is committed to complying with the laws
regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states
where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.
International donations are gratefully accepted, but we cannot
make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.
Please check the Project Gutenberg web pages for current
donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.
Section 5. General Information About
Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.
Project Gutenberg™ eBooks are often created from several
printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

More Related Content

PDF
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
PDF
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
PPT
Presentation1
PDF
Learning SQL
PDF
Learning SQL
PDF
SQL Overview
PDF
Sql overview-1232931296681161-1
PDF
DP080_Lecture_1 SQL lecture document .pdf
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui
Presentation1
Learning SQL
Learning SQL
SQL Overview
Sql overview-1232931296681161-1
DP080_Lecture_1 SQL lecture document .pdf

Similar to Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui (20)

PPTX
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
PPTX
Introduction to SQL
DOC
Introduction to sql
PPTX
SQL(database)
PDF
FUNDAMENTOS DE MATEMATICAS
PPT
Ch 9 S Q L
PPT
PDF
MSBI Classroom Training with Realtime Project
PPTX
Sql for biggner
PPT
SQLPpt.ppt
PPT
hoffer_edm_pp_ch06.ppt
PPT
hoffer_edm_pp_ch06.ppt
PPT
hoffer_edm_pp_ch06.ppt
PPT
SQLB1.ppt
PPT
hoffer_edm_pp_ch06.ppt
PPT
hoffer_edm_pp_ch06.ppt
PPT
Review of SQL
PDF
Free Demo on #Microsoft #SQLServer & #T-SQL with #Azure from SQL School.
PPT
SQL Inteoduction to SQL manipulating of data
PDF
SQL command for daily use ddl dml dcl dql
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
Introduction to SQL
Introduction to sql
SQL(database)
FUNDAMENTOS DE MATEMATICAS
Ch 9 S Q L
MSBI Classroom Training with Realtime Project
Sql for biggner
SQLPpt.ppt
hoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppt
SQLB1.ppt
hoffer_edm_pp_ch06.ppt
hoffer_edm_pp_ch06.ppt
Review of SQL
Free Demo on #Microsoft #SQLServer & #T-SQL with #Azure from SQL School.
SQL Inteoduction to SQL manipulating of data
SQL command for daily use ddl dml dcl dql
Ad

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Basic Mud Logging Guide for educational purpose
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Complications of Minimal Access Surgery at WLH
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Institutional Correction lecture only . . .
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
master seminar digital applications in india
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Types and Its function , kingdom of life
O7-L3 Supply Chain Operations - ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
Basic Mud Logging Guide for educational purpose
TR - Agricultural Crops Production NC III.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Microbial disease of the cardiovascular and lymphatic systems
Complications of Minimal Access Surgery at WLH
102 student loan defaulters named and shamed – Is someone you know on the list?
Abdominal Access Techniques with Prof. Dr. R K Mishra
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Institutional Correction lecture only . . .
Sports Quiz easy sports quiz sports quiz
master seminar digital applications in india
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPH.pptx obstetrics and gynecology in nursing
VCE English Exam - Section C Student Revision Booklet
Cell Types and Its function , kingdom of life
Ad

Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui

  • 1. Visit https://ebookultra.com to download the full version and explore more ebooks Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui _____ Click the link below to download _____ https://ebookultra.com/download/essential-sql-on-sql- server-2008-1st-edition-dr-sikha-bagui/ Explore and download more ebooks at ebookultra.com
  • 2. Here are some suggested products you might be interested in. Click the link to download Inside Microsoft SQL Server 2008 T SQL Querying 1st Edition Itzik Ben-Gan https://ebookultra.com/download/inside-microsoft-sql- server-2008-t-sql-querying-1st-edition-itzik-ben-gan/ SQL Server 2008 Administration Instant Reference 1st Edition Michael Lee https://ebookultra.com/download/sql-server-2008-administration- instant-reference-1st-edition-michael-lee/ Microsoft SQL Server 2008 Analysis Services Unleashed 1st Edition Irina Gorbach https://ebookultra.com/download/microsoft-sql-server-2008-analysis- services-unleashed-1st-edition-irina-gorbach/ SQL Server T SQL Recipes 4th Edition Jason Brimhall https://ebookultra.com/download/sql-server-t-sql-recipes-4th-edition- jason-brimhall/
  • 3. Microsoft SQL Server 2012 T SQL 1st Edition Tom Coffing https://ebookultra.com/download/microsoft-sql-server-2012-t-sql-1st- edition-tom-coffing/ Murach s SQL Server 2008 for Developers 3rd Edition Bryan Syverson https://ebookultra.com/download/murach-s-sql-server-2008-for- developers-3rd-edition-bryan-syverson/ Microsoft SQL Server 2008 Administration with Windows PowerShell 1st Edition Ananthakumar Muthusamy https://ebookultra.com/download/microsoft-sql- server-2008-administration-with-windows-powershell-1st-edition- ananthakumar-muthusamy/ Protecting SQL Server Data John Magnabosco https://ebookultra.com/download/protecting-sql-server-data-john- magnabosco/ Professional Microsoft SQL Server 2008 Administration Wrox Programmer to Programmer 1st Edition Brian Knight https://ebookultra.com/download/professional-microsoft-sql- server-2008-administration-wrox-programmer-to-programmer-1st-edition- brian-knight/
  • 5. Essential SQL on SQL Server 2008 1st Edition Dr. Sikha Bagui Digital Instant Download Author(s): Dr. Sikha Bagui, Dr. Richard Earp ISBN(s): 9780763781385, 076378138X Edition: 1 File Details: PDF, 3.27 MB Year: 2009 Language: english
  • 6. Sikha Bagui | Richard Earp 2008 Essential SQL on SQL Server®
  • 8. Jones and Bartlett’s books and products are available through most bookstores and online booksellers. To con- tact Jones and Bartlett Publishers directly, call 800-832-0034, fax 978-443-8000, or visit our website, www.jbpub.com. Substantial discounts on bulk quantities of Jones and Bartlett’s publications are available to corporations, professional associations, and other qualified organizations. For details and specific discount information, contact the special sales department at Jones and Bartlett via the above contact information or send an email to specialsales@jbpub.com. Copyright © 2011 by Jones and Bartlett Publishers, LLC All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any form, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the copyright owner. SQL Server 2008, Visual Studio, and Windows are registered trademarks of Microsoft Corporation in the United States and other countries. Production Credits Publisher: David Pallai Acquisitions Editor: Timothy McEvoy Editorial Assistant: Melissa Potter Associate Production Editor: Tiffany Sliter Associate Marketing Manager: Lindsay Ruggiero V.P., Manufacturing and Inventory Control: Therese Connell Composition: Northeast Compositors, Inc. Cover Design: Scott Moden Cover Image: © Denis Babenko/ShutterStock, Inc. Printing and Binding: Malloy, Inc. Cover Printing: Malloy, Inc. Library of Congress Cataloging-in-Publication Data Bagui, Sikha, 1964- Essential SQL on SQL server 2008 / Sikha Saha Bagui and Richard Walsh Earp. p. cm. Includes indexes. ISBN-13: 978-0-7637-8138-5 (pbk.) ISBN-10: 0-7637-8138-X 1. SQL (Computer program language) 2. SQL server. 3. Database design. 4. Database management. I. Earp, Richard, 1940- II. Title. QA76.73.S67B27 2010 005.75'85—dc22 2009033348 6048 Printed in the United States of America 13 12 11 10 09 10 9 8 7 6 5 4 3 2 1 World Headquarters Jones and Bartlett Publishers 40 Tall Pine Drive Sudbury, MA 01776 978-443-5000 info@jbpub.com www.jbpub.com Jones and Bartlett Publishers Canada 6339 Ormindale Way Mississauga, Ontario L5V 1J2 Canada Jones and Bartlett Publishers International Barb House, Barb Mews London W6 7PA United Kingdom
  • 9. Dedicated to my father, Santosh Saha, and mother, Ranu Saha, and my husband, Subhash Bagui and my sons, Sumon and Sudip and my brother, Pradeep, and nieces, Priyashi, and Piyali S.B. Dedicated to my wife, Brenda, and my children, Beryl, Rich, Gen, and Mary Jo R.E.
  • 11. c h a p t e r 11 Contents Contents Preface ix Acknowledgments xiii Chapter 1—Starting Microsoft® SQL Server® 2008 1 1.1 Starting Microsoft® SQL Server® 2008 and SQL Server Management Studio 3 1.2 Creating a Database in Microsoft® SQL Server® 2008 5 1.3 The Query Editor 10 1.4 Creating Tables Using the Load Script 13 1.5 Viewing Table Designs 15 1.6 Modifying Table Designs 16 1.7 Viewing Table Data 19 1.8 Deleting a Table 19 1.9 Deleting a Database 20 1.10 Entering a SQL Query or Statement 20 1.11 Parsing a Query 21 1.12 Executing a Query 21 1.13 Saving a Query 22 1.14 Displaying the Results 22 1.15 Stopping Execution of a Long Query 22 1.16 Viewing Error Messages 25 1.17 Printing the Query and Results 25 1.18 Copying the Query and Results 25 1.19 Customizing Microsoft® SQL Server® 2008 25 Summary 27 Review Questions 27 Chapter 1 Exercises 27 v
  • 12. vi Contents Chapter 2—Beginning SQL Commands in Microsoft® SQL Server® 29 2.1 Displaying Data with the SELECT Statement 30 2.2 Displaying or Selecting Columns from a Table 33 2.3 Displaying or SELECTing Rows from a Table 46 2.4 The COUNT Function 54 2.5 The ROWCOUNT Function 57 2.6 Using Aliases 58 2.7 Synonyms 63 2.8 Adding Comments to SQL Statements 65 2.9 Some Conventions for Writing SQL Statements 66 2.10 A Few Notes about Microsoft® SQL Server® 2008 Syntax 67 Summary 68 Review Questions 68 Chapter 2 Exercises 69 Chapter 3—Creating, Populating, Altering, and Deleting Tables 71 3.1 Data Types in Microsoft® SQL Server® 2008 73 3.2 Creating a Table 81 3.3 Inserting Values into a Table 83 3.4 The UPDATE Command 91 3.5 The ALTER TABLE Command 93 3.6 The DELETE Command 97 3.7 Deleting a Table 98 Summary 98 Review Questions 98 Chapter 3 Exercises 99 References 100 Chapter 4—Joins 101 4.1 The JOIN 102 4.2 The Cartesian Product 110 4.3 Equi-Joins and Non-Equi-Joins 112 4.4 Self-Joins 113 4.5 Using ORDER BY with a Join 115 4.6 Joining More than Two Tables 116 4.7 The OUTER JOIN 118 Summary 123 Review Questions 123 Chapter 4 Exercises 123
  • 13. Contents vii Chapter 5—Functions 127 5.1 Aggregate Functions 130 5.2 Row-Level Functions 135 5.3 Other Functions 142 5.4 String Functions 148 5.5 Conversion Functions 164 5.6 Date Functions 167 Summary 174 Review Questions 174 Chapter 5 Exercises 175 Chapter 6—Query Development and Derived Structures 179 6.1 Query Development 180 6.2 Parentheses in SQL Expressions 185 6.3 Derived Structures 189 6.4 Query Development with Derived Structures 202 Summary 208 Review Questions 208 Chapter 6 Exercises 209 Chapter 7—Set Operations 213 7.1 Introducing Set Operations 214 7.2 The UNION Operation 216 7.3 The UNION ALL Operation 219 7.4 Handling UNION and/or UNION ALL Situations with an Unequal Number of Columns 220 7.5 The IN and NOT ... IN Predicates 222 7.6 The Difference Operation 233 7.7 The Union and the JOIN 236 7.8 A UNION Used to Implement a Full Outer JOIN 242 Summary 243 Review Questions 244 Chapter 7 Exercises 244 Chapter 8—Joins Versus Subqueries 249 8.1 The IN Subquery 250 8.2 The Subquery as a JOIN 251 8.3 When the JOIN Cannot Be Turned into a Subquery 254 8.4 More Examples Involving Joins and IN 255 8.5 Using Subqueries with Operators 259 Summary 262
  • 14. viii Contents Review Questions 262 Chapter 8 Exercises 263 Chapter 9—Aggregation and GROUP BY 265 9.1 A SELECT in Modified BNF 266 9.2 The GROUP BY Clause 266 9.3 The HAVING Clause 272 9.4 GROUP BY and HAVING: Aggregates of Aggregates 274 9.5 Auditing in Subqueries 279 9.6 Nulls Revisited 283 Summary 286 Review Questions 287 Chapter 9 Exercises 287 Chapter 10—Correlated Subqueries 291 10.1 Noncorrelated Subqueries 292 10.2 Correlated Subqueries 293 10.3 Existence Queries and Correlation 295 10.4 SQL Universal and Existential Qualifiers 308 Summary 315 Review Questions 316 Chapter 10 Exercises 316 Chapter 11—Indexes and Constraints on Tables 321 11.1 The “Simple” CREATE TABLE 322 11.2 Indexes 323 11.3 Constraints 327 Summary 349 Review Questions 349 Chapter 11 Exercises 350 Appendix 1 355 Appendix 2 359 Glossary of Important Commands and Functions 373 Index 381
  • 15. c h a p t e r 11 Preface Preface Why This Book? SQL Server® database software is one of the most powerful database engines used today. Microsoft’s latest release of SQL Server, SQL Server® 2008, is a comprehensive database platform that provides secure and reliable storage for both relational and structured data, enabling one to build and manage high-performance data applications. SQL Server 2008’s close integration with Microsoft® Visual Studio® development system, Microsoft® Office® system, and a suite of new development tools sets it apart from previous versions and from other database engines. This system allows one to build, debug, and operate applications faster than ever before. SQL Server 2008 can be installed on small machines using the Micro- soft® Windows® operating system as well as large servers. In recent years, the computer industry has seen a dramatic increase in the popularity of relational databases and multiuser databases, and there is a great need for application developers and people who can write SQL code efficiently and correctly for relational and multiuser databases. This book focuses on SQL programming using SQL Server 2008—a relational and multiuser database. The book is aimed at students who wish to learn SQL using Microsoft’s SQL Server 2008, and is expected to be used by schools and SQL training organizations, as well as by database and IT professionals who are actively working with SQL Server 2008. This book is mainly intended to be a systematic learning guide to learn SQL using SQL Server 2008. The book starts with very simple SQL concepts, and slowly builds into more complex query development. The purpose of this book is to present every topic, concept, and idea with ex- amples of code and output. Exercises have also been included so the user ix
  • 16. x Preface gains proficiency in SQL using SQL Server. The best approach to using this book efficiently is to read with SQL Server open and active. As the book is read, it will be advantageous to actually work through the examples. If the book is being used for a beginning database course, students can do the exercises over the course of one semester at a pace of one chapter per week. The exercises are found at the ends of the respective chapters. Due to the dramatic increase in the popularity of relational and mul- tiuser databases, many schools and training organizations are using SQL Server in their database courses to teach database principles and concepts. This has generated a need for a concise book on SQL Server programming: Essential SQL on SQL Server® 2008. SQL and SQL Server SQL (Structured Query Language) is a standard language used for query- ing, updating, and managing relational databases, and lately SQL has be- come the de facto standard “language” for accessing relational databases. SQL is not really a language so much as it is a database query tool. In this book, we concentrate on learning SQL using SQL Server 2008. SQL allows us to define a relational database by creating and modifying tables (in this sense, SQL is a data definition language, or DDL). SQL also allows us to tell SQL Server which information we want to select (retrieve), insert, update, or delete. That is, SQL also allows us to query the relational database in a flexible way, as well as change the stored data (in this sense, SQL is a data manipulation language, or DML). This book is targeted at SQL Server users on the Windows operating system, but is easily adaptable to other platforms. Audience and Coverage This book can be used as a standalone exercise to learn SQL using SQL Server 2008. It can also be used to supplement a theoretical database text in an introductory databases class. This book does not assume any prior database knowledge. This book consists of 11 chapters. Chapter 1 introduces the user to SQL Server 2008, explaining how to open SQL Server, load the database, and view and perform simple table manipulations. Chapter 1 also covers how and where to enter a SQL query, how to customize SQL Server 2008’s settings, and how to connect to other databases. Chapter 2 introduces the user to some beginning SQL commands in SQL Server. Chapter 3 discusses creating, populating, altering, and deleting tables, as relational databases are built on the idea of tabular data. Chapter 4 introduces and covers all types of joins, which are a common database mechanism for
  • 17. Preface xi combining tables. Chapter 5 covers SQL Server 2008’s functions. Chapter 6 discusses query development as well as the use of views and other derived structures. Chapter 7 covers simple set operations. Chapters 8, 9, and 10 cover subqueries, aggregate functions, and correlated subqueries. Chapter 11 addresses indexes and constraints that can be added to tables in SQL Server 2008. Appendix 1 describes the Student course database and other tables that are used throughout the book. Appendix 2 contains the script that loads the Student course database. A glossary of important commands and functions has also been provided. This book is complete enough for beginning SQL users to get an overview of what SQL Server entails and how to use SQL. There are even many SQL programmers who have based their employment on this mate- rial. This book gives the user a very good feel for what SQL is, and how it is used in SQL Server. —Sikha Bagui and Richard Earp
  • 19. c h a p t e r 11 Acknowledgments Acknowledgments Our special thanks to Tim McEvoy and the incredible staff at Jones and Bartlett Publishers for their hard work putting this book together. We would also like to thank President Judy Bense and Provost Chula King for their inspiration, encouragement, and true leadership qualities, and Dean Jane Halonen for her continuing support. Our sincere appreciation also goes to Dr. Leo TerHaar, chair of the Com- puter Science Department, for his advice, guidance, and support through the completion of this book, as well as Dr. Norman Wilde and Dr. Ed Rodgers for their continuing encouragement. And, last but not least, we would like to thank our fellow faculty members and Diana Walker for their continuous support. xiii
  • 21. c h a p t e r 1 Starting Microsoft SQL Server 2008 c h a p t e r 1 Starting Microsoft® SQL Server® 2008 Topics covered in this chapter Starting Microsoft® SQL Server® 2008 and SQL Server Management Studio Creating a Database in Microsoft® SQL Server® 2008 Objects in the Student course Database Default Tables in the Student course Database Default System Databases The Query Editor Opening the Query Editor by Right-Clicking Opening the Query Editor Using the New Query Button Opening (or Activating) the Database Using USE Creating Tables Using the Load Script Viewing Table Designs Modifying Table Designs Modifying Column Designs Modifying the Table Design Directly Viewing Table Data 1
  • 22. 2 CHAPTER 1 Starting Microsoft SQL Server 2008 Deleting a Table Deleting a Database Entering a SQL Query or Statement Parsing a Query Executing a Query Color Coding Saving a Query Displaying the Results Viewing Results in Grid Form Viewing Results in Text Form Saving Results to File Stopping Execution of a Long Query Viewing Error Messages Printing the Query and Results Copying the Query and Results Customizing Microsoft® SQL Server® 2008 The Environment Tab The Text Editor Tab The Query Execution Tab The Query Results Tab The SQL Server Query Explorer Tab The Designers Tab The Source Control Tab Summary Review Questions Chapter 1 Exercises In this chapter, you will learn about the basic workings of Microsoft® SQL Server® 2008 and SQL Server 2008’s Management Studio. You will learn how to create a database, view the objects and default tables in a database, use the query editor, activate the database in different ways, and create tables in the database using a load script. The load script is available
  • 23. 1.1 STARTING MICROSOFT SQL SERVER 2008 3 at http://www.cs.uwf.edu/∼sbagui. When run from SQL Server, the load script creates the Student course database that is used throughout this text. At this point, copy the load script, SQLServer2008 load.sql, by right-clicking on the script on the website, selecting Save Target As, and saving it to your working directory. You will also learn how to view and modify a table design; delete a table and a database; type, parse, execute, and save a query; display results in different forms; stop execution of a query; and print a query and its results. The final section of this chapter discusses customizing SQL Server 2008’s settings. 1.1 Starting Microsoft® SQL Server® 2008 and SQL Server Man- agement Studio In this section, we will show you how to start Microsoft SQL Server 2008 and open up SQL Server 2008’s Management Studio. From the Start menu, go to All Programs, select Microsoft SQL Server 2008, and then select SQL Server Management Studio, as shown in Figure 1.1. Figure 1.1 Opening Microsoft SQL Server 2008 and SQL Server Management Studio
  • 24. 4 CHAPTER 1 Starting Microsoft SQL Server 2008 You will see the dialog box shown in Figure 1.2. This dialog box will allow you to connect to Microsoft SQL Server 2008. To connect to a server other than the default, enter the appropriate Server type and Server name, and select Windows Authentication. Then click Connect. Figure 1.2 Connecting to Microsoft SQL Server 2008 You will now be connected to the server that you indicated, and you will see the image shown in Figure 1.3. Figure 1.3 is the Microsoft SQL Server Management Studio screen that we will be using throughout the rest of the book. Figure 1.3 Connected to Microsoft SQL Server 2008’s server The Microsoft SQL Server Management Studio screen contains the Object Explorer on the left portion of the screen. The Object Explorer
  • 25. 1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 5 provides a hierarchical view of objects. For example, you can drill down into a database, table, column, or other object, as we will soon show you. 1.2 Creating a Database in Microsoft® SQL Server® 2008 Before we begin to work with Microsoft SQL Server 2008, we will create a database. To create a database, right-click on Databases and select New Database . . . as shown in Figure 1.4. Figure 1.4 Creating a new database You will see the screen shown in Figure 1.5. We will create a database called Student course, type Student course as the Database name. You may leave the Owner as <default> for now, as shown in Figure 1.5, and click OK. You will see the screen shown in Figure 1.6.
  • 26. 6 CHAPTER 1 Starting Microsoft SQL Server 2008 Figure 1.5 Typing in the database name Click here Figure 1.6 Viewing the databases
  • 27. 1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 7 The Student course database has now been created. As shown in Fig- ure 1.6, you may now expand the databases node by clicking on the + sign beside Databases in the Object Explorer (on the left side of your screen). You will also see the Student course database node under Databases, as shown in Figure 1.7. Click here Figure 1.7 The Student course database in the Object Explorer 1.2.1 Objects in the Student_course Database A SQL Server database is a collection of many objects, such as tables, views, and synonyms that are defined to support activities performed with data. In Figure 1.7, expand the Student course database node by clicking on the + sign beside the Student course node. You will see Figure 1.8, which shows the default objects that are in the Student course database.
  • 28. 8 CHAPTER 1 Starting Microsoft SQL Server 2008 Figure 1.8 Viewing the objects in the Student course database 1.2.2 Default Tables in the Student_course database A database is a collection of related tables. So far we have created the Student course database, but we have not created any tables. To view the default tables in the Student course database, expand the Tables node, as shown in Figure 1.9. The only thing there right now is a folder called System Tables. This folder will be populated by SQL Server as we create and use our new database. Click here Figure 1.9 Default tables in the Student course database
  • 29. 1.2 CREATING A DATABASE IN MICROSOFT SQL SERVER 2008 9 At this point you may click on the – sign beside the Tables node, and then on the – sign beside the Student course node to close those up; your screen will now look like Figure 1.7. 1.2.3 Default System Databases SQL Server 2008 comes with some default system databases—master, model, msdb, and tempdb. To view these default database nodes, expand the Database node and then the System Databases node, as shown in Figure 1.10. First click Second click Figure 1.10 Default system databases master is a database comprised of system tables that keeps track of server installation as a whole and all other databases that are subsequently created. SQL Server 2008 defaults to the master database. model is a template database. Every time a new database is created, SQL Server makes a copy of the model database to form the basis of the new database. If you want all your new databases to inherit certain properties, you could include these properties in your model database. msdb is a database that performs scheduled activities such as backups and replication tasks. tempdb is a temporary database or workspace recreated every time SQL Server is restarted. tempdb is used to hold temporary tables created by users and intermediate results created internally by SQL Server during query processing and sorting.
  • 30. 10 CHAPTER 1 Starting Microsoft SQL Server 2008 1.3 The Query Editor The most important thing in SQL Server 2008, or any other database for that matter, is querying the database—using the database to find informa- tion about the data stored therein. Queries in SQL Server 2008 are typed in the query editor. In this section, we will show you how to open the query editor. The query editor can be opened in two ways: by right-clicking with your mouse or by clicking the New Query button. We will illustrate both ways. 1.3.1 Opening the Query Editor by Right-Clicking Select the Student course database and right-click. Then select New Query as shown in Figure 1.11. Figure 1.11 Opening the query editor You will see an image similar to Figure 1.12, which shows the query editor. The query editor can be used to create queries and other SQL scripts and to execute them against SQL Server databases. A script is a prewritten series of queries as opposed to a single, ad hoc query. Scripts are stored in text files and usually are created using an editor such as Notepad. The first query will be called SQLQuery1.sql by default. Later we will show you how to change the name of the query when saving it. If the query editor is opened in this way, the Student course database
  • 31. 1.3 THE QUERY EDITOR 11 The Student_course database has been opened Type your query here The query editor screen Figure 1.12 The query editor is automatically activated. If we want to work in our Student course database, we have to make sure it is active. If it is not active, we have to activate it. We show you how to do this in the following sections. 1.3.2 Opening the Query Editor Using the New Query Button You can also open the query editor by selecting the New Query button from the toolbar (leftmost icon), as shown in Figure 1.13. New Query button Figure 1.13 The New Query button If you used the New Query button in Figure 1.13 without selecting the Student course database, you will see the screen shown in Figure 1.14.
  • 32. 12 CHAPTER 1 Starting Microsoft SQL Server 2008 Here, note that master is the active database rather than Student course. master database is active You type in a query here Figure 1.14 The query screen But we want to use the Student course database that we just created, so we have to activate it. Click on the drop-down icon of the combo box beside master and select Student course, as shown in Figure 1.15. This activates (or opens) the Student course database. Click here Figure 1.15 Selecting the Student course database 1.3.3 Opening (or Activating) the Database Using USE You can also activate or open the Student course database by typing the following in the query editor, as shown in Figure 1.16: USE Student course
  • 33. 1.4 CREATING TABLES USING THE LOAD SCRIPT 13 Then click on the Execute button in the menu bar above the query editor screen. You will get the following message in the results pane, as shown in Figure 1.16: Command(s) completed successfully Execute button Results pane Figure 1.16 Using USE 1.4 Creating Tables Using the Load Script After we activate the Student course database, we will create tables in the database and insert data into the tables. To do this, we will run (execute) the load script, SQLServer2008 load.sql, which you already downloaded and saved to your working directory. Go to the directory where you saved the load script, and double-click the script to open it. Then select the entire script and copy it. This script will have to be pasted into SQL Server 2008’s query editor. Open the SQL Server 2008’s query editor as shown in Section 1.3.1. Make sure the Student course database is active. Then paste the load script into the query editor, as shown in Figure 1.17.
  • 34. 14 CHAPTER 1 Starting Microsoft SQL Server 2008 Figure 1.17 Pasting the load script into the query editor Once the script has been pasted into the query editor, execute this script by clicking the Execute button. This script only takes a few seconds to execute. You should see the results shown in Figure 1.18. Figure 1.18 Executed load script This script creates the following tables in the Student course database and inserts data into them: Course, Department to major, Dependent, Grade report, Languages, Plants, Prereq, Room, Section, Student, and teststu. The tables in the Student course database are presented in Ap- pendix 1, and the load script is presented in Appendix 2.
  • 35. 1.5 VIEWING TABLE DESIGNS 15 To view the tables that were created by the load script, expand the Student course node by clicking on the + sign beside Student course, and then expand the Tables node by clicking on the + sign beside Tables. (If you don’t see the tables you just created, you may need to close Man- agement Studio and restart it.) You should see Figure 1.19. Every table shows up as a node under Student course. First click Second click Figure 1.19 Viewing the tables in the Student course database 1.5 Viewing Table Designs Every table in SQL Server 2008 has a table design. The table design gives us information about a table such as the column (or field) names, the data types of the columns, and whether the columns allow null (missing) values. To view the design of the Student table, for example, expand the Student node by clicking on the + sign beside it, and then expand the Columns node by clicking on the + sign beside it, as shown in Figure 1.20. You will be able to view the columns in the Student table. The columns in the Student table are stno, sname, major, class, and bdate.
  • 36. 16 CHAPTER 1 Starting Microsoft SQL Server 2008 First click Second click Figure 1.20 Viewing the table design of the Student table 1.6 Modifying Table Designs If you wish to modify any of the column specifications, for example, if you want to insert or delete columns, rename a column, change the data type of a column, or allow or disallow null fields, you would need to modify the table design. The table design can be modified in two ways by modifying the column design or by modifying the table design. We illustrate both ways to change a table design in the following sections. 1.6.1 Modifying Column Designs To modify the column design, right-click on the column that you wish to modify. For example, if you wish to modify the design of the sname column in the Student table, right-click on SNAME, as shown in Figure 1.21, and select one of the following options—New Column, Modify, Rename, Delete, Refresh, or Properties.
  • 37. 1.6 MODIFYING TABLE DESIGNS 17 Figure 1.21 Modifying the column design 1.6.2 Modifying the Table Design Directly Another way to view or modify the table design is to right-click on the table. For example, select Student (as shown in Figure 1.22), and then select Design.
  • 38. 18 CHAPTER 1 Starting Microsoft SQL Server 2008 Figure 1.22 Modifying/viewing the table design The table design of the Student table is now displayed, as shown in Figure 1.23. Table design of Student table Figure 1.23 Viewing the table design of the Student table using the Design option
  • 39. 1.7 VIEWING TABLE DATA 19 Here, you can delete or insert columns, change the data types, and allow or disallow null fields. Once you have finished making your changes (or just viewing the table design, if that is what you intended to do), you can close this window. You will be asked if you wish to save the changes; select Yes or No, depending on whether or not you made changes to the table design and you want to save the changes. 1.7 Viewing Table Data To view the data in a table, right-click on the table, as shown in Figure 1.22, and select Select Top 1000 Rows. For example, to view the data of the Student table, right-click on the Student table, and select Select Top 1000 Rows. You will see a screen similar to Figure 1.24. Note that the query used by the system shows up on the top portion of the screen (the query editor screen), and the results are presented in the results pane (on the bottom portion of the screen). Results in the results pane Query used by system Number of rows Figure 1.24 Viewing the data in the Student table This will show all 48 rows of the Student table. The number of rows presented in the output is displayed at the bottom-right corner of the figure. 1.8 Deleting a Table To delete a table, right-click on the table that you wish to delete (as shown in Figure 1.22), and then select Delete. Deleting a table will delete the table, the table design, and the data in the table. Once you delete a table, there is no way to get the table or its data back. Be very careful to ensure
  • 40. 20 CHAPTER 1 Starting Microsoft SQL Server 2008 that you indeed intend to permanently dispose of data before selecting Delete. Note: Please do NOT delete any tables right now. Just note this section for later, since you may have to delete tables at some point. 1.9 Deleting a Database To delete a database, right-click on the database that you would like to delete, and select Delete, as shown in Figure 1.25. Note: Please do NOT delete the database right now. Figure 1.25 Deleting a database 1.10 Entering a SQL Query or Statement A SQL query or statement is used to give instructions to the computer. A query is a request for data stored in SQL Server. The computer analyzes each instruction and interprets it. If the instruction is “understandable” to the database engine, the program produces a result. If the computer cannot figure out what the instruction means, it will display an error message. In SQL Server 2008, the SQL query is entered in the query editor screen as shown in Figure 1.12. But before you type your query, make sure the
  • 41. 1.11 PARSING A QUERY 21 database that you wish to work with is active or open. To type in or work on the queries in this book, the Student course database should be active or open. Right-click on Student course and select New Query as shown in Figure 1.11. Enter the following SQL query in the query editor screen: USE Student course SELECT * FROM Student “USE Student course” is used to activate the Student course data- base, as shown in Figure 1.12. “SELECT” is the SQL keyword that means “select data” or “retrieve the following data from the database.” The “*” is interpreted to mean “show all columns in the result.” “FROM” is the keyword that is used before a table name, and “Student” is the name of a table. This is a simple SQL query that tells the system to display all the rows and columns (all the data) in the Student table. 1.11 Parsing a Query Before you execute your query, you may want to parse it to be sure it is written correctly. The Parse Query button is shown in Figure 1.26. 1.12 Executing a Query To execute a query, click the Execute button above the query editor screen. If the query is correct, the Execute button will execute (run) the query and the results will show on the Results pane (bottom partition) of the screen, as shown in Figure 1.26. If the query is incorrect, an error message will be presented on the Results pane of the screen as shown in Figure 1.26.
  • 42. 22 CHAPTER 1 Starting Microsoft SQL Server 2008 Execute button Parse Query button Results pane Figure 1.26 Displaying output 1.12.1 Color Coding The automatic color coding of SQL code in the query editor will help you enter your SQL query correctly as well as prevent and resolve errors. If you are using the default color codes, for example, and you type in a keyword that is not then displayed in blue, the keyword is probably misspelled. If your code is displayed in red, you might have omitted a closing quotation mark for a character string. 1.13 Saving a Query To save a query while the query is on the query editor screen, select File from the main menu, and then select Save SQLQuery1.sql As. . . . A dialog box will open up and you will be able to type a name for your query and navigate to a directory where you can save it. 1.14 Displaying the Results Results in SQL Server 2008 are displayed in the Results pane. The Results pane is shown in Figure 1.26. SQL queries can be executed to view results in grid form or text form, or the results can be saved to a file. We discuss each of the options to display or view the results in the following sections.
  • 43. 1.14 DISPLAYING THE RESULTS 23 Cancel query execution Results to text Results to grid Results to file Caption cut off Figure 1.27 Displaying the results icons 1.14.1 Viewing Results in Grid Form The grid form displays the results in spreadsheet-like grids. To execute a query and view query results in grid form, first click on the Results to grid icon (this icon is shown in Figure 1.27) and then click the Execute button. Note that the Results to grid option is the default option. You may also press <F5> on the keyboard to execute queries. Your results will be in grid form, as shown in Figure 1.28. Messages tab Number of rows in result Name of database Figure 1.28 Viewing results in grid form In Figure 1.28, the name of the database and the number of rows in the result set are displayed at the bottom of the screen.
  • 44. 24 CHAPTER 1 Starting Microsoft SQL Server 2008 1.14.2 Viewing Results in Text Form To execute a query and view query results in text form, click the Results to text icon (this icon is shown in Figure 1.27) and then click the Execute button. You will now see the results in text form, as shown in Figure 1.26. Viewing the output in text form may make it easier for you to copy and paste the output into a word processor so that you can use it in a report or print it. Figure 1.26 also displays the name of the database and the number of rows in the result set at the bottom of the screen. 1.14.3 Saving Results to File To save your query results to a file, select the Results to file icon (this icon is shown in Figure 1.27), and then click the Execute button. The Save Results window will come up and you will be able to se- lect the appropriate directory, enter the appropriate filename, and save the results to file for later use. The RESULTS TO FILE option saves the results as a Crystal Reports file. It is beyond the scope of this book to discuss Crystal Reports, but the report file can be opened with Notepad by right-clicking it and using the Open With option if you navigate to the appropriate directory outside of SQL Server. To open this Crystal Report (or saved file) from within SQL Server, select File from the main menu, and then Open, and select File (as shown in Figure 1.29). Navigate to the directory where you saved your file and select your file; your results will be displayed on the screen. Figure 1.29 Opening Crystal Reports
  • 45. 1.19 Customizing Microsoft SQL Server 2008 25 1.15 Stopping Execution of a Long Query If you want to stop or interrupt the execution of a long-running query, you can click on the Cancel Query Execution button (shown in Figure 1.27) or press Alt-Break. This option can be used for queries on very large tables but may not be needed with the database used here. 1.16 Viewing Error Messages To view error messages, click on the Messages tab (shown in Figure 1.28). This displays any messages, including error messages, of the SQL query output. 1.17 Printing the Query and Results Once the SQL query is on the query editor screen, you can print the query by selecting File from the main menu and then selecting Print. To print the results displayed in the Results pane, place your cursor in the Results pane by clicking anywhere in the pane (see Figure 1.26 for the Results pane), and then select File from the main menu and then Print. You can also right-click anywhere in the Results pane and select Print. When the results are saved to file, they can, of course, be retrieved and printed from the file. 1.18 Copying the Query and Results Once the SQL query is on the query editor screen, you can select the entire query by highlighting it and then right-clicking. Select Copy, and paste it wherever you wish. To copy a portion of the results, highlight the portion that you would like to copy, right-click, and then select Copy. The Results to grid option has an option of Copy with Headers, which copies the results along with the headers. 1.19 Customizing Microsoft® SQL Server® 2008 You can customize some options in SQL Server 2008 by selecting Tools from the main menu and then Options. Once you select Tools and Options, you will see the following tabs: Environment, Text Editor, Query Ex- ecution, Query Results, SQL Server Query Explorer, Designers, and Source Control.
  • 46. 26 CHAPTER 1 Starting Microsoft SQL Server 2008 1.19.1 The Environment Tab The Environment tab contains the General, Fonts and Colors, Key- board, and Help options. Among other options, the General option allows you to change the default start-up window of SQL Server 2008. The Fonts and Colors option allows you to change, among other things, an item’s foreground and background colors. The Keyboard option allows you to change keyboarding options like Shortcuts. 1.19.2 The Text Editor Tab The Text Editor tab allows you to change the default editor and set language and text options. 1.19.3 The Query Execution Tab The Query Execution tab allows you to change the default ROWCOUNT options, TEXTSIZE options, execution time-out length, and other settings. 1.19.4 The Query Results Tab The Query Results tab allows you to change the default type of results, the default location for results to be saved, and other settings. 1.19.5 The SQL Server Query Explorer Tab The SQL Server Query Explorer tab allows you to change table and viewing options and scripting options. 1.19.6 The Designer Tab The Designer tab allows you to change the default table and database designer settings. 1.19.7 The Source Control Tab The Source Control tab specifies the source control plug-in to use with Microsoft SQL Server Management Studio and allows changes to plug-in- specific options.
  • 47. Chapter 1 Exercises 27 SUMMARY In this chapter, we have shown you how to start Microsoft® SQL Server® 2008 and SQL Server 2008’s Management Studio. We have also shown you how to create the Student course database that we will be using throughout the rest of this book. In addition, we have demonstrated how to work with tables, and how to type, parse, execute, and save a simple query. In the process, we have also familiarized you with the main screens and workings of SQL Server 2008’s Management Studio. Toward the end of the chapter, we showed you how to change some of SQL Server 2008’s default settings to suit your needs. Review Questions 1. If you want to see what columns a table is made of and what the sizes of the fields are, what option do you have to look for? 2. What is a query? 3. A SQL query is typed in the . 4. What is the purpose of the model database? 5. What is the purpose of the master database? 6. What is the purpose of the tempdb database? 7. What is the purpose of the USE command? 8. If you delete a table in the database, will the data in the table also be deleted? 9. What is the Parse Query button used for? How does this help you? 10. Tables are created in a in SQL Server 2008. Chapter 1 Exercises The tables available in the Student_course database are shown in Appendix 1. You may want to look at Appendix 1 before starting this section. 1. The Student course database contains the following tables: Student, Department to major, Grade report, Section, Dependent, Course, Prereq, Room, Languages, Plants, and teststu. a. View the table design of each of these tables. To save and print your table design, we suggest that you copy and paste your table design into a word processor where you can save it for later use or print it out. b. View the data of each of these tables. Save your results to file and also print them out.
  • 48. 28 CHAPTER 1 Starting Microsoft SQL Server 2008 2. Write a SQL query to view all the columns and rows in the Student table (Hint: To retrieve all columns, use “SELECT *” in your query; the “*” means “all columns”). a. View the results in grid form and print the results. b. View the results in text form and print the results. c. Save the results to file. d. Save the query.
  • 49. c h a p t e r 2 Beginning SQL Commands in Microsoft SQL Server c h a p t e r 2 Beginning SQL Commands in Microsoft® SQL Server ® Topics covered in this chapter Displaying Data with the SELECT Statement SELECT without the FROM Displaying or Selecting Columns from a Table Displaying or SELECTing One Column from a Table Display or SELECTing More Than One Column from a Table Displaying or SELECTing All Columns of a Table ORDER BY ORDER BY and NULLs Ascending and Descending Order Ordering Within an Order Displaying or SELECTing Rows from a Table Filtering with WHERE The AND Operator The OR Operator The BETWEEN Operator 29
  • 50. 30 CHAPTER 2 Beginning SQL Commands in Microsoft SQL Server Negating the BETWEEN Operator The COUNT Function IS NULL IS NOT NULL The ROWCOUNT Function Using Aliases Column Aliases Table Aliases Table Aliases Used as Table Qualifiers Synonyms Adding Comments to SQL Statements Some Conventions for Writing SQL Statements A Few Notes about Microsoft® SQL Server® 2008 Syntax Summary Review Questions Chapter 2 Exercises In Chapter 1, we introduced you to some of the basics of Microsoft® SQL Server® 2008 and SQL Server 2008’s Management Studio. We provided instructions on creating a database, the Student course database, which we will be using in this chapter and throughout the rest of the book. We also showed you how and where to enter and execute a query. In this chapter, we discuss how to write (build) simple SQL query statements in SQL Server 2008 using the SELECT statement. We examine how to retrieve data from a table by the use of SELECT statements, how to SELECT columns (fields) and rows from tables, how to use the ORDER BY and WHERE clauses, and how to use the AND, OR, and BETWEEN operators. The concepts of COUNT and null values are also introduced. Then, to make writing queries clearer and simpler, we discuss how to use table and column aliases, table qualifiers, and synonyms, and finally we present a convention for writing SQL statements. 2.1 Displaying Data with the SELECT Statement One of the first things that you will usually want to do with a database containing a set of tables is to see what information the tables contain. To display the information from a table using a query, you use a SELECT
  • 51. Another Random Scribd Document with Unrelated Content
  • 52. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem. 1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. 1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions. 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause. Section 2. Information about the Mission of Project Gutenberg™
  • 53. Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life. Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org. Section 3. Information about the Project Gutenberg Literary Archive Foundation The Project Gutenberg Literary Archive Foundation is a non- profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws. The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact
  • 54. Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form accessible by the widest array of equipment including outdated equipment. Many small donations ($1 to $5,000) are particularly important to maintaining tax exempt status with the IRS. The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate. While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate. International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff. Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and
  • 55. credit card donations. To donate, please visit: www.gutenberg.org/donate. Section 5. General Information About Project Gutenberg™ electronic works Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and distributed Project Gutenberg™ eBooks with only a loose network of volunteer support. Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition. Most people start at our website which has the main PG search facility: www.gutenberg.org. This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.
  • 56. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com