Вы находитесь на странице: 1из 9

BASIC SQL STATEMENTS

THIS WEEK'S LEARNING OBJECTIVES


Understand how to use the following SQL statements

SELECT
ORDER BY
WHERE
Logical Operators
JOIN
Aliases

THE SELECT STATEMENT


The SELECT statement is used to retreive data from tables within a SQL database.
SELECT ColumnName1, ColumnName2...
FROM TableName

After the SELECT you choose which columns you wish to display in your output
After the FROM you choose which tables these columns are in

Here is another method we can use.


SELECT *
FROM TableName
In this situation, we used a wildcard. This means all columns from the table will be shown. Later on when we join
tables together, wildcards can be used in conjunction with specific columns.

SORTING USING ORDER BY


Now that we know how to pull data from a table, we can use ORDER BY to reorder the results.
SELECT *
FROM TableName
ORDER BY Column1, Column2...
Notice that we can sort by multiple columns. For example, if the first column specified in country and the second
column is province. All records will be sorted in order by country first, then by province.

By default all records are sorted in ascending order (A-Z). You can specify to sort in descending order as well (Z-A).
Although it is default, you can also explicity set the sort for ascending as well.
The following command sorts Column1 ascending (As it's the default) then Column2 as descending.
SELECT *
FROM TableName
ORDER BY Column1, Column2 DESC
The following command will do the same as above, but in this case we are explicity stating for Column1 to sort
ascending.
SELECT *
FROM TableName
ORDER BY Column1 ASC, Column2 DESC

THE WHERE CLAUSE


The WHERE Clause can be added to the Select statement. This can be used to "filter" the results you see. For example,
if you only wanted to see the records where the country is "USA"
SELECT *
FROM TableName
WHERE Column = value
ORDER BY Column
This is the proper order for the select statement, notice we first specify the columns we wish to see, followed by
what tables are included in the select statement. Then we enter in our WHERE clause (or conditions) followed up by
the ORDER BY
This syntax checks a column against a value, if it is true then the record will be displayed in the results. If the value
is a string of characters (such as text) you need to put single quotes around the value ('value'). If it is numeric the
value does not need single quotes.
Although the WHERE clause can also be used to join tables, this is not a proper method. We should use the WHERE
clause to define conditions, we will look at the JOIN clause next for a better way to join tables.

LOGICAL OPERATORS
We can include logical operators in our WHERE clause.
These are two main logical operators

AND
OR

Here is an example of the AND operator:


SELECT City, Country
FROM Locations
WHERE Country = 'USA' AND City = 'Detroit'
ORDER BY Country, City
In this situation both conditions to the left and right of the and operator must be true for the results to be shown.
In this case, in a single record the country must equil USA and the city must equal to Detroit for the record to show.
Here is an example of the OR operator:
SELECT City, Country
FROM Locations
WHERE Country = 'USA' OR City = 'Detroit'
ORDER BY Country, City
In this situation either condition to the left or right of the OR statement has to be true. So in this case the results will
show all records where the country is set to the USA. It will also include all records where the City is set to Detroit.
This does not make too much sense for this situation, so the OR statement is probibly not ideal for this. So why
would we use the OR?
The OR's are usually used in situations where you wish to get information say from more than one country. Here is
an example:
SELECT City, Country
FROM Locations
WHERE Country = 'USA' OR Country = 'Canada'
ORDER BY Country, City
In this query we will return records where the country is either USA or Canada. If you use the AND here you will
never display any results as a single record cannot have two different values for the same column.
We can also use brackets to help with the order of operations. SQL Server will process logical conditions in brackets
first. Just like in math :)

To understand this more, lets create a broken SQL Query and fix it using brackets.
SELECT City, Country
FROM Locations
WHERE Country = 'Canada' AND City = 'Vancouver' OR City = 'London'
ORDER BY Country, City
So what is the issue with this query? Well, both conditions to the left and right of the AND must be true. So only
results where the Country = 'Canada' and City = 'Vancouver' will be shown. Another issue, only one condition left or
right of an OR has to be true. So the results will show where the Country is Canada and the City is Vancouver but
also any city that is London regardless of the country.
How do we fix this?
The easiest way to fix this is to add in brackets.
SELECT City, Country
FROM Locations
WHERE Country = 'Canada' AND (City = 'Vancouver' OR City = 'London')
ORDER BY Country, City
So we added brackets around our OR statement values. Everything in the brackets to the right of the operator is
considered one value. So regardless if the city is London or Vancouver, they but also must be part of Canada.
There are other logical operators we can use with numerical values and dates. We already used '=' equil to, but here
are some more we can use.

< - Less than


> - Greater than
<= - Less than or Equal to
>= - Greater than or Equal to

JOINING TABLES
You can use the JOIN clause to join multiple tables together for your results.
Here is the syntax of a JOIN statement
SELECT *
FROM Table1
JOIN Table2
ON Table1.column = Table2.column
WHERE Column = valueORDER BY Column

