Published on

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Introduction to Microsoft Access Part 2 – QueriesOne of the main reasons why computerised databases are useful is their ability to find the information what you want quickly.1. SortingSorting simply puts the records in a sensible order.1. Click in the Field you want to Sort2. Either use the two buttons on the toolbar or select Sort from the Records menu.You need to select either Sort Ascending or Sort Descending.Sort Ascending sorts alphabetically from A-Z or numerically from smallest tolargest.Sort Descending sorts reverse-alphabetically from Z-A or numerically from largest tosmallest.Your TaskA limitation of the Sort function is when you have letters mixed with numbers. Tryentering these addresses into a table. Use the Sort function and record what happens:12 Bond Street24 Regent Street36 Ashford Road345 Benfleet Road140 Ash Avenue15 York Road16 Market StreetPage 1 of 19 04/07/12
  2. 2. 2. Finding Data in Tables1. Start by entering some more data into the Artists table, as follows:2. The simplest find of all is to click in a column and press CTRL+F (alternatively,select FIND from the EDIT menu.3. Enter some text to searchfor and click Find First4. By default, Access searches only in the field you clicked in before you started theFind. Untick the Search only the Current Field box if you want to search the wholetable.5. If you are finding that there are too many matches, use Search Up or SearchDown to search from the current record.6. By default, Access looks for records that contain only an exact match of your text.This means, for example, that if you searched for Rob your search would not findRobbie. Bill would not find Billy, and so on. If you want to widen your search, lookat the options in the Match box.7. Match Case makes the search case sensitive. With this option activated, a searchfor McNulty would find neither MCNULTY nor mcnulty.For DiscussionIn any Access search, you can search for a "wildcards". Wildcards match patterns.For example, you can use the # symbol to represent a number. # # ShipwrightsDrive would find 10 Shipwrights Drive but not 9 Shipwrights Drive. Why not?Page 2 of 19 04/07/12
  3. 3. 3. Filtering: Filter By SelectionFilters group together records that share something in common.There are three methods of filtering: filter by selection, filter by form and AdvancedFilter/Sort. We will go through each in turn.Note: Although the examples here are used on tables, filters can also be applied toforms, queries and records.1. Find one recording artist who is American and highlight the word American.2. Either click the Filter By Selection button on the toolbar or go to Records ►Filters ► Filter By Selection.You should now see a table listing only American musicians.3. Click the Remove Filter button on the toolbar to return to the complete tableYour TaskUsing the Filter By Selection tool, see if you can generate a list of British musicians.Is Robbie Williams in your list? Why not?Page 3 of 19 04/07/12
  4. 4. 4. Filtering: Filter By FormFilter By Form is more flexible than Filter By Selection, as we shall see.1. Start by clicking the Filter By Form button or go to Records ► Filters ► FilterBy Form.2. You should notice that a Look For tab is at the bottom of the window and also thatan upside down arrow appears in whichever field you select.3. Using the Filter By Form you can set Search Criteria, for example, you can tellAccess to look for Artists who are English Or British (so you make sure you includeRobbie Williams). You could ask for a list of Australians who are also called RolfHarris.4. Click the Apply Filter button when you want to run the filter and the RemoveFilter button when you want to return to the full table. The Clear Grid button lets you start again if you make a mistake. The Remove Filter button and the Apply Filter button both look like this. Because you only use them one at a time, this shouldn’t be confusing!Your TaskUsing Filter By Form, generate a list of Artists who are either American orAustralianPage 4 of 19 04/07/12
  5. 5. 5. Filtering: Advanced Filter/SortAdvanced Filter/Sort is almost a query. Its only limitation is that you can only workwith one table at a time.1. Start by going to Records ► Filters ► Filter By Form.2. You will see a Field List in the top half of the window and blank Query Grid inthe bottom half.3. Add the field or fields that you want to filter. You can add one or more fields. Adda field by double-clicking the field name in the Field List or by selecting it from thedrop-down list.If you want to add all the fields at once, double click on the heading in the Field Listand drag the fields to the Query Grid.4. You can set an Ascending or Descending sort for each field. This will control theway the order in which the filter results are listed. If more than one field is selected,the Sort will work from left to right in the Query Grid.5. You can set your search criteria in inverted commas. This search is going to lookfor artists who are Australian or American.Page 5 of 19 04/07/12
  6. 6. Select Delete Columns from the Edit menu, if you want to remove a column from theQuery Grid.Click the Clear Grid button if you want to clear the whole Query Grid.Click the Apply Filter button to run the filter and the Remove Filter button to returnto the full table.Click the Save As Query button, if you want to save the filter for later use.Boolean OperatorsAND Finds examples of both e.g. American AND Australian finds artists who are both American and Australian (will produce zero results) OR Finds examples of either e.g. American OR Australian finds records artists who are either American or Australian IS Finds exact matches only e.g. IS Rolf Harris finds records which contain both namesLIKE Finds any record that contains e.g. LIKE Rolf finds any artist called the term somewhere. Rolf > Greater than e.g. in a money or field <30 would show all numbers below 30 < Less than e.g. >30 lists all numbers over 30 > = Greater than or equal to e.g. >=30 lists all numbers from 30 < = Less than or equal to e.g. <=30 lists all numbers that are 30 or less than 30 <> Not Equal e.g. <> 30 lists all numbers except 30 = Equals e.g. =30 lists only 30Your TaskOpen a larger database, such as the Northwind database (this is a sample databasethat Microsoft supply with Access.Open the Products table and do an Advanced Filter/Sort to find: • Items with more than 50 units in stock • Condiments that cost more than $20.00 • Seafood products that come from Escargots Nouveaux or Tokyo Traders or New England Seafood Cannery of which there are least 30 units in stock.For DiscussionArithmetic operators can be applied to text and date fields. For example, LASTNAME >"G" finds everyone with surnames from G to Z. Why doesnt it pick up AliG?Page 6 of 19 04/07/12
  7. 7. 6. How to Create a Simple QueryCreating a query is easier than using Advanced Filter/Sort because: • The results of the query are automatically saved. • You can use the Simple Query Wizard to design the query • You can use multiple tables1. Click on the Queries tab of the Database Window.2. Click the New button and select Simple Query Wizard.3. Choose your tables and fields.4. If you want to add sorting and search criteria, you must open the Query in DesignView.5. A very useful feature to note is the Top Values box, into which you can type anumber or a percentage. Click the Run button to run the QueryYour TaskUsing the Northwind database, create a query to show the 20 most expensiveproducts.Page 7 of 19 04/07/12
  8. 8. 7. More Complex Queries1. You can design a query that combines fields from more than one table, as long asthe tables are related. Create the relationships before you create the query.2. You can create a query to show items between two values. For example, thefollowing Query shows orders between two specified dates:Your TaskUsing the Northwind database, create a query to show all orders in the second half of1996. Use the Customers and the Orders tables to show the details of who madethese orders.3. Boolean Operators can be used across columns. It is important to remember thedifference between AND/OR operations.AND operations restrict your search. OR operations widen the search.You can combine AND/OR operations. The query below looks for orders that weremade between two dates AND were made by customers from the UK OR France ORCanada.Page 8 of 19 04/07/12
  9. 9. Your Task1. Open the Query from the previous task2. Make sure the Country field is included in the query. Add it if necessary.3. Restrict the query to show only orders made by customers in Germany or Denmarkor Austria.4. Click the Design View button to make a further change to your search criteria.5. Refine your query so that it shows orders made by customers in Germany orDenmark or Austria AND with the company name “Drachenblut Delikatessen” (thequery should show only one order).4. Using the OR operator in one column is easy but it becomes more complicated if.If you want to widen the search by adding an OR over several columns, you need toput the OR on a separate line.For example, this query shows orders made between two dates and all orders made byLondon companies:Your Task1. In the example above, what would be the result if “London” were put in theCriteria row?2. How good a salesperson is Nancy Davolio? Produce a query to show all ordersthat she took in 1994 that were over £50 in value.Page 9 of 19 04/07/12
  10. 10. 8. Counting QueriesTo get your queries to do calculations, you start the query as normal, select the tablesand fields you are going to use and then press the Sigma Button (∑) to make theTotal Row appear.You need to have a field or fields to Group By. This function tells Access that youwant to organise the information you are displaying into groups. You can group byseveral fields. You also need a field on which to perform a functionThe Count function simply tells you how many records are in each group. Forexample, the following query tells you how many customers are in each country:The following query will add together the daily value of UK orders, using the Sumfunction:Your Task1. Using your Music database, do a query to count how many different artists youhave in your database.2. Using the Northwind database, calculate the total value of all orders made in1996.Page 10 of 19 04/07/12
  11. 11. You can use a Search Criteria in any field, including a Group By field. Thefollowing query, searches for products that cost more than $100 Access Functions and What They DoGroup By Organises the query results Sum Adds up all the values in the field Avg Calculates the average values Min Returns the lowest value Max Returns the highest value Count Shows the number of records that match the query criteria First Returns the first value that Access finds Last Returns the last value that Access findsExpression Creates a calculated field Where Uses the field as part of the search criteria but does not display the field itself in the results of the queryYour Task1. Create a list of products that cost less than $502. Find the average price of Northwind’s products3. Show the most expensive product onlyPage 11 of 19 04/07/12
  12. 12. 9. Crosstab QueriesCrosstab queries are used to summarise data in tables. It has a rows and columnsformat, where you can think of each row as a record and each column as a fielddescribing that record. Unlike a table, however, there is an additional column thatperforms a calculation on the data.For example, you might create a crosstab query based on a table of sales orders.Products could be shown in rows and the Order Date in columns. You would alsohave a calculating column to Sum the values. The calculating column would providea total value for each product.A crosstab query can be based on tables or queries.1. You want to show the total value of the sales of each of Northwind’s products foreach year. First, create a query that combines data from the Orders and OrderDetails tables. You need the name of the product, the dates on which the product wasordered and the value of each order.2. Start the Crosstab Query Wizard.3. Select the query that you just created.4. You want to use the name of the product as the row heading.5. Use the order date for the column headings.6. Group the orders together by year.7. The Wizard then asks you what number you want to be calculated at theintersection of each row and column. You want to add together the value of theorders.Page 12 of 19 04/07/12
  13. 13. 10. Calculated FieldsA calculated field takes numbers from other fields in the query and performs acalculation on them.You can add a calculated field to a query, as long as you include in the query all thedata that the calculated field needs to perform its calculation.A calculated field can take data from more than one field.Calculated fields are ideal for performing “What if?” queries. For example, “whatwould our prices be if we increased all prices by 5%?”1. To answer this question, use the Northwind database and create a new query usingthe Products Table.2. You need the name of the product and the price of the product in the query.3. Type [UnitPrice]*1.05 as the field name in a new field:4. Run the query by clicking the Run Button. You will notice that your field namehas been given the name Expr1, which isn’t very descriptive and the numbers in thecolumn are not formatted as currency. Click the Design View button to remedy this.5. Double click Expr1 to select it and change the name to New Price.6. Click the Properties ButtonChange the Format of the field toCurrency.In the Description Box type: Showsprices raised by 5%. Close theProperties.Page 13 of 19 04/07/12
  14. 14. 7. Run the Query again and you will see the effect of your changes. When you clickin the New Price field, you will see the Description Text appear in the Status Bar atthe bottom-left of the Access window.Your TaskThe accounting department at Northwind want to know the value of each product thatis on order. Produce a query with a calculated field that will show this.8. Of course, the company could be awkward and reduce the prices by 4.5%, and thenthey might change their minds again. This needn’t be a worry to you if you makeAccess ask for a percentage value before running the calculation.To achieve this, simply make up the name of a field, for example “PercentIncrease”and include that in the expression in place of the figure. For example: New Price: [UnitPrice]*[Percent Increase]Now, when the query runs, it asks for a percentage increase and calculates the resultsaccordingly.Your TaskNorthwind are considering reducing their prices for a month. Produce a query with acalculated field that will allow the accounting department to see the effect of apercentage decrease in the value of orders.9. You can calculate with text fields as well as with numbers. A common use for thisis when you want to combine the FirstName and LastName fields. You wouldsimply enter: [FirstName]+" "+[LastName]N.B. the space between the quotation marks tells Access to leave a space between firstname and last name.Your TaskCreate a list of customers with their titles in brackets. For example:Maria Anders (Sales Representative)Hint: Click the Build button on the toolbar to use the Expression Builder.Page 14 of 19 04/07/12
  15. 15. 11. Other Types of QueriesA Select Query is the commonest type of query. It answers questions about yourdata.An Action Query is a query that makes changes to your data.Simple jobs dont need complicated solutions. If you want to change every instanceof a word or phrase, throughout a field, you can open a table, select a field and thenselect Replace from the Edit Menu (or use CRTL+H).In Find What: enter a word orphrase to search for.In Replace With: enter a word orphrase to replace it with.The other options in this dialog boxare the same as for the Find feature.Your TaskIn the Customers Table of the Northwind Database change every example of theentry Owner to Proprietor.More complicated and widespread changes should bemade with the appropriate type of Query. When youcreate a new query, Access gives you a Select Query.You can change the Query Type by opening the QueryMenu and selecting a different type of query or you canuse the Query Type drop-down list.You will recognise the Crosstab Query because you have used it before.The last four types of queries are listed with an exclamation mark to remind you thatthey actually change the way your information is organised. You should not run thesequeries unless you have first previewed the changes and unless you also have abackup.The Run button executes the query. All changes are saved automatically.The View button allows you to preview the query without saving thechanges.Page 15 of 19 04/07/12
  16. 16. 12. The Delete QueryThe delete query is the easiest type of action query to use and it is also the mostdangerous!1. Create a normal select query and add the fields you want. Preview the query whenfinished and click the View button to preview the changes.2. Change the Query type from Select to Delete. You will notice that the Sort linechanges to a Delete line.3. Enter your criteria to delete. The following example, will remove records ofcustomers located in France or Canada.4. Click the View button and you will see a list of records that would be deleted ifyou were brave enough to click the Run button. If you are sure you want to deletethese records, click the Design button and then click the Run button. Access willgive you one last chance to change your mind and then your records will be trashed.Your TaskIn an act of blatant ageism, Northwind decide to sack all employees who were bornbefore 1960. Create a Delete query that will remove these employees from thedatabase. Preview the results but dont run the query.Page 16 of 19 04/07/12
  17. 17. 13. The Update QueryAn update query allows you to create a query to select records and then change thoserecords according to an instruction.1. Create a select query first, preview it and then change the query type to UpdateQuery. You will notice that the Sort line changes to an Update line.2. Enter an instruction in the Update Line tellingAccess what to do with the records you haveselected.This query will apply a 10% discount to allproducts over $100.3. Clicking the View button will show you a list of the records that will be changed,should you decide to click the Run button.Your TaskIncrease the prices of all products in the Northwind Database that are over $50 by10%4. The other query types are less commonly used. Once you have got the hang of theDelete Query and the Update Query, these should not cause you too manyproblems: Make Table Query Saves the results of a query as an additional table. This is useful for exporting information to another database. Append Query Allows you to add information from a query to an existing table. In the Criteria line, you could, for example, append only those customers with unpaid bills. Find Duplicates From the results of a Find Duplicates query, you can Query determine if there are duplicate records in a table, or determine which records in a table share the same value. Use the Find Duplicates Query Wizard. Find Unmatched Using the Find Unmatched Query Wizard, you can find Query records in one table that dont have related records in another table. For example, you can find customers who dont havePage 17 of 19 04/07/12
  18. 18. orders. Use the Find Unmatched Query Wizard.14. Keyboard ShortcutsF2 Select an entire fieldCtrl+; Insert the Current DateCtrl+: Insert the Current TimeCtrl+Enter Insert a Line Break (use it in a memo or large text field)Ctrl++ Add New RecordCtrl+- Delete the Current RecordShift+Enter Save the RecordCtrl+Z Undo the last change you made (dont rely on this)Ctrl+Enter Open the selected object in Design ViewAlt+F4 Quit Access15. Summary (from the Access Help file)Page 18 of 19 04/07/12
  19. 19. Page 19 of 19 04/07/12