Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating conditions in SQL

From: SQL Server 2008 Essential Training

Video: Creating conditions in SQL

So we have this very simple SQL query, selecting these three columns from the SalesLT.Customer table in the AdventureWorksLT database. If I execute that, it's going to bring back the entire contents of that table, which is 847 rows. But I can either see by scanning through it or down here in the status bar, 847 rows. But of course, if I don't want all those rows available, if I want to filter that information, it's a very common thing. So, the way that I do it is by using the WHERE keyword.

Creating conditions in SQL

So we have this very simple SQL query, selecting these three columns from the SalesLT.Customer table in the AdventureWorksLT database. If I execute that, it's going to bring back the entire contents of that table, which is 847 rows. But I can either see by scanning through it or down here in the status bar, 847 rows. But of course, if I don't want all those rows available, if I want to filter that information, it's a very common thing. So, the way that I do it is by using the WHERE keyword.

I only want to bring back that data where people have a certain last name or have a certain email address or their customer ID is in a particular range. Now it all depends on what kind of data that you're filtering on. So, for example, if I wanted to bring back information where the LastName of the person was equal to Vargas, well, if it's text I need to write it in quotes. Another single quote again here. If I execute that, I get in this case four rows coming back. It looks like my table may even have some duplicate data that I will need to look at a little later.

You'll find that this equality is case insensitive. That is based on the collation all the database. So whether it's lowercase v or uppercase V, it doesn't matter. But I do need the quotes. After all if I was missing the quotes, the SQL Server database is trying to imagine that this is probably a column. I try and execute it. It says I have no idea what this is meant to be. So if it's text, it's in the single quotes. If however it is a number, so for example this table has a CustomerID, which is numeric, it's just an integer, I could say CustomerID = 600.

I don't want the quotes here and I am now retrieving that piece of data. Now you notice that I can put a WHERE clause here based on a column that I'm not retrieving in my SELECT part of the statement, which is perfectly acceptable. I can either be bringing back CustomerID or not. it doesn't matter. I can still filter on it. Now just as we have the equal sign, we could always say WHERE CustomerID > 600 and execute that. 466 rows returned.

Well, surprisingly again, we have the less than sign, less than and equal to, all the usual suspects. We can also describe a range. I could say WHERE CustomerID >600 and it's >800 and the way that I would write is using the keyword AND actually written out here. AND CustomerID < 800. Execute that. We get 59 rows returned.

We also have a slightly more readable way of doing it where I could actually say WHERE CustomerID between 600 and 800. However, this one is considered an inclusive statement, meaning that if I was actually retrieving the CustomerID as part of my statement, just to take a look it at, we can see that when it says between 600 and 800. It's like a greater than or equal to. So we are retrieving 600 there rather than a greater than sign, which would skip the 600.

You can also do this with textual or character fields. Although in this case because we have no one exactly matching A and C, we are just bringing back all the B LastNames. If you wanted to check for multiple values where you're interested in several different LastNames, for example, we could of course say where a LastName = Smith or LastName = Bright or a LastName = Bremer.

Just like having the AND we can have an OR statement. But we can also use the keyword IN to describe a range. Because I'm checking for a text value, I do need to surround each independent value with the single quotes and just separate them by commas. Now getting a little bit more flexible with this, let's say for example that we have been retrieving some information including the CompanyName.

And when we are scanning things, we are finding several companies with very similar names, like Metro for example. Well, what I could ask is to bring back this information where the CompanyName begins with the word Metro. The way that I do this is I actually use the keyword LIKE. I type in the text that I want to find and for whatever else it could be, the wildcard is the percent sign.

In a lot of languages or other ways of doing this, this might be represented with an asterisk, but in SQL it's the percent sign and we use LIKE. So this should bring me back anything where the company name begins with Metro, anything else. We click execute, and oops! Unfortunately, what I've got to be careful with this is I had Metro actually highlighted. That means it was just trying to execute that word. I do need to make sure that I haven't got any particular piece of text selected there. And there we go. We are bringing back 14 rows with several different places, Metro Cycle Shop, Metropolitan Bicycle Supply, Metro Manufacturing.

Again, like any text operation this is case insensitive. So it doesn't matter whether it's an uppercase M or lowercase m. You can also put the % sign at the beginning of the word, and in this case this would do a wildcard search for anything in the company name column that had etro anywhere in that string. I execute that and we are also getting back Petroleum Products Distributors. If however, you're just looking for a single letter, you can represent that with the underscore in your LIKE statement, which in this case brings back the same information, but is a slightly more specific way to do it.

Do you bear in mind that if you're doing lots of wildcard searches, this can be very inefficient, particularly on large databases if it has to scan the tables and go through every column row by row figuring out if these letters occur anywhere there. Now depending on the data that you are retrieving, sometimes you will get a value and sometimes you won't. If I retrieve the MiddleName, for example, I can scan the data returned and see that several of them have NULL being returned.

