BeginningSQL Joes2Pros WebSample
BeginningSQL Joes2Pros WebSample
By Rick A. Morelan
MCDBA, MCTS, MCITP, MCAD, MOE, MCSE, MCSE+I
RickA.Morelan AllRightsReserved2009
ISBN: 1-4392-5317-X EAN: 978-1-4392-5317-5 Rick A. Morelan [email protected]
1
www.Joes2Pros.com
Chapter 1.
Table of Contents
About the Author ................................................................................................ 7 Acknowledgements ............................................................................................. 7 Preface................................................................................................................. 9 Introduction ......................................................................................................... 9 Skills Needed for this Book .............................................................................. 11 About this Book ................................................................................................ 11 How to use this Book and Videos ..................................................................... 13 How to Use the Downloadable Companion Files ............................................. 13 What this Book is Not ....................................................................................... 14
2
www.Joes2Pros.com
Chapter 1. Database Complexity ........................................................................................ 63 Relational Data.................................................................................................. 63 Inner Joins ......................................................................................................... 65 Lab 3.1: Inner Joins........................................................................................... 69 Inner Joins - Points to Ponder ........................................................................... 71 Outer Joins ........................................................................................................ 72 Left Outer Joins............................................................................................. 72 Right Outer Joins .......................................................................................... 73 Full Outer Joins ............................................................................................. 74 Filtering Multi-Table Queries ........................................................................... 75 Filtering with Inner Joins .............................................................................. 76 Filtering with Outer Joins ............................................................................. 77 Filtering with All Types of Joins .................................................................. 77 Lab 3.2: Outer Joins .......................................................................................... 78 Outer Joins - Points to Ponder .......................................................................... 79 Chapter Glossary ............................................................................................... 79 Review Quiz...................................................................................................... 80 Answer Key .................................................................................................. 82 Bug Catcher Game ............................................................................................ 83
3
www.Joes2Pros.com
Chapter 1. Verifying Which Databases Exist ................................................................... 113 Creating User Databases ............................................................................. 116 Lab 5.1: Creating Databases ........................................................................... 118 Creating Databases - Points to Ponder ............................................................ 119 Creating Tables ............................................................................................... 120 Lab 5.2: Creating Tables ................................................................................. 122 Creating Tables - Points to Ponder ................................................................. 124 Chapter Glossary ............................................................................................. 124 Review Quiz.................................................................................................... 125 Answer Key ................................................................................................ 126 Bug Catcher Game .......................................................................................... 126
4
www.Joes2Pros.com
Chapter 1. Importing Data ................................................................................................ 175 Exporting Data ................................................................................................ 179 Lab 7.2: Using BCP ........................................................................................ 181 Using BCP - Points to Ponder ......................................................................... 182 Chapter Glossary ............................................................................................. 182 Review Quiz.................................................................................................... 183 Answer Key ................................................................................................ 185 Bug Catcher Game .......................................................................................... 186
Chapter 10.
5
www.Joes2Pros.com
Chapter 1. Introduction to Security .................................................................................. 228 Securables and Permissions ............................................................................ 228 Creating SQL Logins ...................................................................................... 228 Authentication Modes ..................................................................................... 230 Dropping SQL Logins..................................................................................... 236 Lab 10.1: SQL Logins..................................................................................... 237 Granting Permissions ...................................................................................... 239 Lab 10.2: Granting Permissions ...................................................................... 244 Granting Permissions - Points to Ponder ........................................................ 244 Revoking and Denying Permissions ............................................................... 245 Lab 10.3: Revoking and Denying Permissions ............................................... 250 Denying Permissions - Points to Ponder ......................................................... 251 Chapter Glossary ............................................................................................. 252 Review Quiz.................................................................................................... 252 Answer Key ................................................................................................ 254 Bug Catcher Game .......................................................................................... 254
Chapter 11.
SQL Language Statement Types .................................................................... 256 Other SQL Language Statements.................................................................... 256
6
www.Joes2Pros.com
Chapter 1.
Acknowledgements
As a book with a supporting web site, illustrations, media content and software scripts, it takes more than the usual author, illustrator and editor to put everything together into a great learning experience. Since my publisher has the more traditional contributor list available, Id like to recognize the core team members: Editor: Peter D. Kendall, Jessica Brown, Doug Fritz Technical Editor: Peter Bako (MCTS), Jong Jin Lee (MCTS) Cover Illustration: Jungim Jang Technical Review: Hugo Rossini, Ed Hartmann Software Design Testing: Michael Baker (MCTS), Eugene Kim (MCTS) Content Review: Rhonda Chesley (MCTS), Allan Fridson User Acceptance Testing: Cyrus Despres, Anthony L. Walker Thank you to all the teachers at Catapult Software Training Institute in the mid1990s. What a great start to open my eyes. It landed me my first job at Microsoft by August of that year. A giant second wind came from Koenig-Solutions, which gives twice the training and attention for half the price of most other schools. Mr. Rohit Aggarwal is the visionary founder of this company based in New Delhi, India. Rohits business model sits students down one-on-one with experts. Each expert dedicates weeks to help each new IT student succeed. The numerous twelve-hour flights I took to India to attend those classes were pivotal to my success. Whenever a new generation of software was released, I got years ahead of the learning curve by spending one or two months at Koenig.
7
www.Joes2Pros.com
Chapter 1. Dr. James D. McCaffrey at Volt Technical Resources in Bellevue, Wash., taught me how to improve my own learning by teaching others. Youll frequently see me in his classroom because he makes learning fun. McCaffreys unique style boosts the self-confidence of his students, and his tutelage has been essential to my own professional development. His philosophy inspires the Joes 2 Pros curriculum. Hades Meza, one of my most technically advanced students, tells aspiring SQL professionals that you need two things to clinch a job: First, you need to know the SQL language and have SQL Server development skills. Then, you need to be able to pass a SQL Server job interview. Meza has given and has been subjected to dozens of SQL technical interviews. His hiring question insights are woven into the Points to Ponder labs and quizzes in this book. Numerous colleagues such as Peter Bako, Jessica Brown, Anne Hunt and Peter D. Kendall contributed their skills and experience to make this book possible. Peter Bako is a hands-on master of computer hardware, software and programming languages. Whenever a challenge arises he either has the answers, he knows how to quickly get the answers, or invents a working solution on-the-fly. Jessica Brown and Anne Hunt have very sharp eyes for details and contributed greatly to the smooth progress of the book. Peter D. Kendall, a professional journalist whose expertise earned my admiration right away, combined the conciseness and punch of AP style with his own SQL knowledge to bring cohesion to this project. What better technical editor could there be than a former newspaper editor who is now a certified SQL server MCTS. The first student to read the entire book and provide review suggestions was Ernie Li. Ernie used his daily bus commute to read the entire book when it was a mere jumble of papers in a 3-ring binder. If you like the big readable figures, then give him some credit. He suggested the figures be vivid, easy to read, and that they zoom in to draw your attention to specific points. Ernie gives the illustrations a big thumbs-up as we go to print, and Ill always be grateful for Ernies diligence, thoroughness, and his eagerness to learn and apply new skills. Finally, a special thank you goes to Ed Hartmann who has taught so many students at Bellevue College over the years. Ed's experienced and careful eye caught a few 11th hour items which really raised the quality standard of this book.
8
www.Joes2Pros.com
Chapter 1.
Preface
How do you build a raging fire of learning from a single spark of curiosity? If you take that little spark and add some paper, a few twigs and a stick, eventually even the largest log can be tossed on to the raging fire. You, too, can evolve from flame to firestorm, from Joe to Pro, when you take the steps outlined in this book. Regardless of your skill level, this is the ideal way to learn. Viewing a large and unruly database that someone else wrote is like throwing a huge log directly onto a match. What if that large database, which included complex relations, started off as a smaller database with just three tables and 12 employees? You will learn how to build that large database one chapter at a time over the course of studying these Joes 2 Pros books. When you are a part of building something, you comprehend each new level of complexity that is added. Afterward, youre able to stand back and say, I built that! Your Joes 2 Pros journey will soon make databases appear fun and familiar.
Introduction
Does the following story sound familiar to you? The first SQL book I bought left me confused and demoralized at chapter one. Enrolling in my first class totally overwhelmed me and left me nearly hopeless and with only a partial tuition refund. Progress was expensive and slow. Countless times I was tempted to give up. After years of trial and error, I finally got into my groove. While grinding away at my own work with SQL, those key ah-ha moments and insights eventually came. What took me over five years of intense study is now a high tide that lifts my students to the same level in just a few months. Each lesson and chapter builds sequentially. The labs have been created and delivered by me over several years of teaching SQL. If a lab offered one of my classrooms an exciting ah-ha experience with students leaning forward on every word and demo, its a keeper. However, when a lab caused more of a trance or tilted squint, it was discarded or revised with a better approach. The labs in this book are the end result, and each one consistently elicits ah-ha moments in my classes. This book follows what students told me worked for them and launched their careers. This curriculum has helped many people achieve their career goals. If you
9
www.Joes2Pros.com
Chapter 1. would like to gain the confidence that comes with really knowing how to get things done, this book is your ticket. This book offers the following ways to help: Most learning for the money: What if you could get more from this book than the average $1,800 class? Perhaps there is even more material here proven teaching tools presented by someone whose goal is for you to succeed and achieve a high level of SQL knowledge and proficiency. More importantly, you can learn SQL with demos and practice. When you finish this book, you will be reading and writing in SQL with ease. This book can easily give you more than a typical 18-hour class costing $1,800. Truly getting it: Is there a better way to learn SQL than a giant book of concepts with only a few examples? You bet there is, and youre reading it. Just wait until you finish the Points to Ponder section of each chapter. It exists in written and video format to bring life and action to concepts. Points-to-Ponder is a wrap-up of each chapter, like getting 10 pages of lengthy reading into one. To see these come to life, read them while watching the downloadable videos. This is a concise way to finalize the new points you have just used. Downloadable files bring text to life: Answer keys, quiz games and setup scripts will prepare your SQL Server for the practices that will hone your skills. The files can be found at www.Joes2Pros.com. Bug Catcher game reviews: After you have run the right code several times, you are ready to write code and help others do the same by spotting errors in code samples. Each chapters interactive Bug Catcher section highlights common mistakes people make and improves your code literacy. In the classroom setting, this segment is a fun chapter wrap-up game with a wireless buzzer system. Try this game at home for yourself. This book is an essential tool. When used correctly, you can determine how far and fast you can go. It has been polished and tuned for your use and benefit. In fact, this is the book I really wished was in my possession years ago when I was learning about SQL. What took me years of struggle to learn can now be yours in only months in the form of efficient, enjoyable and rewarding study.
10
www.Joes2Pros.com
Chapter 1.
11
www.Joes2Pros.com
Chapter 1. that page count is a selling point for publishers. People think they are getting a bargain when a book swells to 700 pages. Its easy to boost the page count without adding content. Wide margins that go in an inch or more from every edge and giant indexes can bloat the size of a 300 page book to 500 pages or more. Other than having a page at the beginning and ending of each chapter to take notes, you will find each page chock full of the visuals and a minimalist narrative geared toward your rapid learning. Maybe the publishers are right about hooking the consumer with page count and padding. People buy on page count and read on content, but how rarely it is that bad, bloated books returned! Perhaps readers are now ready to get the most from their investment. Trim off the fat and get what you deserve for less. When the world is ready, it will reflect in this books success. There are other ways to deliver good teaching without overdosing you on wordy ink. How many words would it take to describe your favorite shirt? Would you rather write them all out or show someone with pictures and videos? Every point made in Joes 2 Pros is demonstrated with life-like examples using real databases, thus the downloadable files are essential tools in your SQL learning. The instructional videos will further enhance your learning experience. There was a time when the term boot camp meant something admirable. Too many programs today prey on students dreams while delivering little in return. These incentives rule stronger than ever in the IT training business model. A worst-case example was a school where I briefly taught. It charged students the highest tuition rate Ive ever encountered while paying instructors the least amount, yet spent far more on advertising in the form of radio spots to lure unsuspecting students seeking to gain IT skills. That school also has the lowest rate of students successfully completing the program than any I have encountered. Beginning SQL Joes 2 Pros was written to change this trend. Most of the exercises in this book are designed around proper database practices in the workplace. The workplace also offers common challenges and process changes over time. For example, it is good practice to use numeric data for IDs. If you have ever seen a Canadian postal code (zip code), you see the need for character data in relational information. You will occasionally see an off-thebeaten-path strategy demonstrated so you know how to approach a topic in a job interview or workplace assignment.
12
www.Joes2Pros.com
Chapter 1. To put it simply, there is a recipe for success. You can choose your own ingredients. Just learn the lesson, do the lab, view Points to Ponder, and play the review game at the end of each chapter.
13
www.Joes2Pros.com
Chapter 1. supporting files are available with a free download from www.Joes2Pros.com. The breakdown of the offerings from these supporting files is listed below: Training videos: To get you started, the first three chapters are in video format for free downloading. Videos show labs, demonstrate concepts, and review Points to Ponder along with tips from the appendix. Ranging from 3-15 minutes in length, they use special effects to highlight key points. You can go at your own pace and pause or replay within lessons as needed. To make knowing where to start even easier, the videos were named alphabetically. You dont even need to refer to the book to know what order they can be viewed. The first video is called BookSetupLabSteps.wmv. The second is called Chapter1AboutDatabases.wmv and the third is Chapter1DatabaseGeekSpeak.wmv. Answer keys: The downloadable files also include an answer key. All exercise lab coding answers are available for peeking if you get really stuck. Resource files: If you are asked to import a file into SQL, you will need that resource file. Located in the resources sub-folder from the download site are your practice lab resource files. These files hold the few non-SQL script files needed for some labs. Lab setup files: SQL Server is a database engine and we need to practice on a database. The Joes 2 Pros Practice Company database is a fictitious travel booking company that has been shortened to the database name of JProCo. The scripts to set up the JProCo database can be found here. Chapter review files: Ready to take your new skills out for a test drive? We have the ever popular Bug Catcher game located here.
14
www.Joes2Pros.com
Chapter 1. Introduction to Databases This is not a memorization book. Rather, this is a skills book to make part of preparing for the MCTS 70-433 certification test a familiarization process. This book prepares you to apply what you have learned to answer SQL questions in the job setting. The highest hopes are that your progress and level of SQL knowledge will soon have business managers seeking your expertise to provide the reporting and information vital to their decision making. Its a good feeling to achieve and to help others at the same time. Many students commented that the training method used in Joes 2 Pros was what finally helped them achieve their goal of certification. When you go through the Joes 2 Pros book series and really know this material, you deserve a fair shot at SQL certification. Use only authentic testing engines drawing on your skill. Show you know it for real. At the time of this writing, MeasureUp at http://www.measureup.com provides a good test preparation simulator. The companys test pass guarantee makes it a very appealing option.
15
www.Joes2Pros.com
Structured Query Language (SQL) is the most used database language across the world. SQL contains words you will recognize as common English words. Often students ask me, Whats the difference between SQL and SQL Server? My reply is simple: If you were going to live and work in Germany, youd be better off if you could speak German. If youre going to SQL Server-land, youd better learn to speak the Structured Query Language or SQL. In other words, SQL Server is the name of the environment. SQL is the programming language that is spoken or used in that environment. Before all that, lets examine the hullabaloo about databases.
16
www.Joes2Pros.com
About Databases
If someone came up to you claiming to have a database and hands you a shoebox full of receipts, you should agree with them. A database is a collection of related information. A checkbook is a database. An address book is a database. A telephone book is a database. A family tree is a database. A report card is a database. A diary is a database.
17
www.Joes2Pros.com
A Simple Database
By looking at the shopping list on this page (Figure 1.1) you can tell how many items you want to have in your bag when you leave the store. What is the cheapest item? What is the most expensive one? What does the third item cost? The SQL language uses the pattern recognition, filtering, grouping and calculations you used to answer these questions. The difference is that humans can only query short lists. SQL lets you query trillions of records in related lists. SQL Server returns answers as result sets in mere nanoseconds. If you can answer questions, you can answer SQL queries.
Figure 1.1 A flat database example.
There are seven items on this shopping list. The most expensive item is eggs. The cheapest item is chips. Item 3 costs 99 cents. Its listed as bread. The item on the list that costs one dollar is named milk. Computer languages are literal and numerical. Imagine that you have an appetite and you ask a computer, Whats a good snack? The computer might answer, 5. People would interpret the language and simply say, Chips. From the short list in Figure 1.1, we have seven rows of information. There are three columns. The columns in this figure are not named but the first column lists the item number and could be named ItemNumber. The item Description column follows. Finally, we have a column we would logically name Price. Part of what you must know is how to translate SQL Geek Speak into plain English. You must learn to translate business storing and reporting goals into SQL statements.
18
www.Joes2Pros.com
In Geek a collection of rows and columns of data is called a table. Figure 1.2 is a screen capture of a table from SQL Server. ShoppingList, the name of our table, is easier to read than the list written by hand on a napkin in Figure 1.1. This table has only seven rows. Calling them rows is just fine in Geek, but a few hardcore SQL folks might call them records. If you have seven rows you also have seven records. The correct word for a column in Geek gives you two choices. You can actually choose between column and field. Here, you see three columns or three fields. Each record in our table has an ItemNumber, a Description and a Price. Each record has three fields. In Geek we say, This table is populated with seven records. Since we do not know the values that might be contained in the next record or eighth record, this is an unknown. Each of the three cells in this potential record contains what are called NULL values. NULL does not mean zero. NULL means we do not know the value. Maybe its going to be sugar at $1.75 or gum at $1.10. For now, just think of NULL as unknown or not specified, but anything is possible later. NULLS will be covered more deeply later in this book. After you have records in a table, you can delete some or all of them. If you deleted one record in the shopping list table, we would have six records remaining. If you deleted all of your records, you have an unpopulated table.
19
www.Joes2Pros.com
Once again, the ShoppingList table has three fields. The first field name in this table is ItemNumber. The second field name is Description. The third field name is Price. Oftentimes the first field is numeric and helps us prevent duplicates. For example, we dont want to have two items named number 4. A business might have two employees named David, but each would have a different employee number. The fields offer you more than just a name label atop your data. You can see we have integer data for the ID, alphabetical data for the description, and decimals for the price field (Figure 1.2). It seems clear what type of data is acceptable for each field of any given record. In SQL Server, database fields are constrained so that they accept only a specified data type. The way this table is set up, if you accidently typed in sugar in the price field for the new records, SQL will not accept the entry. Fields are protected or constrained using data types. You can enter different numbers for Price like $1.95 or $22.50 so long as they match the data type accepted by that field. If you look at where a field and record meet, you get a single value. A value sits inside what looks like a spreadsheet cell and acts similarly. In a table with seven rows and three fields, you get 21 values. When you turn your data into viewable information it is often a grid just like you see in Figure 1.2. We dont call the resulting information a grid, but a record set or result set.
20
www.Joes2Pros.com
The true power in the RDBMS is when you want to tabulate the weekend gross of the latest weekend action movie across the nation. Do you want to ship all the ticket stubs from the box offices across the country to a central accounting desk and count by piles? The movie industry uses an RDBMS so that by Monday morning it instantly knows the weekend gross. That is the true power of turning data into information.
21
www.Joes2Pros.com
Chapter 1. Introduction to Databases often hear people tell you to open SQL Server. Actually, you are opening Management Studio to a SQL service that has already been running. On your SQL Server machine it is likely that the SQL Server service is one of many Windows services. Although this book only briefly mentions services, we thought you might want to see know how to view the invisible services that are running. If you right-click the My Computer icon and select Manage you will see the computer management console. Select Services on the left and view the list in the right pane (Figure 1.3).
Figure 1.3 Your services can be viewed from your Computer Management console.
You can start or restart the SQL Server service without rebooting your computer. Simply choose the service and get a context menu as seen in Figure 1.4. Your service is up and running by selecting Start or Restart. You can only use SQL Server and all of its tools if the SQL Server service is running.
Figure 1.4 Restarting the SQL Server service is as simple as clicking a mouse.
22
www.Joes2Pros.com
Chapter Glossary
Database: A collection of objects to store and retrieve data. Datatype: An attribute of a field that tells SQL Server what kind of data it may accept. Examples include integers, dates and characters. Field: A column in a database table. Information: The data and calculation you choose to view from a database, usually for business purposes. Management Studio: The user interface to talk with SQL Server services. Populated: A term used to describe a table that contains data. Query: A question you ask to get information from data in a database. RDBMS: Relational Database Management System is a tool that allows for safe storage of data and quick retrieval of important business information. Record: A row of data in a table. Record set: The set of data returned as an answer to a query. Result set: Another term for record set. Service: A process, much like an application, that runs in the background of your system. SQL: Structured Query Language. T-SQL: Transact Structured Query Language is the computer programming language based on the SQL standard and used by Microsoft SQL Server to create databases, populate tables and retrieve data.
23
www.Joes2Pros.com
As you now know, data is what you store. By using the SELECT command you are choosing which stored data to retrieve and view as information. In case you are an intermediate level student and simply skimmed the first chapter, here is a one sentence recap: Data is what you have stored and information is what you choose to show. Its information that you want to present. For example, your manager asks you to send her a report of books sold last week. If you viewed the raw data in the companys massive sales database, you would see an enormous amount of detail (such as title, author, price, ISBN, language, weight, quantity remaining in inventory, etc.) for every book sold. However, what your manager wants to see is key information regarding last weeks sale, such as the total amount of sales expressed in US dollars, the total number of books, a comparison of last weeks total sales versus the prior week, and the top 10 titles sold. The way you retrieve data to get what your manager wants is to write a query starting with the word SELECT. This chapter will show you the core of the most commonly used keywords to retrieve data from your RDBMS known as SQL Server.
READER NOTE: Is assumed at this point you have SQL installed on your computer. Please run the script Chapter2.0SetupAll.sql in order to follow along with the examples in the first section of this chapter. The setup scripts for this book are posted at Joes2Pros.com.If you need help running the script please download and view the videoBookSetupLabSteps.wmv video from the Joes2Pros web site.
24
www.Joes2Pros.com
Database Context
If you were to ask your best friend for their age you might get a different result than if you asked your child the same question. How many employees work at your company? could be a query. If you were working on a database for a pet store and looked for a list of employees, your results would differ greatly from the same query on the database of a giant global corporation. If you create the perfect query in the wrong database, it may run without error messages. When you query the right database, you get the information you need. Set your database context before you run your query. In my career, every single server Ive encountered has had many databases. You will find the same to be true and perhaps already have. The Object Explorer inside Management Studio talks with the SQL Server service and finds all your databases. Databases appear as yellow cylinders inside the Object Explorer window. In Figure 2.1 we see three databases named dbBasics, dbTester and JProCo.
The data inside these three databases are different. When you look for information you usually write a query on only one database at a time. Database context refers to which database you are running the current query against. Always set your database context before you run your query. Notice the left side of Figure 2.2 shows the Object Explorer. The right side of the figure is your query window. The query window can have only one database context at a time. If you look in the toolbar above both windows, you see it is set to JProCo. You can change this connection by clicking the dropdown control and selecting the desired database from the list.
25
www.Joes2Pros.com
Figure 2.2 Full view of Management Studio with the database context set to the JProCo database.
There is always a risk that you will run code using the wrong database context. To avoid that situation, we simply change the database context to the correct database (Figure 2.2). You can also do this with a SQL statement. If we were in the JProCo database and wanted to change to the dbBasics database, we would type the USE command below:
USE dbBasics GO
Running this SQL statement is the preferred way to modify database context. Alternatively, you can use the dropdown list which works just as well. However, the code method is best when writing code you plan to reuse, particularly when working on a team that shares SQL scripts. When sharing your code, you want others to be in the correct database when it runs. Putting the USE statement in the top window changes the database context. Hit the F5 key or click the Execute button above the query pane to run this code (Figure 2.3).
26
www.Joes2Pros.com
Figure 2.3 Changing context to dbBasics with the USE statement and then executing the code.
The SQL code tells the service to use the dbBasics database. The word GO means the statement above it must finish before going any further. So, GO really means stop, finish and then go. This is a safety feature since the next statement is dependent on the content already being set to dbBasics. If youre not in dbBasics, you cant query dbBasics. The GO makes sure the statement above it is completed in a batch before going further. Modern systems are capable of running many lines at the same time. GO means the statement above it must completely finish before proceeding to the next line.
27
www.Joes2Pros.com
Chapter 2. Basic Queries The word SELECT means you want to see all information displayed. The asterisk (*) is handy if you dont know the names of the fields, but want all of them to be displayed. The keyword FROM chooses the table youre querying for the information. Run your query by hitting the F5 key or the Execute button (Figure 2.4).
Figure 2.4 A query for all records and all fields from the ShoppingList table.
USE dbBasics GO
28
www.Joes2Pros.com
Chapter 2. Basic Queries Now is a good time to point out you can put words on your query screen that have nothing to do with SQL. You could write non-SQL words and notes like I wrote this query today above your select statement. If you do, you must tell SQL to ignore this text since its not intended to be code. In fact, it should be nonexecuting code known as comments. To make comments, you need to begin the line with two hyphens. Change your context back to JProCo and use this example:
29
www.Joes2Pros.com
Figure 2.5 A table with a space in the name will not run without delimiters.
You can put square brackets around any table. In fact, automatically generated code always creates these delimiters. The only time you need to do this is when table names are not obvious to SQL Server. Once you delimit the name of the Shopping List table with square brackets, the query runs without error (Figure 2.6). We get seven records in our result set.
Figure 2.6 Delimiting a table whose name includes a space allows the query to run.
30
www.Joes2Pros.com
Chapter 2. Basic Queries Delimiting table names helps us in another way, too. It would be a bad idea to name your tables after known keywords. For example, a table named From would look like this:
Figure 2.7 Delimiters tell SQL Server Grant is a table name, not the keyword GRANT.
31
www.Joes2Pros.com
Chapter 2. Basic Queries Square brackets will work on all table identifiers. You can put square brackets around the [Employee] table if you want. In reality, you only really need them occasionally. This also works for fields. For example, the Location table has a field named state. STATE is also a keyword (beginning in SQL Servers 2008 version). Theres more on selecting fields later in this chapter.
Exact Matching
There is a big difference between selecting everything and being selective. If you question the business importance of databases systems, ask yourself what a highly profitable search engine company does. The world has billions of web sites and you want your search narrowed down to just a few sites of interest to you. Without providing any new sites themselves, the search engine companies make the internet more selective than you need, and you are presented with a plethora of links, so you visit them. This drives the search engines advertising business. Trying to obtain information by looking at all records in a table is about as useful as trying to look at all web sites on the internet to find what you want. Instead, the preferred way is to add criteria to your query. With criteria you can deliver the information that gives people what they want. All queries must have the SELECT and FROM keyword clauses to be valid. We do have other choices available at our fingertips, such as the WHERE clause, which is the most common optional keyword. When we query the entire [ShoppingList] table we have two items which cost $1.25. Its easy to spot two records out of seven. Two records from a million would be like looking for a needle in a haystack. So, lets tunnel through that haystack with the WHERE clause.
32
www.Joes2Pros.com
Chapter 2. Basic Queries We want to limit our result set based on the Price field being exactly $1.25. We add this specific criteria immediately after the WHERE clause (Figure 2.8).
Figure 2.8 The WHERE clause limits the number of records in your result set.
The WHERE clause is perfect for filtering your information. The amount of data in the [ShoppingList] table is still seven records. The number of records in our result set is now just two. The WHERE clause can filter any type of data. If we wanted to see all employees named David in the JProCo database we can use the WHERE clause. When using character data we must use a single quotation mark.
33
www.Joes2Pros.com
Chapter 2. Basic Queries The query seen in Figure 2.9 uses a WHERE clause to filter on the Firstname field to look for all employees with the first name of David. We still have twelve records of data stored in the Employee table. The WHERE clause shows us just the records in our result set that we asked to view. WHERE expects a logical statement to evaluate each record. The logical statement Firstname = David is called a predicate. By predicating on Firstname, you filter your result set.
Figure 2.9 Using the WHERE clause shows employees with the first name of David.
Of the twelve employees, we have 10 who are not named David. To see all the records that dont have David as a Firstname, we use this query:
34
www.Joes2Pros.com
Chapter 2. Basic Queries of SQL, you may be used to the < > operator as meaning Not Equals. That is still true today with the code you see below:
35
www.Joes2Pros.com
Figure 2.10 Your query of the CurrentProducts table should produce 480 records.
Skill Check 2: In the JProCo database, write a query that shows all records and all fields from the [Grant] table. Your result set should show 10 records. Skill Check 3: In the JProCo database, write a query that shows all records from the [Grant] table that have an amount of $21,000. Your result set should show two records.
36
www.Joes2Pros.com
Skill Check 4: Write a query that displays a result set of all records from the Location table that are in the state of WA. When you are done your screen should resemble Figure 2.11.
Figure 2.11 Your query should produce two Washington (WA) records.
Answer Code: The SQL code to this lab can be found from the downloadable files named Lab2.1_SingleTableQueries.sql.
READER NOTE: At this point you can read pages 38-50 to help prepare you for Lab 2.2. on using criteria. Alternately the Lab2.2_UsingCriteria.wmv video will also cover the lab as well as summarize the information contained from pages 38-50. If you want to do the Read-View-Do approach then start reading the next page until you get to the skill checks. If you want to use the View-Read-Do approach then start watching the Lab2.2_UsingCriteria.wmv until you get to the skill checks.
37
www.Joes2Pros.com
Pattern Matching
What do the names Brian and Bo have in common? They both start with the letter B. Yes, there are other similarities, but lets go with the most obvious. If you use the = operator with the letter B, it wouldnt find either name. It would look for the name B, which is only one letter long. This would give you an empty result set. We need to combine a more approximate operator with something called a wildcard. The operator that allows you to do approximate predicates is LIKE. The LIKE operator allows you to do special relative searches to filter your result set. To find everyone whose first name starts with the letter B, you need B to be the first letter. After the letter B you can have any number of characters. Using B% in single quotes after the LIKE operator gets all names starting with the letter B (Figure 2.12). This is a good time to point out that SQL does not care if your name is Barry or barry. SQL is not case sensitive unless you go out of your way to change its default setting.
38
www.Joes2Pros.com
The % wildcard symbol represents any number of characters of any length. Lets find all first names that end in the letter A. By using the percentage % symbol with the letter A, you achieve this goal using the code sample below:
Figure 2.13 Using the underscore wildcard to find exactly one character.
39
www.Joes2Pros.com
Querying Ranges
If you want to find all Firstname values starting with the letters A or B you can use two predicates in your WHERE clause. You need to separate them with the OR operator. In Figure 2.14 you find records where Firstname starts with A or B.
Figure 2.14 Using the OR operator to find Firstname values starting with letters A or B.
Finding names beginning with A or B is easy. This works well until you want a range of A-K as in the example below:
SELECT * FROM Employee WHERE Firstname Like 'A%' OR Firstname Like 'B%' OR Firstname Like 'C%' OR Firstname Like 'D%' OR Firstname Like 'E%' OR Firstname Like 'F%' OR Firstname Like 'G%' OR Firstname Like 'H%' OR Firstname Like 'I%' OR Firstname Like 'J%' OR Firstname Like 'K%'
40
www.Joes2Pros.com
Chapter 2. Basic Queries The previous query does find Firstname values starting from A-K. However, if you need a range of letters, the LIKE operator has an even better option. Since were looking for the first letter to be within a range, we specify that range in square brackets. The wildcard after the brackets allows any number of characters after the range. Note this range will not work if your LIKE was changed to an equal (=) sign. The following code will not return any records to your result set: --Bad query (it wont error but returns no records)
Figure 2.15 Using square brackets with LIKE to find Firstname values in the range from a-k.
A range of characters can be found using LIKE and the appropriate characters inside square brackets. The wildcard is considered a string pattern and must be enclosed in single quotes. Simply put, its the starting letter followed by a hyphen and then the ending letter of your range (Figure 2.15). Notice you get Alex in your result set. This is because A is considered to be in the [a-k] range. The same logic applies to John. There is a similar trick you can play with number ranges.
41
www.Joes2Pros.com
Chapter 2. Basic Queries If you look at the Grant table, you will notice we get amounts as low as $4,750 and as high as $41,000 for the Amount field (Figure 2.16).
Figure 2.16 All fields and all records from the [Grant] table.
We have multiple grants that are over $20,000 in the Amount field. In the following query we use the greater than operator to find amounts over 20000:
42
www.Joes2Pros.com
Chapter 2. Basic Queries We have multiple grants that are under $20,000 in the Amount field. The following query uses the less than operator to find amounts under 20000:
Figure 2.17 Result sets for greater than vs. greater than or equal to operators.
When someone asks you to pick a number between one and ten, what are valid answers? Zero would be out of range. How about an edge case answer of one? Is one between one and ten? Yes! When you use the word between in everyday life the numbers on the edge are considered inclusive. The same is true with the BETWEEN operator in SQL Server.
43
www.Joes2Pros.com
After the WHERE, you can use the BETWEEN operator with the AND operator to specify two numbers that define your range. When we look for amounts between 21000 and 30000, we get four records in our result set (Figure 2.18).
Notice that two of our results are exactly 21,000. BETWEEN offers you results that are inclusive of the numbers in your predicate.
44
www.Joes2Pros.com
Chapter 2. Basic Queries We have three special characters and no literal percent symbol. Help is on the way again with the square brackets. Take the wildcard you want to use as a literal percentage symbol and surround it with square brackets. You see two grants having a percentage symbol within their names (Figure 2.19). In this example the square brackets give you the literal percentage symbol.
We have a grant called K_Land fund trust with an actual underscore in the name. We have other grants with underscores as well. How do you search for an underscore sign with a wildcard on each side? The ineffective query below gets all records that are at least one character long: --Bad query logic finds all records with one or more characters
45
www.Joes2Pros.com
Chapter 2. Basic Queries You see three grants having underscores in their names (Figure 2.20). In this example the square brackets tell SQL you are looking for a literal underscore character.
What if you want to find grants that have an apostrophe (single quote) in their names such as Normans Outreach? Everything inside single quotes after the LIKE evaluates every record to give you your final result set. The first single quote starts the string and it ends with the second single quote. Everything between the single quotes is part of the search string. Everything before the first single quote and after the second single quote is not part of the search string. The single quote encompasses or delimits the pattern you are searching. A new challenge arises here. The following query produces a syntax error.
--Bad query results in an error. SELECT * FROM [GRANT] WHERE GrantName LIKE '%'%'
46
www.Joes2Pros.com
Chapter 2. Basic Queries The problem lies in the fact that SQL Server assumes the predicate is done after the second single quote. SQL Server sees everything after the second single quote as an error in your SQL code. Your intentions were lost or misunderstood. To forego the special meaning of the single quote, precede it with another single quote (Figure 2.21).
Figure 2.21 Using two single quotes filters your result set for a grant name with an apostrophe.
You now have two records with a single quote in your result set. To view all names without a single quote you would simply change the LIKE to NOT LIKE in the WHERE clause.
47
www.Joes2Pros.com
The Employee table has seven fields (Figure 2.22). A few more fields and you would need to scroll right or left to view all your information.
Figure 2.22 Using the asterisk * after SELECT displays all records and all fields in the table.
Tables can have up to 1024 fields. That is a lot of data to view. If you wanted just some of those fields, you can pick them. Simply itemize the field list after the SELECT clause. To do this you need to know the names of the available fields. By listing the Firstname and LastName fields separated by a comma, we get just two fields in our result set (Figure 2.23).
48
www.Joes2Pros.com
Figure 2.23 Changing your field select list to show just the Firstname and Lastname fields.
Until now, we have been using SELECT * in all of our queries. This displays all available fields in a table. However, we can choose to display only the fields we wish to view by naming them, separated by commas, after the SELECT. You can list one, many or all the fields available from the tables listed in the FROM clause. Of course, its easier to type * than to know and type out all those names separated by commas. Optionally, you can use the two-part name of the field by listing the table identifier and then the field identifier separated by a period. This requires extra typing, which we show you how to avoid in Chapter 4. Using two-part names for fields uses the TableName.FieldName syntax. Employee.FirstName and Employee.LastName (Figure 2.24) gives us the same results as just specifying FirstName and LastName (Figure 2.23).
49
www.Joes2Pros.com
Figure 2.24 Field select list using the two-part naming convention of TableName.FieldName.
Field names can clash with an existing keyword. For example, the Location table has a field named State. You can put the square brackets around the [State] field to tell SQL Server youre referring to the object and not the keyword command. The following example demonstrates a query that gets street, city and state.
50
www.Joes2Pros.com
Figure 2.25 Your query should show 96 records from the CurrentProducts table.
Skill Check 2: Write a query to show all records from the CurrentProducts table of the JProCo database with a retail price more than $1,100.00. When youre done, your result should resemble Figure 2.26.
Figure 2.26 Your Skill Check 2 query should show six records from the CurrentProducts table.
51
www.Joes2Pros.com
Chapter 2. Basic Queries Skill Check 3: Write a query from the CurrentProducts table of the JProCo database with the following specifications: Show only the ProductName, RetailPrice and Category fields. Show the records where the first letter of the product name starts with the letters A to C. When youre done, your screen should resemble Figure 2.27.
Skill Check 4: Write a query from the [Grant] table of the JProCo database with the following specifications: Show all fields. Show the four records that have an amount between 7,500 and 20,000. When youre done, your screen should resemble Figure 2.28.
Figure 2.28 Your query in Skill Check 4 should show four records.
52
www.Joes2Pros.com
Chapter 2. Basic Queries Skill Check 5: Write a query from the [Grant] table of the JProCo database with the following specifications: Show all fields. Show the three records that have an underscore in their grant names. When youre done, your screen should resemble Figure 2.29.
Figure 2.29 Your query in Skill Check 5 should show three records.
Skill Check 6: Write a query from the Employee table of the JProCo database with the following specifications: Show all fields. Show the three employee records having a first name of David or James. When youre done, your screen should resemble Figure 2.30.
Figure 2.303 Your query in Skill Check 6 should show three records.
53
www.Joes2Pros.com
Chapter 2. Basic Queries Skill Check 7: Write a query from the [Grant] table of the JProCo database with the following specifications: Show all fields. Show the two grant records that have the character O as the second letter in the GrantName field. When youre done, your screen should resemble Figure 2.31.
Figure 2.31 Your query in Skill Check 7 should show two records.
Skill Check 8: Write a query from the Employee table of the JProCo database with the following specifications: Show all fields. Show the two employee records with a status equal to Has Tenure. When youre done, your screen should resemble Figure 2.32.
Figure 2.32 Your query in Skill Check 8 should show two records.
54
www.Joes2Pros.com
Chapter 2. Basic Queries Skill Check 9: Imagine you have been asked to create a result set from the JProCo database. You must create a record set showing all grants that were funded by someone with a valid .com email address. To succeed, you will need to use wildcards with the following information: Look for the @ symbol somewhere in the name. The e-mail address name should end in .com Make sure at least one character exists before the @ symbol. Make sure at least one character exists between the @ and the .com Ensure there are no spaces in the GrantName. When youre done, your screen should resemble Figure 2.33.
Answer Code: The SQL code to this lab can be found in the downloadable file named Lab2.2_UsingCriteria.sql.
55
www.Joes2Pros.com
11. 12.
13.
56
www.Joes2Pros.com
Chapter Glossary
Database Context: Refers to which database you are running the current query against. Delimiter: A character which separates one object or entity from another. Keyword: A word built into the SQL language. Clause: A type of keyword used for a query. SELECT is both a clause and a keyword. Operator: Words or symbols used by SQL to make calculations or evaluations. Some commonly used operators are AND, OR, (<), (>) and (=).
Review Quiz
1.) Which SQL clause helps you to limit the number of records you see in a query from a single table? O a. O b. O c. O d. FROM WHERE IF SELECT
2.) Which wildcard usage will help you find all last names starting with R? O a. O b. O c. O d. WHERE LastName = 'R%' WHERE LastName = '%R' WHERE LastName LIKE 'R%' WHERE LastName LIKE '%R'
4.) Which keyword filters or reduces the number of fields in your query? O a. O b. O c. O d. ON WHERE IF SELECT
57
www.Joes2Pros.com
Chapter 2. Basic Queries 5.) What comes right after the SELECT clause? O a. O b. O c. The predicate The list of fields The list of records
6.) What comes right after the FROM clause? O a. O b. O c. O d. O e. The predicate The list of fields The list of records The table or tables The data type
7.) You want to find all first names that start with the letters A-M in your Customer table. Which SQL code would you use? O a. O b. O c. O d. O e. SELECT * FROM Customer WHERE Firstname <= 'm%' SELECT * FROM Customer WHERE Firstname = 'a-m%' SELECT * FROM Customer WHERE Firstname like 'a-m%' SELECT * FROM Customer WHERE Firstname = '[a-m]% ' SELECT * FROM Customer WHERE Firstname like '[a-m]%'
8.) What comes right after the WHERE clause? O a. O b. O c. O d. O e. The predicate The list of fields The list of records The table or tables The data type
58
www.Joes2Pros.com
Chapter 2. Basic Queries 9.) You want to find all scores for contestants who scored in the range of 20-30 points. Which SQL code would you use? O a. O b. O c. O d. SELECT * FROM contestant WHERE score BETWEEN 20 OR 30 SELECT * FROM contestant WHERE score BETWEEN 20 AND 30 SELECT * FROM contestant WHERE score IS BETWEEN 20 AND 30 SELECT * FROM contestant WHERE score MIDDLE RANGE (20,30)
10.) You want to find all first names that have the letter A as the second letter and do not end with the letter Y. Which SQL code would you use? O a. O b. O c. SELECT * FROM Employee WHERE Firstname like '_A% ' AND Firstname NOT LIKE 'Y%' SELECT * FROM Employee WHERE Firstname like '_A% ' AND Firstname NOT LIKE '%Y' SELECT * FROM Employee WHERE Firstname like 'A_% ' AND Firstname NOT LIKE 'Y%'
11.) You work for a commercial certificate authority (CA) to track safe internet business. You have a table named ApprovedWebSites. Some are ftp:// sites and some are http:// sites. You want to find all approved .org sites listed in the URLName field of the ApprovedWebSites table. All URL names will have the :// with at least one character before them. All sites will have at least one character after the :// and before the .org at the end. What code will give you all .org records? O a. O b. O c. O d. SELECT * FROM ApprovedWebSites WHERE URLName like '%://%[.org]' SELECT * FROM ApprovedWebSites WHERE URLName like '_%org' SELECT * FROM ApprovedWebSites WHERE URLName like '%://%.org' SELECT * FROM ApprovedWebSites WHERE URLName like '_%://_%.org'
59
www.Joes2Pros.com
Answer Key
1.) The FROM clause lists the table or tables you are using but does not limit its records so (a) is incorrect. The IF keyword is used for finding running conditions and not inside of queries (see chapter 5), therefore (c) is also incorrect. SELECT limits the number of fields (not records) returned so its not (d). The WHERE clause creates criteria and limits the records in your result set so (b) is the right answer. 2.) The = sign does not use wildcards so both (a) and (b) are incorrect. Putting the % before the R would give you a name ending in R, so (d) is also incorrect. R% means a string where the first character is R followed by any number of characters (even zero) so (c) would be the correct answer. 3.) Because every query starts with SELECT, it is not an optional word; therefore (a) is incorrect. Given that all queries start with SELECT, it must be required; making (b) the correct answer. 4.) ON is used to define the criteria on which to join two tables, so (a) is incorrect. The WHERE clause creates criteria that limits the records in your result set so (b) is also wrong. The IF keyword is used for finding running conditions and not inside of queries (see chapter 5), therefore (c) is also incorrect. Since you list the specific fields you would like displayed in your result immediately following the SELECT keyword, it is limiting the number of fields returned so (d) is the correct answer here. 5.) The predicate is the equation following the WHERE keyword which defines criteria for filtering records so (a) is wrong. The list of records makes up our result set which is usually displayed on screen thus making (c) wrong too. The correct answer is (b) since the SELECT keyword filters the number of fields. 6.) The predicate is the equation following the WHERE keyword which defines criteria for filtering records so (a) is wrong. The SELECT keyword is followed by The list of fields which makes (b) wrong too. The list of records makes up our result set which is usually displayed on screen thus making (c) wrong too. The data type is used when defining fields while creating tables so (e) is also incorrect. FROM lists the table or tables you are using making (d) the correct answer. 7.) Wildcards (%) only work with the LIKE keyword so (a), (b) and (d) are all incorrect. LIKE a-m% would only match strings where the first three characters are a-m so (c) is also wrong. The correct answer is (e) because the predicate uses the LIKE keyword and ends in %, meaning zero or more characters following the first character, which has its range defined correctly with [a-m].
60
www.Joes2Pros.com
Chapter 2. Basic Queries 8.) The list of fields follows the SELECT keyword so (b) is incorrect. The list of records makes up our result set making (c) wrong too. The table or tables follows the FROM clause to determine which tables to look in so (d) is also incorrect. The data type is used when defining fields while creating tables so (e) is also incorrect. The predicate is the equation immediately following the WHERE keyword which defines criteria for filtering records so (a) is correct. 9.) BETWEEN uses the AND operator so (a) is incorrect because it used the OR operator. The IS operator is not used with the BETWEEN operator so (c) is also incorrect. There is no such operator as MIDDLE RANGE so (d) is wrong too. The BETWEEN operator requires the AND operator but doesnt not need the IS operator so (b) is correct. 10.) When pattern matching, the use of NOT LIKE Y% only ensures that the first character in the string is not Y it does not check to see what the string ends in so (a) and (c) are both wrong. The use of LIKE _A% will match strings with any character in the first position followed by A followed by zero or more characters; the use of NOT LIKE %Y ensures that the last character in the string is not Y so (b) is correct. 11.) The wildcard % can match zero characters so (a) is wrong because it would match a string starting with ://. The pattern we need to match must include :// and (b) doesnt include this so it is wrong too. The wildcard % can match zero characters so (c) is wrong because it would also match a string starting with ://. The two wildcards _ and % used side by side ensure that a pattern contains at least one character immediately followed by zero or more characters; therefore (d) is the correct answer.
61
www.Joes2Pros.com
Have you ever had to look something up? Maybe you had a persons name, but not their phone number. When you have part of the information, but you need more related information, you are in effect joining data. When you join data you are putting the information into one viewable location. The data may even physically reside in a separate area. For example, the phone number is still in the phone book even after you write it down on your memo pad. Joining data leaves the original data where it started, but shows you the information all together as one consolidated report. This chapter explores how to select data from two related tables into one result set. It is common to use two or more tables in a single query. No matter how many tables are in your query, it appears as one result set. Joining tables is one of the most common ways to turn separated data into consolidated information for reports. This chapter will show you how to discern the relationships between tables and query them into one report.
READER NOTE: Please run the script Chapter3.0SetupAll.sql in order to follow along with the examples in the first section of this chapter. The setup scripts for this book are posted at Joes2Pros.com.
62
www.Joes2Pros.com
Database Complexity
There are two types of database complexity. The first type is a flat file database. It is a single list that does not relate to any other list. A flat file database cannot go beyond a single table of data. The second type is called a relational database. If you had a list of students at school and wanted to keep track of their parents and legal guardians, you might add a second list. These lists relate to one another. This allows the school to look up the students parental information. Tables that relate to one another and reside on one managing system are part of a relational database. As you may recall from the Geek Speak chapter, lists are really called tables. SQL Server thrives by allowing you to query one table or look at a result set that may have relationships between several tables.
Relational Data
Have you ever been given a vague answer to a question? Lets say you asked someone where they worked. You are looking for perhaps a city name or address and they tell you, I work at headquarters. Its an accurate answer, but not the detailed answer you wanted to know. After detecting a slight New England accent from James Newton, you look him up in the Employee table and see that he works at LocationID 2. In what city or state is this mysterious LocationID 2 located? A quick query to the Location table shows us the following data (Figure 3.1).
63
www.Joes2Pros.com
Chapter 3. Viewing Combined Information Now, each time you see an employee listed for LocationID 2 you know his work place street, city and state. Why not just store city, state, and street information all in the Employee table? In fact why not put all of your data in on giant table so you only have one place to go and get your information? That is a common interview question about database design. Lets give you several reasons for your interviewing arsenal. One reason is this saves us lots of space by not replicating all three data items for each employee. Another reason for having location fields only in the Location table is that it would save us time as well. What would happen if LocationID 2 moved from Boston to a new building in nearby Cambridge? You would have to update every street, city and state for every employee. Leaving the LocationID field only in the Location table means all employees with LocationID 2 map to an update you make just once. So, how do we find an employees address if the information is spread between two tables? Each table has the LocationID field. Stated in a two-part identifier (from Chapter 2), we can say that the Employee.LocationID field corresponds to the Location.LocationID field. Refer to Figure 3.2 for a look at Alex Adams and Barry Brown. Both these employees work in LocationID 1. If you were new and only had access to the Employee table, you would not have enough detailed information to send a parcel to Alex Adams. What if we put two tables next to one another on our screen? By physically drawing a line from the Employee.LocationID field to the Location.LocationID field we can get more location details for each employee. LocationID 1 is located at 111 First St. in Seattle, WA.
Figure 3.2 The Employee and Location tables are correlated on the LocationID field.
64
www.Joes2Pros.com
Chapter 3. Viewing Combined Information What about a global company with locations in all 50 states and over 100 different countries? We will have many records in our Location table and probably will not be able to look at both tables very efficiently on one screen. How can we effectively see information in two different tables? Our ultimate goal is to show the Employee and Location information in one result set (Figure 3.3). Since we have not shown you the code on how to do this, we hidden that part of the figure so you can just see what the goal of the upcoming example is.
Inner Joins
Each query has only one result set and allows only one FROM clause. How can you put two tables in one FROM clause? You can put up to 256 tables in one FROM clause if you use joins. The most common type of join is called the inner join. The inner join allows you to join multiple tables in one query, but it requires a specific condition in order to do its work. You must ensure that the join statement has two tables with at least one common or overlapping field. We already know the Employee and Location tables share a common LocationID field. The relationship is between Employee.LocationID and Location.LocationID, so just tell SQL Server that the join is on this field and voila! You will combine two tables into one result set.
65
www.Joes2Pros.com
Figure 3.4 The inner join connects two or more tables in the same FROM clause.
Every time a value is found in Employee.LocationID, the inner join searches for the matching record in the Location.LocationID field. If a match is found, data from both tables are displayed as a single record. Both tables will show all their fields if we type SELECT * at the beginning of our query. In looking at the Grant table we can see [email protected] was the largest amount at $41,000 (Figure 3.5).
66
www.Joes2Pros.com
Chapter 3. Viewing Combined Information The employee who made that procurement was EmpID 10. What if we wanted to find more information about this employee? Is this employee a man or woman? When was this employee hired? To answer detailed questions about this employee, we need to go beyond the Grant table. For visual purposes, lets put these two tables next to one another. We can see that the EmpID field correlates data between these two tables. Grant.EmpID equates to Employee.EmpID. If we look at EmpID 10 on both tables, we can see Terry OHaire is the employee who found the $41,000 grant (Figure 3.6).
Figure 3.6 The Grant table relates to the Employee table on Grant.EmpID to Employee.EmpID.
Again, placing these two small tables side by side and analyzing them can work, but its time-consuming and not very efficient, especially if we have two very large tables. Instead, we can use SQL Server to put both tables into one result set. Putting information into one report is of great value to businesses. The tables in Figure 3.6 share the common field of EmpID. Knowing this is a key step. To put all these records into one result set, you need both tables in the FROM clause. The joins require field(s) that correspond to both tables. The ON clause after the INNER JOIN shows this relationship. If you looked closely at Figures 3.6 and 3.7 you may see a reason for caution. There are ten grants, but the INNER JOIN only returned nine records. Thus, inner
67
www.Joes2Pros.com
Chapter 3. Viewing Combined Information joins can produce what seem to be a data loss. We will explore how to know when this will happen.
Figure 3.7 Joining Grant to Employee with an inner join shows 9 of the 10 grants who have a matching EmpID in the Employee table.
The Grant called Normans Outreach was an online registration, so no employee is listed as receiving credit. (See Figure 3.6 where EmpID is NULL.) This is the NULL value we talked about in Chapter 1. Nulls will never match records in another table. Since no match was found, the record containing the Normans Outreach grant was not included in the result set. The core behavior of inner joins is to only include records when a match is found in both tables. Unmatched records are left out of the query result set.
68
www.Joes2Pros.com
69
www.Joes2Pros.com
Chapter 3. Viewing Combined Information Skill Check 3: Change your database context from the JProCo database to the dbBasics database. The Activity tables show the books which have been checked out and the Library card number of the library patron who checked it out. Join the Activity table to the Members table to see the books and the member details of who checked it out. When youre done, your result should resemble the figure you see here. Your Result set should contain 7 records.
Skill Check 4: In the dbBasics database, join the PurchaseActivity and the Customer table. Show just the Date, Item, Price and CustomerName fields. Your Result set should contain 11 records.
Answer Code: The SQL code to this lab can be found from the downloadable files named Lab3.1_InnerJoins.sql.
70
www.Joes2Pros.com
71
www.Joes2Pros.com
Outer Joins
If you understand inner joins, understanding outer joins is an easy progression. They both look for and display every match they find between two tables. Both joins require that you specify the matching field(s) in the ON clause. Outer joins can show the records that inner joins omit. The Employee table has 12 records and the inner join query with the Location table shows only 11 records. That is because John Marshbank is our traveling salesman and has no LocationID. In an employee report, you may want to list all employees and their location even if a location isnt listed. To do this you need to use some type of outer join.
Figure 3.12 A left outer join favors the Employee table listed to the left of the join.
72
www.Joes2Pros.com
Chapter 3. Viewing Combined Information (Figure 3.12). Notice John Marshbank appears. This left outer join will find all employees from the table on the left. It then tries to find matches with the table on the right. All employees are shown and matches are filled in and displayed.
Figure 3.13 The right outer join shows all locations, even if nobody works there.
Notice the EmpID values are no longer in order. The LocationID values go from one to four in order. The Location table is showing all records in order and any
73
www.Joes2Pros.com
Chapter 3. Viewing Combined Information matching values it finds in the join. Location is on the right side of this right outer join.
Figure 3.14 A full outer join shows all records from both tables.
Notice with a full outer join you get can get more records than either table contains. Here, the result set has thirteen records. The Employee table has twelve records and the Location table has four. Full outer joins show all matches and unmatched records from both tables.
74
www.Joes2Pros.com
Chapter 3. Viewing Combined Information Here is another example of the full outer join with all records from both tables. You want to find all employees with no grants and all grants with no employees. Use the full outer join seen in Figure 3.15. As we can see, the full outer join finds all matches and unmatched records. All our joins so far have not used the WHERE clause, so we got all possible records. With a WHERE clause you would get only the records that satisfied the WHERE criteria. For example, we could add the clause WHERE LocationID = 1 to the code shown above (Figure 3.14). This WHERE clause would filter the records down to just the Seattle location and the records that remain will display. Without the WHERE clause, you get all matches and unmatched records in your result set. Unmatched records between the tables show up as NULL.
Figure 3.15 A full outer join between the Grant and Employee tables shows all records.
75
www.Joes2Pros.com
Figure 3.16 The records for John cannot be found by the inner join, so the WHERE clause has no records to filter.
76
www.Joes2Pros.com
Figure 3.17 The WHERE criteria fetches the only record that matches its expression from the left outer join.
77
www.Joes2Pros.com
Answer Code: The SQL code to this lab can be found in the downloadable files in a file named Lab3.2_OuterJoins.sql
78
www.Joes2Pros.com
4. 5. 6. 7. 8.
Chapter Glossary
Inner Join: Combines records from two or more tables where matching values are found. Outer Join: Combines records from two or more tables and shows matching and unmatched values. Relational Database: A database containing more than one table. Flat File Database: A database with only one table. A text file or simple list is a flat file database.
79
www.Joes2Pros.com
Review Quiz
1.) Which symbol says you want all fields from a table in a SELECT statement? O a. O b. O c. O d. _ & % *
3.) The FROM Clause in a query against a single table is O a. O b. Optional Required
4.) Which record(s) will not return with the following WHERE clause? WHERE EmpName like %T (Choose all correct answers) a. b. c. d. Thomas Atwater Tompter TeeTee
5.) Which record will not return with the following WHERE clause? WHERE LastName like T% O a. O b. O c. O d. Thomas Atwater Tompter. TeeTee
6.) Which type of join would not show nulls as a match? O a. O b. O c. O d. INNER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN
80
www.Joes2Pros.com
Chapter 3. Viewing Combined Information 7.) Which syntax would create an error? O a. O b. O c. O d. O e. JOIN INNER JOIN INNER OUTER JOIN FULL JOIN FULL OUTER JOIN
9.) You have a table named Employee. You write the following query:
81
www.Joes2Pros.com
Answer Key
1.) The _ matches exactly one character when comparing strings so (a) is wrong. & is not a wildcard and would only match another & so (b) is wrong too. % represents zero or more characters when pattern matching so (c) is also wrong. The correct answer is (d) because * represents every field in a table. 2.) The WHERE clause filters records from the result set if used but not every result set needs to be filtered so (b) is not correct. If you want all records returned from a query you would not filter the table with a WHERE clause so (a) is the correct answer. 3.) Running a query without knowing what tables to use is not possible so (a) is not correct. Since the FROM clause tells the query which tables to look in, it is required making (b) the correct answer. 4.) Because % represents zero or more characters and the last character in the pattern to be matched is T the only names that will be returned will end in T. Since none of the names end in T (a)Thomas, (b)Atwater, (c)Tompter and (d) TeeTee are all correct answers. 5.) Because % represents zero or more characters and the first character in the pattern to be matched is T the only names that will be returned will start with T. Since 3 of the names do start with T (a)Thomas, (c)Tompter and (d) TeeTee are all wrong. Since Atwater is the only one that does not start with T (b) is the correct answer. 6.) OUTER JOINs display mismatching records using NULL as a value for fields in records that otherwise would not have been returned so (b), (c) and (d) are incorrect. INNER JOINs only display records where the field from one table contains the same value as the field in the other table so (a) is correct. 7.) Since JOIN is short for INNER JOIN both (a) and (b) are incorrect. Because FULL JOIN is short for FULL OUTER JOIN both (d) and (e) are incorrect too. Because INNER and OUTER are two different types of JOIN you cant use both on the same tables so (c) is the right answer. 8.) An INNER JOIN will return All records where both tables match so (a) is incorrect. RIGHT OUTER JOINing to Location would return All records from Location including matches from Employee making (c) wrong too. A FULL OUTER JOIN would return The superset of both tables so (d) is also wrong. Because Employee is on the left and Location is on the right of the LEFT OUTER JOIN operator (b) is correct and will return All records in Employee including matches from Location
82
www.Joes2Pros.com
Chapter 3. Viewing Combined Information 9.) RIGHT JOIN Location lo ON em.LocationID = lo.LocationID will return all location records including any matches from the employee table so (b) is wrong. INNER JOIN Location lo ON em.LocationID = lo.LocationID will only return the employee records that have a matching location so (c) is wrong too. FULL JOIN Location lo ON em.LocationID = lo.LocationID will return the superset of both tables making (d) incorrect. LEFT JOIN Location lo ON em.LocationID = lo.LocationID will return all employee records including any matches from the location table making (a) the correct answer.
83
www.Joes2Pros.com