Microsoft Access Lesson 5: Structured Query Language (SQL) Structured Query Language (pronounced S.Q.L. or sequel ) is a standard computing language for retrieving information from and manipulating databases. Access actually is a front-end to SQL: when you write a query using Access s GUI interface, the query is converted to a SQL statement before executing. SQL is a powerful, but fairly easy to use, tool. Although SQL is a versatile tool that can be used to update, insert, and delete records from database tables, we will limit this lesson to querying a database. SQL Keywords and Syntax There are several variations of SQL, but the major keywords in the different versions usually are the same. The keywords that are most important for queries are listed below SELECT FROM WHERE ORDER BY INNER JOIN... ON... Used to specify the fields you want to retrieve Used to specify the tables from which you will pull the data Used to specify the criteria that limit the data you retrieve Used to specify how the data will be sorted Used to relate two tables (the usual Access join) A SQL query commonly is made up of four clauses: SELECT field names FROM table name WHERE specify criteria (if any) ORDER BY specify sort (if any) ; Note the semicolon at the end of the statement. 1
SQL Operators and Wildcards These should be familiar, because they are the same as we used in Access, which is not coincidental since Access is a SQL front-end. Operator Meaning Example = Equal to = 100 > Greater than > 100 < Less than < 100 >= Greater than or equal to >= 100 <= Less than or equal to <= 100 <> Unequal to <>100 BETWEEN... AND... Between two numbers Between 100 and 200 LIKE Used with a wild card Like r*g (see below) Wildcard Symbol * Meaning One or more characters Example? One alphabetic character r?g will find rig and rag # Any single numeric character 10# will find 101 and 105. The comparison operators and wildcards are used in the WHERE clause of the SQL statement. Note that an expression containing a wildcard must be surrounded by apostrophes: LIKE 1/*/2000 LIKE Arth* LIKE 10# LIKE r?g r*g will find rig, rag, ring, rung and running Sorting Information Using SQL The ORDER BY clause tells how to sort the information. Ascending order: Descending order: ORDER BY ORDER BY... DESC (the default) If you ORDER By more than one field, the information will be sorted by the first field and then the second. For example, the SQL statement below sorts by ZipCode first and then Last Name. SELECT FirstName, LastName, ZipCode FROM tblemployees ORDER BY ZipCode, LastName; 2
Creating a SQL Query in Access Open the ExampleDB database and in the Queries window, choose Create a query in Design View. Close the Show Tables window without adding a table. You will see a SQL View icon on the left of the toolbar where you have seen the Design and Datasheet Views icons earlier. Click on the SQL View icon. The Design View window will become blank window ready to enter a SQL query. Let s write a simple SQL query to find the first and last names of all employees who live in South Carolina, sorted by last name. Before we write the query, let s think about what we need. Fields: Table: Criterion: Sort: FirstName, LastName, and State All of these fields are in tblemployees State = SC Sort by LastName We can easily turn these requirements into a SQL statement. Here it is: SELECT FROM WHERE ORDER BY FirstName, LastName, State tblemployees State= SC LastName; The use of single rather than double quotation marks around SC is required by SQL. Enter this query in the window. Again, the statement must be followed by a semicolon. Click on the exclamation mark in the top toolbar to run the query. Does it work? 3
If you choose Design View from the view menu on the top toolbar, you will see the Access Design View corresponding to this SQL statement. You can return to the SQL view from the same menu. Combining Criteria in a WHERE Clause In the previous lesson we wrote an Access query to find all the names of all employees, sorted by last name, who live in Spartanburg and who were hired before 1/1/2000. Let s write a SQL query to do this search. First, let s figure out what we need Fields: Table: Criteria: Sort: FirstName, LastName, City, HireDate All of these fields are in tblemployees City = Spartanburg and HireDate earlier than 1/1/2000 Sort by LastName This is slightly more complex than the previous statement because there are two criteria. We will include both criteria with an AND operator. SELECT FirstName, LastName, City, HireDate FROM tblemployees WHERE City= Spartanburg AND HireDate < #1/1/2000# ORDER BY LastName; 4
As in the Access criteria, the pound signs indicate that a quantity is a date. Enter this statement into the SQL View window and try the query. Does it work? Practice: Design a SQL query that lists first and last names of all employees who live in Spartanburg or Greer. Sort by City first and then by Last Name (Hint: Use OR instead of AND). Try it. Practice: Design a SQL query that lists all addresses (Street, City, State, Zip Code) with Zip Codes beginning with 293. Order by Zip Code (Hint: Think about Wildcard symbols. Use LIKE rather than an equal sign when you are using a wildcard.) Try it. Practice: Design a SQL query to list all employees who live in SC and who were hired in 2004. Order by Hire Date. (Hint: Think about the BETWEEN... AND... comparison operator.) Try it. Practice: Design a SQL query to list all employees who satisfy these two criteria: Department IDs either 100 or 102 Hired before January 1, 2004 Sort the list by Department ID. Careful. This one is harder than the others. You will need to group the OR part of the statement within parentheses. Try it. Using Multiple Tables in a SQL Statement You can use more than one table in a SQL statement by designating the table name associated with each field, tbltablename.fieldname. The table name is first, followed by a period, and then the field name. Let s write a SQL query to find the names and salaries of all employees, sorted by salary. As usual, let s figure out what we need. Fields: Table: Criteria: Sort: FirstName, LastName, Salary FirstName and Last Name in tblemployees, Salary in tblsalaries None Sort by Salary We need to look at the two tables and take note of the common element that defines the relationship between the two tables. In this case, it is the primary key in both tables, EmployeeID. 5
The two tables are joined by the common element, name EmployeeID in both tables. We specify this with an INNER JOIN statement as is illustrated in the SQL query below: SELECT tblemployees.firstname, tblemployees.lastname, tblsalaries.salary FROM tblemployees INNER JOIN tblsalaries ON tblemployees.employeeid = tblsalaries.employeeid ORDER BY tblsalaries.salary ; Note that the FROM section contains one table in the join and the INNER JOIN section contains the other. The ON section specifies the elements that relate the two tables. Try the SQL query above to see how it works. Practice: Write a SQL query to list the names of all members of the personnel department, sorting the list by Last Names. Try it. Practice: Write a SQL query to list the names of all exempt employees with a salary that is $40,000 or less. Sort the list by salaries in descending order. Why Use SQL? I am sure the question is on your lips, Other than to torture poor defenseless CS 101 students, what good is SQL? Access is hard enough! Practice: We want to produce the following query using tblemployees in EmployeesDB. List all employees with their Department ID List them as First Name, Last Name, Dept ID Sort them by Last Name first and then by First Name First do this with the Access Design View grid, as in Lesson 2. Is it easy to do? Now do the same query using a SQL statement. Which is easier the Design Grid or SQL? 6
Most database users will never need to use SQL statements, but there sometimes are good reasons to use SQL statements rather than Access s Design View grid 1. 1. SQL queries are faster than Access queries If you are dealing with a large database, such as Banner, that contains thousands of tables and hundreds of thousands of records, and has many concurrent users, performance matters. Working with SQL statements can make a difference. 2. There are SQL-specific queries that can do things you cannot with the Design View grid. Access has SQL specific queries that cannot be duplicated easily with the design grid. For example, pass-through queries allow you to look for data in other non-access databases. A SQL pass-through query will be sent directly to Banner (an Oracle database) without needing to use the Access engine. This improves performance immensely. 3. SQL queries are more flexible than those designed using the Design View Grid. The Practice problem you tried a moment ago is an example 1. Suppose you want to list names and Department IDs of employees. You would like the names to be displayed with the first name before the last, like we are accustomed to seeing them. You also would like to sort them by last name first and then by first name. It turns out that this is a bit of a problem using the Design View grid. If we put the first name before the last in the Design View grid, then the names will be sorted by first name first not how we want them sorted. If, on the other hand, we put the last name first in the Design View grid, then the sort will be done correctly, but they will not be displayed with the first name before the last. 1 Green, Martin. Access and SQL, Part 1: Setting the SQL Scene. Access Tips. 2003. 27-July 2005 <http://www.fontstuff.com/access/acctut14.htm> cctut14.htm> 7
There is a way to get around this, but it is a little cumbersome. Basically the Design View grid doesn t work well for this type of query. A simple SQL query handles this easily. The order of display is specified by the SELECT clause, whereas the sort order is specified by the ORDER BY clause. 8