This is also slightly highlighted to indicate it's not word null. It is a NULL value. There's nothing here. Well, what if I wanted to only retrieve those rows where that value was NULL? Well, I might be tempted to say WHERE MiddleName = NULL and we try and execute that and nothing comes back. Because that's not the word that we use when we are checking for the existence of NULL. What we want is the word IS where MiddleName IS NULL, not = NULL, because a quality is a value.

This is the lack of a value. So, now I'm retrieving the 343 rows where MiddleName is NULL. Conversely, if I'm just interested in the fact where it's not NULL, well, we just say IS NOT NULL and execute that. And now, we only have the rows where the MiddleName is not NULL and has a value. You can of course get a little deeper than this on your conditions and we'll see how to connect values to other tables and what's going on in other parts of the database.

But with what we've just seen, that'll get you writing most of the conditions in at least your basic SQL statements.

Show transcript

This video is part of

Image for SQL Server 2008 Essential Training
SQL Server 2008 Essential Training

74 video lessons · 36715 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 2m 21s
    1. Welcome
      1m 19s
    2. Using the exercise files
      1m 2s
  2. 17m 58s
    1. SQL Server core concepts
      9m 4s
    2. SQL Server editions
      3m 8s
    3. Applications included with SQL Server
      5m 46s
  3. 26m 1s
    1. Preparing for installation
      3m 44s
    2. Creating service accounts
      2m 33s
    3. Installing SQL Server
      11m 42s
    4. Post-installation checks
      3m 9s
    5. Installing sample databases
      4m 53s
  4. 13m 35s
    1. Introduction to SQL Server Management Studio
      8m 7s
    2. Introduction to SQL Server Books Online
      3m 6s
    3. SQL Server system databases
      2m 22s
  5. 1h 26m
    1. Planning your database
      9m 39s
    2. Creating a SQL Server database
      4m 7s
    3. Creating tables
      7m 51s
    4. Data types in SQL Server
      12m 25s
    5. Defining keys
      8m 9s
    6. Creating default values
      4m 39s
    7. Creating check constraints
      2m 25s
    8. Creating unique constraints
      4m 34s
    9. Introduction to relationships and foreign keys
      9m 51s
    10. Creating relationships in SQL Server Management Studio
      8m 14s
    11. Database normalization
      11m 47s
    12. Creating computed columns
      3m 10s
  6. 23m 11s
    1. Using the SQL Server Import and Export Wizard
      3m 58s
    2. Importing Excel files into SQL Server
      6m 11s
    3. Importing CSV files into SQL Server
      5m 27s
    4. Importing Access databases into SQL Server
      7m 35s
  7. 55m 29s
    1. Introduction to Transact-SQL
      3m 43s
    2. Using SELECT statements
      7m 16s
    3. Changing the default database
      2m 21s
    4. Creating conditions in SQL
      8m 10s
    5. Sorting your output
      3m 23s
    6. Using aggregate functions
      7m 12s
    7. Finding unique values
      2m 14s
    8. Joining multiple tables together
      8m 0s
    9. Using subqueries
      9m 33s
    10. Viewing execution plans
      3m 37s
  8. 19m 36s
    1. Writing INSERT statements
      5m 47s
    2. Writing UPDATE statements
      4m 38s
    3. Writing DELETE statements
      2m 54s
    4. Using the OUTPUT clause to return inserted keys and GUIDs
      6m 17s
  9. 32m 52s
    1. Introduction to SQL functions
      6m 26s
    2. Using SQL configuration functions
      2m 14s
    3. Using string functions
      7m 26s
    4. Using date functions
      6m 27s
    5. Creating user-defined functions
      10m 19s
  10. 28m 46s
    1. Introduction to stored procedures
      4m 23s
    2. Creating stored procedures
      11m 23s
    3. Introducing transactions
      4m 23s
    4. Creating transactions
      8m 37s
  11. 16m 39s
    1. Understanding and creating indexes
      6m 32s
    2. Monitoring and rebuilding indexes
      6m 0s
    3. Monitoring database size and integrity
      4m 7s
  12. 11m 41s
    1. Creating backups
      4m 21s
    2. Creating differential backups and using backup compression
      3m 40s
    3. Restoring databases
      3m 40s
  13. 17m 40s
    1. Introduction to SQL Server security and permissions
      5m 54s
    2. Adding a Windows user to the database
      5m 7s
    3. Creating SQL Server logins and switching authentication modes
      6m 39s
  14. 36m 41s
    1. Introduction to SQL Server Reporting Services
      2m 52s
    2. Connecting to the Report Manager
      4m 29s
    3. Using Report Builder
      12m 4s
    4. Formatting values in reports
      4m 17s
    5. Adding indicators to reports
      5m 11s
    6. Adding charts to reports
      3m 54s
    7. Working with report security
      3m 54s
  15. 24m 41s
    1. Introduction to SQL Server Integration Services (SSIS)
      1m 57s
    2. Using Business Intelligence Development Studio (BIDS)
      6m 59s
    3. Creating and executing a simple SSIS package
      7m 35s
    4. Importing packages into SQL Server Management Studio
      3m 21s
    5. Scheduling jobs with SQL Server Agent
      4m 49s
  16. 31s
    1. Goodbye
      31s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed SQL Server 2008 Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.