Using AND in a Query: Step 1: Open Query Design From the Database window, choose Query on the Objects bar. The list of saved queries is displayed, as shown in this figure. Click the Design button. The query displays, as shown in this figure. Step 2: Add the First Criteria Type the first criteria in the Criteria row in the query design grid under the field you want to query. Use a simple matching query or set up a condition using the operators, greater than (>), less than (<), greater than or equal to (>=), or less than or equal to (<=). 1
Step 3: Add the Second Criteria Type the second criteria in the same Criteria row in the query design grid. For example, if you want to view customers with freight charges of a thousand or more who live in Alaska, you would enter >=1000 under Freight and AK under the ShipRegion field. When you use more than one criteria on the Criteria line of the query design grid, Access matches both. Customers who live in Alaska but don't have freight charges of $1,000 or more will not display in the results. Step 4: Narrow the Search As you continue to add criteria on the Criteria line, you are continuing to narrow the search. For example, if you add UPS under the ShipVia field in the above criteria, you would see only customers who live in Alaska, with freight charges of $1,000 or more, and use UPS to ship their freight. Access adds an implied AND between each of these criteria, narrowing down the results. 2
Using OR in a Query: Step 1: Open Query Design From the Database window, choose Query on the Objects bar. The list of saved queries is displayed, as shown in this figure. Click the Design button. The query displays, as shown in this figure. Step 2: Add the First Criteria Type the first criteria in the Criteria row in the query design grid under the field you want to query. Use a simple matching query or set up a condition using the operators, greater than (>), less than (<), greater than or equal to (>=), or less than or equal to (<=). 3
Step 3: Add the Second Criteria Type the second criteria in the Or row in the query design grid under the field you also want to include in the query. For example, if you want to view customers who live in Washington or who live in Alaska, you would type WA in the Criteria row under the State field in the query design grid. Then you would type AK in the Or row under the Sate field in the query design grid. When you view the results, you would see customers in both Washington and Alaska because the OR criteria widens the possible matches. Step 4: Mix AND and OR Criteria You can continue to add criteria on the Criteria line and the Or line to create complex search criteria to get to the exact information you desire. Step 5: Run the Query Simply click the View button to see the results of the query. 4
Using NOT in a Query: Step 1: Open Query Design From the Database window, choose Query on the Objects bar. The list of saved queries is displayed, as shown in this figure. Click the Design button. The query displays, as shown in this figure. Step 2: Use the NOT Criteria NOT criteria are simple to use in Access and help save time and errors. For example, if you want to see all the customers who live outside of the United States, you could list all the countries in the table separated by OR and run the query. However, if you added new customers in new parts of the world, you would have to remember to add them to the long list in the query, or they would be left out when you run the query. 5
A better way to set up the country query would be to type NOT "USA" in the Country field. Not only does this save time, but when new customers are added, they will automatically be included the next time you run the query. Step 3: Run the Query Simply click the View button to see the results of the NOT query. Creating a Simple Query in Microsoft Access Using Wizard Using Wizard Have you ever wanted to combine information from multiple tables in your database in an efficient manner? Microsoft Access offers a powerful query function with an easyto-learn interface that makes it a snap to extract exactly the information you need from your database. In this tutorial we'll explore the creation of a simple query. Let's explore the process step-by-step. Our goal in this tutorial is to create a query listing the names of all of our company's products, current inventory levels and the name and phone number of each product's supplier. Step 1. Open your database. Open the Northwind database on your computer. Step 2. Select the queries tab. This will bring up a listing of the existing queries that Microsoft included in the sample database along with two options to create new queries. Step 3. Double-click on "create query by using wizard". The query wizard simplifies the creation of new queries. We'll use it in this tutorial to introduce the concept of query creation. In later tutorials we'll examine the Design View, which facilitates the creation of more sophisticated queries. 6
Step 4. Select the appropriate table from the pull-down menu. When you select the pull-down menu, you'll be presented with a listing of all the tables and queries currently stored in your Access database. These are the valid data sources for your new query. In this example, we want to first select the Products table which contains information about the products we keep in our inventory. Step 5. Choose the fields you wish to appear in the query results. by either doubleclicking on them or by single clicking first on the field name and then on the ">" icon. As you do this, the fields will move from the Available Fields listing to the Selected Fields listing. Notice that there are three other icons offered. The ">>" icon will select all available fields. The "<" icon allows you to remove the highlighted field from the Selected Fields list while the "<<" icon removes all selected fields. In this example, we want to select the ProductName, UnitsInStock, and UnitsOnOrder from the Product table. 7
Step 6. Repeat steps 4 and 5 to add information from additional tables, as desired. In our example, we wanted to include information about the supplier. That information wasn't included in the Products table -- it's in the Suppliers table. Here's the power of a query! You can combine information from multiple tables and easily show relationships. In this example, we want to include the CompanyName and Phone fields from the Suppliers table. All you have to do is select the fields -- Access will line up the fields for you! Note that this works because the Northwind database has predefined relationships between tables. If you're creating a new database, you'll need to establish these relationships yourself. Step 7. Click on Next. Step 8. Choose the type of results you would like to produce. We want to produce a full listing of products and their suppliers, so choose the Detail option here. 8
Step 9. Click on Next. Step 10. Give your query a title. You're almost done! On the next screen you can give your query a title. Select something descriptive that will help you recognize this query later. We'll call this query "Product Supplier Listing." Step 11. Click on Finish. You'll be presented with the two windows below. The first window is the Query tab that we started with. Notice that there's one additional listing now -- the Product Supplier Listing we created. The second window contains our results -- a list of our company products, inventory levels and the supplier's name and telephone number! 9
Modifying a Query in Microsoft Access I. Open Query in Design View Our first step is to invoke the Design View for our query. Step 1. Select the appropriate query. From the Northwind database menu, single click on the query you wish to modify. In our case, choose the "Product Supplier Listing" query that we designed earlier. Step 2. Click the Design View icon. This icon appears in the upper left portion of the window. Immediately upon clicking this icon, you'll be presented with the Design View. 10
II. Adding Fields Adding a field is one of the most common query modifications. This is usually done to either display additional information in the query results or add criteria to the query from information not displayed in the query results. In our example, the purchasing department wanted the contact name of each product's supplier displayed. As this was not one of the fields in the original query, we must add it now. Step 1. Choose an open table entry. Look for an entry in the field row that does not contain any information. Depending upon the size of your window you may need to use the horizontal scroll bar at the bottom of the table to locate an open entry. Step 2. Select the desired field. Single click in the field portion of the chosen entry and a small black down arrow will appear. Click this once and you'll be presented with a list of currently available fields. Select the field of interest by single clicking on it. In our example, we want to choose the ContactName field from the Suppliers table (listed as Suppliers.ContactName). 11
III. Removing Fields Often, you'll need to remove unnecessary information from a query. If the field in question is not a component of any criteria or sort orders that we wish to maintain, the best option is to simply remove it from the query altogether. This reduces the amount of overhead involved in performing the query and maintains the readability of our query design. Step 1. Click on the field name. Single click on the name of the field you wish to remove in the query table. In our example, we want to remove the CompanyName field from the Suppliers table. Step 2. Open the Edit menu and select Delete Columns. Upon completion of this step the CompanyName column will disappear from the query table. IV. Adding Criteria We often desire to filter the information produced by a database query based upon the value of one or more database fields. For example, recall that our purchasing department was only interested in those products with a small inventory and no products currently on order. In order to include this filtering information, we can add criteria to our query in the Design View. Step 1. Select the criteria field of interest. Locate the field that you would like to use as the basis for the filter and single click inside the criteria box for that field. In our example, we'd first like to limit the query based upon the UnitsInStock field of the Products table. Step 2. Type the selection criteria. For a complete look at the allowable criteria, see these examples of criteria expressions from Microsoft. Continuing with our example, we want to limit our results to those products with less than ten items in inventory. To accomplish this, enter the mathematical expression "< 10" in the criteria field. Step 3. Repeat steps 1 and 2 for additional criteria. 12
We'd also like to limit our results to those instances where the UnitsOnOrder field is equal to zero. Repeat the steps above to include this filter as well. V. Hiding Fields Sometimes we'll create a filter based upon a database field but won't want to show this field as part of the query results. In our example, the purchasing department wanted to filter the query results based upon the inventory levels but did not want these levels to appear. We can't remove the fields from the query because that would also remove the criteria. To accomplish this, we need to hide the field. Step 1. Uncheck the appropriate Show box. It's that simple! Just locate the field in the query table and uncheck the Show box by single clicking on it. If you later decide to include that field in the results just single click on it again so that the box is checked. V. Sorting the Results The human mind prefers to work with data presented in an organized fashion. For this reason, we often desire to sort the results of our queries based upon one or more of the fields in the query. In our example, we want to sort the results alphabetically based upon the product's name. Step 1. Click the Sort entry for the appropriate field. Single click in the Sort area of the field entry and a black down arrow will appear. Single click on this arrow and you'll be presented with a list of sort order choices. Do this for the Products.ProductName field in our example. Step 2. Choose the sort order. For text fields, ascending order will sort alphabetically and descending order will sort by reverse alphabetic order. We want to choose ascending order for this example. 13
That's it! Close the design view by clicking the "X" icon in the upper right corner. From the database menu, double click on our query name and you'll be presented with the results shown below -- exactly what our purchasing department asked for! Check back with us next week for a look at creating a web interface for your database applications! SQL Fundamentals Introduction The Structured Query Language (SQL) comprises one of the fundamental building blocks of modern database architecture. SQL defines the methods used to create and manipulate relational databases on all major platforms. At first glance, the language may seem intimidating and complex but it's really not all that bad. In a series of articles over the next few weeks we'll explore the inner workings of SQL together. By the time we're through, you'll have the fundamental knowledge you need to go out there and start working with databases! This week, our first article in the SQL series provides an introduction to the basic concepts behind SQL and we'll take a brief look at some of the main commands used to create and modify databases. Throughout this article, please keep our goal in mind: we're trying to get the "big picture" of SQL -- not a mastery of the individual commands. We'll provide a few examples for illustrative purposes and explain the theory behind them, but don't feel frustrated if you can't write your own SQL commands after reading this article. We'll cover each of the major commands in detail in future weekly installments. SQL comes in many flavors. Oracle databases utilize their proprietary PL/SQL. Microsoft SQL Server makes use of Transact-SQL. However, all of these variations are based upon the industry standard ANSI SQL. In our tutorial series, we'll stick to ANSIcompliant SQL commands that will work on any modern relational database system. SQL commands can be divided into two main sub-languages. The Data Definition Language (DDL) contains the commands used to create and destroy databases and database objects. After the database structure is defined with DDL, database administrators and users can utilize the Data Manipulation Language to insert, retrieve and modify the data contained within it. In the next two sections of this article, we'll 14
explore DDL and DML in further detail. In future articles we'll take an in-depth look at specific SQL commands. Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and tables. These commands will primarily be used by database administrators during the setup and removal phases of a database project. They are beyond the scope of this course and would not be discussed. Data Manipulation Language The Data Manipulation Language (DML) is used to retrieve, insert and modify database information. These commands will be used by all database users during the routine operation of the database. Let's take a brief look at the basic DML commands: SELECT statement The SELECT command is the most commonly used command in SQL. It allows database users to retrieve the specific information they desire from an operational database. Syntax SELECT [predicate] { */table.*/[table.]field1 [AS alias1] [, [table.]field2 [AS alias2] [,...]]} FROM tableexpression [,...] [IN externaldatabase] [WHERE criteria ] [GROUP BY groupfieldlist ] [HAVING groupcriteria ] [ORDER BY field1 [ASC/DESC ][, field2 [ASC/DESC ]][,...]]] ] The SELECT statement has these parts: Part Description predicate One of the following predicates: ALL, DISTINCT, DISTINCTROW, or TOP. You use the predicate to restrict the number of records returned. If none is specified, the default is ALL. * Specifies that all fields from the specified table or tables are selected. table The name of the table containing the fields from which records are selected. field1, field2 The names of the fields containing the data you want to retrieve. If you include more than one field, they are retrieved in the order listed. alias1, alias2 The names to use as column headers instead of the original column names in table. tableexpression The name of the table or tables containing the data you want to retrieve. externaldatabase The name of the database containing the tables in tableexpression if criteria groupfieldlist they are not in the current database. Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records. The names of up to 10 fields used to group records. The order of the field names in groupfieldlist determines the grouping levels from the 15
groupcriteria field1, field2 Part ALL highest to the lowest level of grouping. An expression that determines which grouped records to display. The names of the fields on which to sort records Description Assumed if you do not include one of the predicates. The Microsoft Jet database engine selects all of the records that meet the conditions in the SQL statement. The following two examples are equivalent and return all records from the Employees table: SELECT ALL * FROM Employees ORDER BY EmployeeID; DISTINCT SELECT * FROM Employees ORDER BY EmployeeID; Omits records that contain duplicate data in the selected fields. To be included in the results of the query, the values for each field listed in the SELECT statement must be unique. For example, several employees listed in an Employees table may have the same last name. If two records contain Smith in the LastName field, the following SQL statement returns only one record that contains Smith: SELECT DISTINCT LastName FROM Employees; If you omit DISTINCT, this query returns both Smith records. If the SELECT clause contains more than one field, the combination of values from all fields must be unique for a given record to be included in the results. DISTINCTROW The output of a query that uses DISTINCT is not updatable and does not reflect subsequent changes made by other users. Omits data based on entire duplicate records, not just duplicate fields. For example, you could create a query that joins the Customers and Orders tables on the CustomerID field. The Customers table contains no duplicate CustomerID fields, but the Orders table does because each customer can have many orders. The following SQL statement shows how you can use DISTINCTROW to produce a list of companies that have at least one order but without any details about those orders: SELECT DISTINCTROW CompanyName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY CompanyName; If you omit DISTINCTROW, this query produces multiple rows for each company that has more than one order. TOP n [PERCENT] DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used in the query. DISTINCTROW is ignored if your query includes only one table, or if you output fields from all tables. Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose you want the names of the top 25 students from the class of 1994: SELECT TOP 25 FirstName, LastName FROM Students WHERE GraduationYear = 1994 ORDER BY GradePointAverage DESC; 16
If you do not include the ORDER BY clause, the query will return an arbitrary set of 25 records from the Students table that satisfy the WHERE clause. The TOP predicate does not choose between equal values. In the preceding example, if the 25 th and 26 th highest grade point averages are the same, the query will return 26 records. You can also use the PERCENT reserved word to return a certain percentage of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose that, instead of the top 25 students, you want the bottom 10 percent of the class: SELECT TOP 10 PERCENT FirstName, LastName FROM Students WHERE GraduationYear = 1994 ORDER BY GradePointAverage ASC; The ASC predicate specifies a return of bottom values. The value that follows TOP must be an unsigned Integer. table TOP does not affect whether or not the query is updatable. The name of the table from which records are retrieved. Let's take a look at a few examples, again using a table named Employees. The minimum syntax for a SELECT statement is: SELECT fields FROM table You can use an asterisk (*) to select all fields in a table. SELECT * FROM Employees Alternatively, you may want to limit the attributes (fields) that are retrieved from the database. For example, the Human Resources department may require a list of the last names of all employees in the company. The following SQL command would retrieve only that information: SELECT LastName FROM Employees If you want a different field name or a name is not implied by the expression used to generate the field, use the AS reserved word. The following example uses the title Birth to name the BirthDate field in the Employees table: SELECT BirthDate AS Birth FROM Employees; Whenever you use aggregate functions or queries that return ambiguous or duplicate Field object names, you must use the AS clause to provide an alternate name for the Field object. The following example uses the title HeadCount to name the returned Field: SELECT COUNT(EmployeeID) AS HeadCount FROM Employees; The WHERE clause can be used to limit the records that are retrieved to those that meet specified criteria. The CEO might be interested in reviewing the personnel records of 17
all highly paid employees. The following command retrieves all of the data contained within Employees for records that have a salary value greater than $50,000: SELECT * FROM Employees WHERE salary > $50000 If a field name is included in more than one table in the FROM clause, precede it with the table name and the. (dot) operator. In the following example, the Department field is in both the Employees table and the Supervisors table. The SQL statement selects departments from the Employees table and supervisor names from the Supervisors table: SELECT Employees.Department, Supervisors.SupvName FROM Employees INNER JOIN Supervisors WHERE Employees.Department = Supervisors.Department; If you want to determine an aggregate of a field using another field, then GROUP BY clause is what you would use. Consider the following example: SELECT CategoryID, Sum(UnitsInStock) FROM Products GROUP BY CategoryID HAVING Sum(UnitsInStock) > 100 And Like "BOS*"; In the above example, we are summing the field UnitsInStock for each individual CategoryID. This means that for each category, we get the sum of all the Units in Stock. HAVING is similar to WHERE, which determines which records are selected. After records are grouped with GROUP BY, HAVING determines which records are displayed: The HAVING clause filters records after they have been grouped. All fields in the SELECT field list must either be included in the GROUP BY clause or be included as arguments to an SQL aggregate function. A HAVING clause can contain up to 40 expressions linked by logical operators, such as And and Or. Summary values are omitted if there is no SQL aggregate function in the SELECT statement. Null values in GROUP BY fields are grouped and are not omitted. However, Null values are not evaluated in any SQL aggregate function. Use the WHERE clause to exclude rows you do not want grouped. Unless it contains Memo or OLE Object data, a field in the GROUP BY field list can refer to any field in any table listed in the FROM clause, even if the field is not included in the SELECT statement, provided the SELECT statement includes at least one SQL aggregate function. The Microsoft Jet database engine cannot group on Memo or OLE Object fields. INSERT statement The INSERT command in SQL is used to add records to an existing table. Returning to the personal_info example from the previous section, let's imagine that our HR 18
department needs to add a new employee to their database. They could use a command similar to the one shown below: Syntax Multiple-record append query: INSERT INTO target [(field1[, field2[,...]])] [IN externaldatabase] SELECT [source.]field1[, field2[,...] FROM tableexpression Single-record append query: INSERT INTO target [(field1[, field2[,...]])] VALUES (value1[, value2[,...]) The INSERT INTO statement has these parts: Part Description target The name of the table or query to append records to. field1, field2 Names of the fields to append data to, if following a target argument, or the names of fields to obtain data from, if following a source argument. externaldatabase The path to an external database. For a description of the path, see the IN clause. source The name of the table or query to copy records from. tableexpression The name of the table or tables from which records are inserted. This argument can be a single table name or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN operation or a saved query. value1, value2 The values to insert into the specific fields of the new record. Each value is inserted into the field that corresponds to the value's position in the list: value1 is inserted into field1 of the new record, value2 into field2, and so on. You must separate values with a comma, and enclose text fields in quotation marks (' '). Remarks You can use the INSERT INTO statement to add a single record to a table using the single-record append query syntax as shown above. In this case, your code specifies the name and value for each field of the record. You must specify each of the fields of the record that a value is to be assigned to and a value for that field. When you do not specify each field, the default value or Null is inserted for missing columns. Records are added to the end of the table. You can also use INSERT INTO to append a set of records from another table or query by using the SELECT... FROM clause as shown above in the multiple-record append query syntax. In this case, the SELECT clause specifies the fields to append to the specified target table. The source or target table may specify a table or a query. INSERT INTO is optional but when included, precedes the SELECT statement. If your destination table contains a primary key, make sure you append unique, non- Null values to the primary key field or fields; if you do not, the records will not be appended. 19
If you append records to a table with an AutoNumber field and you want to renumber the appended records, do not include the AutoNumber field in your query. Do include the AutoNumber field in the query if you want to retain the original values from the field. To find out which records will be appended before you run the append query, first execute and view the results of a select query that uses the same selection criteria. An append query copies records from one or more tables to another. The tables that contain the records you append are not affected by the append query. Instead of appending existing records from another table, you can specify the value for each field in a single new record using the VALUES clause. If you omit the field list, the VALUES clause must include a value for every field in the table; otherwise, the INSERT operation will fail. Use an additional INSERT INTO statement with a VALUES clause for each additional record you want to create. INSERT INTO personal_info VALUES ('bart','simpson',12345,$45000) Note that there are four values specified for the record. These correspond to the table attributes in the order they were defined: First_Name, Last_Name, Employee_ID, and Salary. UPDATE statement Creates an update query that changes values in fields in a specified table based on specified criteria. The UPDATE command can be used to modify information contained within a table, either in bulk or individually. Syntax UPDATE table SET newvalue WHERE criteria; The UPDATE statement has these parts: Part table newvalue criteria Description The name of the table containing the data you want to modify. An expression that determines the value to be inserted into a particular field in the updated records. An expression that determines which records will be updated. Only records that satisfy the expression are updated. Remarks UPDATE is especially useful when you want to change many records or when the records that you want to change are in multiple tables. You can change several fields at the same time. The following example increases the Order Amount values by 10% and the Freight values by 3% for shippers in the United Kingdom: 20
UPDATE Orders SET OrderAmount = OrderAmount * 1.1, Freight = Freight * 1.03 WHERE ShipCountry = 'UK'; On the other hand, our new employee Bart Simpson has demonstrated performance above and beyond the call of duty. Management wishes to recognize his stellar accomplishments with a $5,000 raise. The WHERE clause could be used to single out Bart for this raise: UPDATE personal_info SET salary = salary + $5000 WHERE employee_id = 12345 Important UPDATE does not generate a result set. Also, after you update records using an update query, you cannot undo the operation. If you want to know which records were updated, first examine the results of a select query that uses the same criteria, and then run the update query. Maintain backup copies of your data at all times. If you update the wrong records, you can retrieve them from your backup copies. DELETE statement Creates a delete query that removes records from one or more of the tables listed in the FROM clause that satisfy the WHERE clause. DELETE is especially useful when you want to delete many records. Syntax DELETE [table.*] FROM table WHERE criteria The DELETE statement has these parts: Part table table criteria Description The optional name of the table from which records are deleted. The name of the table from which records are deleted. An expression that determines which records to delete. Remarks You can use DELETE to remove records from tables that are in a one-to-many relationship with other tables. Cascade delete operations cause the records in tables that are on the many side of the relationship to be deleted when the corresponding record in the one side of the relationship is deleted in the query. For example, in the relationship between the Customers and Orders tables, the Customers table is on the one side and the Orders table is on the many side of the relationship. Deleting a record from Customers results in the corresponding Orders records being deleted if the cascade delete option is specified. 21
A delete query deletes entire records, not just data in specific fields. If you want to delete values in a specific field, create an update query that changes the values to Null. Important After you remove records using a delete query, you cannot undo the operation. If you want to know which records were deleted, first examine the results of a select query that uses the same criteria, and then run the delete query. Maintain backup copies of your data at all times. If you delete the wrong records, you can retrieve them from your backup copies. Unfortunately, our latest corporate earnings report didn't quite meet expectations and poor Anne has been laid off. The DELETE command with a WHERE clause can be used to remove his record from the Employees table: DELETE FROM Employees WHERE EmployeeID = 9 And finally, we're sorry to report that our business closed it's doors due to customers. We need to remove all of the data from the table. This SQL command will do the trick: DELETE FROM students 22