A few things to note:

After FROM, we specify the first table in our query


Then we JOIN a second table
Then using ON we define the relationship between the tables
If you wish to JOIN more tables, repeat the JOIN and ON statements for each new table.
After your JOIN is where you can define conditions with the WHERE Clause, followed by the ORDER BY
Clause.

For us to join tables, we need to know which columns reference each other. Refer to the Exhibit shown here, How
do we know which department Joe belongs to? Well, we know Joe belongs to the Sales department, but how do we
know this? We know this because we match up the ID_Dept column from the tblstaff table with the ID_Dept column
from the tblDept table.
If we wanted to show in our results our staff name and the department they belong to we need to join the tables
together. We also need to tell SQL Server how to match up which records belong to each other (The relationship).
Just like we did by matching up ID_Dept between the two tables.
Let us look at the join statement showing the staff name and their department
SELECT tblStaff.Name, tblDept.Name
FROM tblStaff
JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept

A few things to note:

When defining which columns we want to see in the results, we specify the table name followed by the
column name. This is only necessary when we have an ambiguous column name. In this case Name will exist
twice in our results, once from the tblStaff and once from the tblDept table. SQL Server needs to know
which name you want to display.
Our first table to add into our results is defined after the FROM statement and is tblStaff
Our second table toa dd into our results is defined after the JOIN statement and is tblDept
Our relationship is defined after the ON statement. This is what we reference to understand which
department belongs to which staff member

Another note, column names in the relationship do not need to be named the same thing. Although they typically
are, you will find situations where they are not. The only thing to keep in mind is to make sure the correct columns
are referencing each other.
If in the example above we changed the ON to "ON tblStaff.ID_Staff = tblDept.ID_Dept" This would still display the
results, but they would be incorrect. In this case Bob would be displayed as being part of the IT Team but Bob is
actually part of the Marketing team. So make sure your relationships are correct.

DIFFERENT TYPES OF JOINS


There are different type of JOINs you can do within SQL Server. Here is a list of joins you can use.

INNER JOIN - This is the same as just using JOIN, this is the most common type of join.
LEFT OUTER JOIN (or LEFT JOIN)
RIGHT OUTER JOIN (or RIGHT JOIN)
FULL OUTER JOIN (or FULL JOIN)

To understand this a bit more, let us look at the examples below:


Let us start with a typical inner join
SELECT tblStaff.Name, tblDept.Name
FROM tblStaff
JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept

This is our inner join statement, this will only return results where there is matching record on both tables.
In this case, you will see a result for Joe, George and Jane.
You will not see Bob, Ann or Marketing as there is no matching record from the other table. This is an inner join.
Next, let us make a left outer join statement.
SELECT tblStaff.Name, tblDept.Name
FROM tblStaff
LEFT JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept

This is our left outer join statement, this will return all results from the table on the left side of the join statement
regardless if there is a match on the right side. Records from the table specified on the right side of the Join will only
appear if they have a corresponding record from the table on the left.
In this case Joe, Bob, George, Jane and Ann's records will all appear. Bob and Ann's department will show up as Null
since they do not have a department. Marketing will not show up as there is no corresponding match within the left
table.
A right outer join is the opposite of this.
Finally, let us look at our full outer join.
SELECT tblStaff.Name, tblDept.Name
FROM tblStaff
FULL JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept

In this case all records from both tables are displayed regardless if there is a matching record from the other table.
In this case, Joe, Bob, George, Jane and Ann's records will all be displayed. Bob and Ann will have a Null department
value in the results as they do not belong to a department.
Also, Sales, IT and Marketing will also be displayed. Marketing will have a null value in the results as no staff are in
the marketing department.

ALIASES

If we join these two tables together and we want to show the name of the staff member and the name of the
department. The column headers would both say name.
In our case, we should assume someone could make the distinction between a person's name and the department's
name. But not all queries will be so simple.
If we had a table with customers name and we wanted to show their sales rep name. How would we know which
name was the sales rep name and who's was the customer's name. The table name the column comes from is not
shown in the result so we need to add an alias.
An alias allows us to rename the column shown in the result. This helps us show more intuitive column names in our
results.
To add an alias, all we need to do is append it to the column name in our select statement. There are two ways to
do this.
SELECT tblStaff.Name 'Staff Name', tblDept.Name 'Dept Name'
FROM tblStaff
JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept
In the results the column headers will show the alias instead of the column name. The alias is in the single quotes.
Another method to do the same thing is to use AS as shown here:
SELECT tblStaff.Name AS 'Staff Name', tblDept.Name AS 'Dept Name'
FROM tblStaff
JOIN tblDept
ON tblStaff.ID_Dept = tblDept.ID_Dept

Вам также может понравиться