Download presentation
Presentation is loading. Please wait.
Published byPaula Pope Modified over 7 years ago
1
Instructor: Craig Duckett Lecture 02: Thursday, March 30th, 2017
SQL Basics and SELECT, FROM, WHERE
2
Assignment 1 is due LECTURE 5, Tuesday, April 11th, 2017 in StudentTracker by MIDNIGHT
MID-TERM EXAM is LECTURE 10, Thursday, April 27th, 2017 Assignment 2 is due LECTURE 12, Tuesday, May 9th, in StudentTracker by MIDNIGHT
3
3 x 150 Points (450 points Total)
Assignment 1 (Stage 1): DUE LECTURE 5 Tuesday, April 11th Assignment 2 (Stage 2): DUE LECTURE 12 Tuesday, May 9th Assignment 3 (Stage 3): DUE LECTURE 20 Tuesday, June 6th Database Presentation: DUE LECTURE 20 Tuesday, June 6th
4
Tuesday (LECTURE 1) Database Design for Mere Mortals: Chapter 1 Thursday (LECTURE 2) The Language of SQL: Chapter 1: Relational Databases and SQL Chapter 2: Basic Data Retrieval
5
SQL Basics SQL Syntax SQL Keywords The SELECT Statement The FROM Clause The WHERE Clause BIT275: ICE 02
6
SQL Basics
7
SQL Basics SQL, or Structured Query Language, is the common language that lies at the heart of every Relational Database Management System* (the application that actually gets the SQL to run and do something) that you'll likely to use. Now, you've probably noticed the different pronunciation already. Some people say S-Q-L, some people say sequel. I tend to say S-Q-L in general and when talking about MySQL (the MySQL official documentation says that’s how it should be pronounced), but I will say Microsoft Sequel Server (because that’s how they pronounce it on-campus AT Microsoft) although will sometimes revert to S-Q-L Server if I’ve been talking about SQL in general just before hand. In short, both ways are correct, but I would defer to what and how they are calling it where you work Now SQL, the language, has been around since the 1970s, and that's one of the few languages I was writing 20 years ago that I'm still writing now. A lot of other programming languages have come and gone, become fashionable and unfashionable, but SQL has stuck around, and I expect it to stay for a long time to come. But SQL is a very small, very focused language, and the key to first learning it is to understand that it's a little different from other programming languages you might have come across, like C, C++, Java, or C#. SQL is what's considered a declarative query language, as opposed to procedural or imperative languages. What it means is you use SQL to describe what you want, and you let the Database Management System (DBMS) handle how that's actually done. You don't have to manually lay out the algorithm, the different steps of the procedure as you would do in other programming languages.
8
*How Does SQL Run? Different Types of Database Management Systems
A .java files is simply a text file that needs a compiler like jGrasp to run. An .html or .css or .js file are also all text files that need a browser application to run. A C or C++ or C# file are simply text files as well that also need a compiler to run. Like them, a .sql file is also a text file that needs a Database Management System (DBMS)* to run, although you can also enter your SQL queries directly into the DBMS without the need of a separate .sql file (as we shall see throughout the quarter, and starting with today’s ICE). Different Types of Database Management Systems Access FileMaker Pro DB2 Sybase dBase InGres PostgreSQL Rocket U2 MySQL MariaDB SQL Server Oracle See:
9
SQL Basics: How Does It Work?
If I have a Books table with, perhaps, thousand different books in it, and I want to know which books have a list price of more than $40. Well, in a procedural or imperative language like C or Java, I'll have to write the steps to do this…
10
SQL Basics I would probably write some (pseudo) code that would start at the first book and then would loop through all of them one by one. And every time going through this loop you're asking the question, "Is this more than $40? If so, do one thing. If not, do something else." Even writing this in pseudo code, I'd be writing a loop. I'd be writing conditions. I'd be writing returns.
11
SQL Basics With SQL, you don't describe all the steps, you just describe the outcome. You describe what you want the same way you might do in English, where you just say: or this written in SQL: That's it. Select or go get everything from the Books table where the price is more than $40. The Database Management System will take this, it will look at all your data, figure it out, and return the result set, whether that would be one book, 500 books, or even none, based on your query.
12
SQL Basics So SQL can be used to select, to retrieve, or read data, and to ask questions of it. Books Table
13
SQL Basics In fact, all of these things are referred to with the wonderful acronym of CRUD: Create, Read, Update, Delete. An SQL can be used to create not just your data, but to define the databases themselves. FYI: I will be discussing Data Manipulation Language (DML) and Data Definition Language (DDL) in Lecture 5
14
SQL Syntax
15
SQL Syntax Comment A comment is optional text that explains you program. Comments usually describe what a program does or why code was changed. Compilers are for humans—the compiler ignores them. A comment is introduced by two consecutive hypens and continues until the end of the line. -- This is a comment Some DBMS (like Microsoft SQL Server) support the /* ... */ (forward slash-asterisk character pairs) multiline comments (those who've taken Java or C# should recognize these). SQL Statement An SQL statement is a valid combination of tokens introduced by a keyword. Tokens are the basic indivisible parts of the SQL language; they can’t be reduced grammatically. Tokens include keywords, identifiers, operators, constants, and punctuation symbols. Clauses An SQL statement has one or more clauses. In general, a clause is a fragment of an SQL statement introduced by a keyword, is required or optional, and must be given in a particular order. SELECT, FROM, WHERE, and ORDER BY are examples of clauses. Keywords Keywords are words that SQL reserves because they have special meaning in the language. Using a keyword outside its specific context (as an identifier, for example)) causes an error. DBMSs use a mix of standard and nonstandard (proprietary) keywords. Search your DBMS documentation for keywords or reserved words. Identifiers Identifiers are words that you (or the database designer) use to name database objects such as tables, columns, aliases, indexes, and views. Terminating Semicolon AN SQL statement ends with a semicolon.
16
Authors Table
17
SQL Syntax SQL is a "freeform" language whose statements can:
Be in uppercase or lowercase (SELECT, select, or SeLECt are considered to be identical keywords) Continue on the next line as long as you don't split words, tokens, or quoted strings in two. Be on the same line as other statements Start in any column Despite its flexibility, you should adopt a consistent style. I prefer to use uppercase keywords (e.g., SELECT) and an uppercase/lowercase mix for identifiers using Pascal case (e.g., FirstName). Although I don't do it myself, some SQL coders also like to indent each clause on its own line:
18
SQL Syntax Common Errors
Omitting the terminating semicolon when using multiple statements (or Transact-SQL) Misspelling a keyword or identifier Mismatched or unmatched parentheses or quotes (e.g., double quotes instead of single quotes) Listing clauses out of order Not surrounding a string or datetime literal with single quotes Surrounding a numeric constant (literal) or the keyword NULL with quotes Mismatching a table and column name Creating a table with a bad name
19
SQL Keywords
20
SQL Keywords Structured Query Language is the shared vocabulary of relational databases. That's not for general purpose programming. It's a small language focused purely on working with databases and the first handful of keywords that you'll learn (maybe a dozen) will take care of 90% of everything you'd ever do in SQL.
22
The SELECT Statement See:
23
The SELECT Statement See: http://www.w3schools.com/sql/sql_select.asp
In terms of frequency, there's one that's head and shoulders above all the others. By far the most common word you'll ever write in SQL is SELECT. This is the word we start with when we want to SELECT or read information from one of the tables in one of our databases. We're using it to ask the database a question, and we expect a reply. Actually, the better word is not question but query. A query as in the Q in SQL: Structured Query Language. if I want to SELECT some data out of my database, I'm going to have multiple tables and multiple columns in each table. So, I need to say what specific part of this database am I interested in selecting. The general format of a SELECT statement is the word SELECT, what columns you're interested in, then the word FROM what table? SELECT and FROM are your SQL keywords. They're part of the SQL language itself. Now, the columns and table names are up to you. It's whatever you named your columns and your tables in your database. See:
24
The FROM Clause
25
SELECT Statement, FROM Clause
So, if you're interested in getting some information, say out of this Employee table, I'll just pick one of the columns: FirstName, and the name of the table itself, so SELECT FirstName from Employee. Now, running or executing this query would return all the values in that FirstName column, from all the rows in the Employee table whether that's one row or 100,000 rows or none.
26
SELECT Statement, FROM Clause
So, if you're interested in getting some information, say out of this Employee table, I'll just pick one of the columns: FirstName, and the name of the table itself, so SELECT FirstName from Employee. Now, running or executing this query would return all the values in that FirstName column, from all the rows in the Employee table whether that's one row or 100,000 rows or none.
27
SELECT Statement, FROM Clause
Now, you often want multiple column values, so if you want multiple columns, you separate them with commas. FirstName, LastName. If I run that query, we get both columns, again, for all the rows in that Employee's table.
28
SELECT Statement, FROM Clause
If on the other hand, I want all the columns in this table, I don't actually have to write them all. I can use the asterisk instead. So just SELECT asterisk or SELECT star is the common phrase that you'll hear, from Employee. And this would return every column for every row in the Employee table. It's basically saying just show me everything in that table.
29
The WHERE Clause
30
The WHERE Clause See: http://www.w3schools.com/sql/sql_where.asp
Now, because you often want to restrict what is returned, optionally you'll add another keyword to your query which is WHERE. This is your WHERE clause, where a particular condition is true. See:
31
The WHERE Clause See: http://www.w3schools.com/sql/sql_where.asp
Now, because you often want to restrict what is returned, optionally you'll add another keyword to your query which is WHERE. This is your WHERE clause, where a particular condition is true. See:
32
Uppercase, Lowercase, Semicolon?
SQL is not case sensitive generally speaking. It really doesn't care if the word SELECT here is written in upper case or lower case. Now, by long convention over many years, most developers will write the SQL keywords all uppercase. It makes these statements easier to read. Your table names and column names on the other hand, should just match however they were named in the database, whether that was, lowercase, uppercase, mixture, or whatever. Having said that, many Database Management Systems don't even care about that and they treat table names and column names as case insensitive too. Now, line breaks also don't matter. SQL is not sensitive to white space. You can split an SQL statement across multiple lines, as I'm doing here for readability. Now, officially, a complete SQL statement should be ended with a semicolon, though in practice, many Database Management Systems just don't care. But you'll see the semicolon on most of what I write to make it explicit.
33
Database Name with Dot Notation
Currently, I'm selecting everything from the Employee table, but one question you might have is what if you have multiple databases? How does it know which database this table is in? After all, I could even have several databases containing tables with the same name. If that's the case, I need to use not just the table name but the name of the database itself in my SQL statement, but depending on the way you're writing it, the Database Management System may assume that you're already pointing to a particular database. There's often a default database for the database server if you don't name one explicitly. But if I wanted to be explicit, I'd use the name of the database, then a period, then the name of the table. So, here I'm making the assumption I have a database called HumanResources, and I'm interested in the Employee table inside that database. This can be done a little differently depending on the Database Management System, but it is usually this simple. Now, right now, these statements are only selecting from one table at a time. We can write SQL to bring back information from multiple tables in the same query, depending on the relationships we've defined, but that comes later. First, we need to take a closer look at the WHERE clause. Dot notation allows you to prefix a table name to a column name to avoid ambiguity and to query multiple tables.
34
More About the WHERE Clause
When writing a basic query, coming up with the SELECT and FROM parts should be fairly easy to decide, simply what tables you're interested in and what columns in that table you want to see. But writing the WHERE part, where you're specifying their condition or what's officially called a predicate, well, that can give you a few more options to choose from. But writing a WHERE clause to go against a particular table is a bit like writing an if statement in a conventional programming language. You're trying to describe something that at heart is either true or false.
35
More About the WHERE Clause
So, if I want to go against this table and bring back all the rows where people have a certain LastName, it's either true, or it is false. It's the same if they have a certain address or their Employee ID is in a particular range, or they were hired after a specific date. It's either true, they match that condition or false that they don't. And how you write this part, this WHERE statement, kind of depends on the data that you're matching to and how specific you want to be. So, let's get through a few examples. Right now, if I wanted to select all the rows where the LastName of the employee was equal to Green, well, this is the way I would do it. And if it was text that I'm matching on, I need to write that in quotes. Now unlike most general purpose programming languages, strings in SQL use single quotes, not double quotes here. I'll say that again, because it's important. String values in SQL are surrounded with single quotes. It is one of those situations where some Database Management Systems will be flexible and they'll allow you to use either single or double quotes, but if you're talking classic SQL, it's single quotes. Also notice if you're coming from a C-based language, we don't use the double equal sign here for equalities just single equals. We also don't need to surround our condition, our predicate in parenthesis, though you can, if it helps.
36
More About the WHERE Clause
Single ‘=‘ sign If on the other hand I'm checking a number, something that is stored as a numeric column, EmployeeID, for example, I don't need the quotes. So I just directly ask if it's equal to that particular value. And if we're working with numeric options like Salary, I have the comparison operators. We have the operators that you might expect. Greater than, less than, greater than or equal to, less than or equal to, and not equal is written with the less than and greater than signs right next to each other. So, in this case I'm asking for all the rows WHERE Salary > 50,000. ‘<>’ NOT equal
37
More About the WHERE Clause
AND And you can also use AND or OR to combine multiple conditions in your WHERE clause. So, in this case I'll say WHERE Salary > 50,000 AND the Department column value is equal to 'Sales'. And particularly for those of you coming from C-based languages, we actually use the word AND or OR not vertical bars or ampersands. So, in this case a perfectly acceptable way to check if the value of Department is equal to Marketing, or it's equal to Sales, we're going to bring back all those rows. OR See:
38
More About the WHERE Clause
IN Now if you wanted to check for multiple values where you're interested in the same column having several different options, in this case Department being Marketing or Sales, we can also use the word IN and then surround the multiple values inside parentheses separating them by commas. Bcause I'm checking for a text value, I need to surround each independent value with the single quote and just separate them by commas here. (note the single quotes, and comma) See:
39
More About the WHERE Clause
If on the other hand, what you're looking to do is be a bit more flexible on matching text, then instead of using the equal sign, which wants an exact match, we can use the SQL keyword LIKE. Now in a lot of other programming languages or other ways of doing wild card searches, you use a wild card character of an asterisk, but in SQL, it's the percent sign. So, I'm asking here where the last name column is LIKE 'Green%' and then anything after this. So this query would match all the rows with Green in that column, but also Green Span, Green Berg, Green Away, and so on. The wild card can be placed at the end of the text, it can be placed in the middle, it can be placed at the start. And it will match any number of characters. ‘%’ wildcard A substitute for 0 or more characters See:
40
More About the WHERE Clause
‘_’ wildcard If however, you're just looking to match on a single letter, you could represent that with an underscore in your LIKE statement, which in this case would bring back anything that matches on Smith with an I or Smyth with a Y or any letter there. However, do you understand that in large tables, using LIKE can be quite inefficient as it's more demanding on the database to check multiple possible contents of a particular column value, rather than just checking for pure equality, which is a lot easier to do. A substitute for a single character See:
41
More About the WHERE Clause
Some columns can be set to allow null, meaning the lack of a value, and often you want to find out if that is the case or not the case in your WHERE clause. [We'll talk in more depth about NULL when we return to the Design side of things] So, let's say this Employee table that I've defined has a column called MiddleInitial, and that has been set to allow null values when people simply don't have a MiddleInitial. If I wanted to find those people, I might first think to write something like this, WHERE MiddleInitial = NULL, but actually equals is not a good word to use when we're checking for the existence of null, because it's not equal to NULL because NULL isn't a value. It's not equal to anything. What we want instead is the word IS. IS NULL See:
42
More About the WHERE Clause
So instead of MiddleInitial = NULL, it's WHERE MiddleInitial IS NULL. And this would bring back all the rows where there had been no values stored in that column. Conversely, if I'm just interested in the rows that have a value in that column where we can say instead IS NOT NULL and execute that, and now we'd only get the rows where that column actually had a value for each row. And this covers the basics of the most commonly used options in WHERE clauses. IS NOT NULL See:
43
BIT 275 ICE 02
44
BIT275: In-Class Exercises (ICE)
SQL Query Exercise (solo, no partner ) Using what you've learned today about SQL, use the remainder of the class time to write SQL queries as part of the BIT275 ICE 02 exercise. Feel free to utilize whatever you might find useful in building these queries (a book, the PowerPoint slides, Google, etc).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.