Monday, December 31, 2018

Access SQL: basic concepts, vocabulary, and syntax

Access SQL: basic concepts, vocabulary, and syntax

When you want to retrieve data from a database, you ask for the data by using Structured Query Language, or SQL. SQL is a computer language that closely resembles English, but that database programs understand. Every query that you run uses SQL behind the scenes.

Understanding how SQL works can help you create better queries, and can make it easier for you to understand how to fix a query that is not returning the results that you want.

This is one of a set of articles about Access SQL. This article describes the basic use of SQL to select data, and uses examples to illustrate SQL syntax.

In this article

What is SQL?

Basic SQL clauses: SELECT, FROM, and WHERE

Sorting the results: ORDER BY

Working with summarized data: GROUP BY and HAVING

Combining query results: UNION

What is SQL?

SQL is a computer language for working with sets of facts and the relationships between them. Relational database programs, such as Microsoft Office Access, use SQL to work with data. Unlike many computer languages, SQL is not difficult to read and understand, even for a novice. Like many computer languages, SQL is an international standard that is recognized by standards bodies such as ISO and ANSI.

You use SQL to describe sets of data that can help you answer questions. When you use SQL, you must use the correct syntax. Syntax is the set of rules by which the elements of a language are correctly combined. SQL syntax is based on English syntax, and uses many of the same elements as Visual Basic for Applications (VBA) syntax.

For example, a simple SQL statement that retrieves a list of last names for contacts whose first name is Mary might resemble this:

SELECT Last_Name
FROM Contacts
WHERE First_Name = 'Mary';

Note: SQL is not only used for manipulating data, but also for creating and altering the design of database objects, such as tables. The part of SQL that is used for creating and altering database objects is called data-definition language (DDL). This topic does not cover DDL. For more information, see the article Create or modify tables or indexes by using a data-definition query.

SELECT statements

To describe a set of data by using SQL, you write a SELECT statement. A SELECT statement contains a complete description of a set of data that you want to obtain from a database. This includes the following:

  • What tables contain the data.

  • How data from different sources is related.

  • Which fields or calculations will produce the data.

  • Criteria that data must match to be included.

  • Whether and how to sort the results.

SQL clauses

Like a sentence, a SQL statement has clauses. Each clause performs a function for the SQL statement. Some clauses are required in a SELECT statement. The following table lists the most common SQL clauses.

SQL clause

What it does

Required

SELECT

Lists the fields that contain data of interest.

Yes

FROM

Lists the tables that contain the fields listed in the SELECT clause.

Yes

WHERE

Specifies field criteria that must be met by each record to be included in the results.

No

ORDER BY

Specifies how to sort the results.

No

GROUP BY

In a SQL statement that contains aggregate functions, lists fields that are not summarized in the SELECT clause.

Only if there are such fields

HAVING

In a SQL statement that contains aggregate functions, specifies conditions that apply to fields that are summarized in the SELECT statement.

No

SQL terms

Each SQL clause is composed of terms — comparable to parts of speech. The following table lists types of SQL terms.

SQL term

Comparable part of speech

Definition

Example

identifier

noun

A name that you use to identify a database object, such as the name of a field.

Customers.[Phone Number]

operator

verb or adverb

A keyword that represents an action or modifies an action.

AS

constant

noun

A value that does not change, such as a number or NULL.

42

expression

adjective

A combination of identifiers, operators, constants, and functions that evaluates to a single value.

>= Products.[Unit Price]

Top of Page

Basic SQL clauses: SELECT, FROM, and WHERE

A SQL statement takes the general form:

SELECT field_1
FROM table_1
WHERE criterion_1
;

Notes: 

  • Access ignores line breaks in a SQL statement. However, consider using a line for each clause to help improve the readability of your SQL statements for yourself and others.

  • Every SELECT statement ends with a semi-colon (;). The semi-colon can appear at the end of the last clause or on a line by itself at the end of the SQL statement.

An example in Access

The following illustrates what a SQL statement for a simple select query might look like in Access:

SQL object tab showing a SELECT statement

1. SELECT clause

2. FROM clause

3. WHERE clause

This example SQL statement reads "Select the data that is stored in the fields named E-mail Address and Company from the table named Contacts, specifically those records in which the value of the field City is Seattle."

Let's look at the example, one clause at a time, to see how SQL syntax works.

The SELECT clause

SELECT [E-mail Address], Company

This is the SELECT clause. It consists of an operator (SELECT) followed by two identifiers ([E-mail Address] and Company).

If an identifier contains spaces or special characters (such as "E-mail Address"), it must be enclosed in square brackets.

A SELECT clause does not have to say which tables contain the fields, and it cannot specify any conditions that must be met by the data to be included.

The SELECT clause always appears in front of the FROM clause in a SELECT statement.

The FROM clause

FROM Contacts

This is the FROM clause. It consists of an operator (FROM) followed by an identifier (Contacts).

A FROM clause does not list the fields to be selected.

The WHERE clause

WHERE City="Seattle"

This is the WHERE clause. It consists of an operator (WHERE) followed by an expression (City="Seattle").

Note: Unlike the SELECT and FROM clauses, the WHERE clause is not a required element of a SELECT statement.

You can accomplish many of the actions that SQL enables you to do by using SELECT, FROM, and WHERE clauses. More information about how you use these clauses is presented in these additional articles:

Top of Page

Sorting the results: ORDER BY

Like Microsoft Excel, Access lets you sort query results in a datasheet. You can also specify in the query how you want to sort the results when the query is run, by using an ORDER BY clause. If you use an ORDER BY clause, it is the last clause in the SQL statement.

An ORDER BY clause contains a list of the fields that you want to use for sorting, in the same order that you want to apply the sort operations.

For example, suppose that you want your results sorted first by the value of the field Company in descending order, and  — if there are records with the same value for Company — sorted next by the values in the field E-mail Address in ascending order. Your ORDER BY clause would resemble the following:

ORDER BY Company DESC, [E-mail Address]

Note: By default, Access sorts values in ascending order (A-Z, smallest to largest). Use the DESC keyword to sort values in descending order instead.

For more information about the ORDER BY clause, see the topic ORDER BY Clause.

Top of Page

Working with summarized data: GROUP BY and HAVING

Sometimes you want to work with summarized data, such as the total sales in a month, or the most expensive items in an inventory. To do this, you apply an aggregate function to a field in your SELECT clause. For example, if you want your query to show the count of e-mail addresses listed for each company, your SELECT clause might resemble the following:

SELECT COUNT([E-mail Address]), Company

The aggregate functions that you can use depend on the type of data that is in the field or expression that you want to use. For more information about the available aggregate functions, see the article SQL Aggregate Functions.

Specifying fields that are not used in an aggregate function: The GROUP BY clause

When you use aggregate functions, you usually must also create a GROUP BY clause. A GROUP BY clause lists all the fields to which you do not apply an aggregate function. If you apply aggregate functions to all the fields in a query, you do not have to create the GROUP BY clause.

A GROUP BY clause immediately follows the WHERE clause, or the FROM clause if there is no WHERE clause. A GROUP BY clause lists the fields as they appear in the SELECT clause.

For example, continuing the previous example, if your SELECT clause applies an aggregate function to [E-mail Address] but not to Company, your GROUP BY clause would resemble the following:

GROUP BY Company

For more information about the GROUP BY clause, see the topic GROUP BY Clause.

Limiting aggregate values by using group criteria: the HAVING clause

If you want to use criteria to limit your results, but the field that you want to apply criteria to is used in an aggregate function, you cannot use a WHERE clause. Instead, you use a HAVING clause. A HAVING clause works like a WHERE clause, but is used for aggregated data.

For example, suppose that you use the AVG function (which calculates an average value) with the first field in your SELECT clause:

SELECT COUNT([E-mail Address]), Company

If you want the query to restrict the results based on the value of that COUNT function, you cannot use a criteria for that field in the WHERE clause. Instead, you put the criteria in a HAVING clause. For example, if you only want the query to return rows if there are more than one e-mail addresses associated with the company, the HAVING clause might resemble the following:

HAVING COUNT([E-mail Address])>1

Note: A query can have a WHERE clause and a HAVING clause — criteria for fields that are not used in an aggregate function go in the WHERE clause, and criteria for fields that are used with aggregate functions go in the HAVING clause.

For more information about the HAVING clause, see the topic HAVING Clause.

Top of Page

Combining query results: UNION

When you want to review all the data that is returned by several similar select queries together, as a combined set, you use the UNION operator.

The UNION operator lets you combine two SELECT statements into one. The SELECT statements that you combine must have the same number of output fields, in the same order, and with the same or compatible data types. When you run the query, data from each set of corresponding fields is combined into one output field, so that the query output has the same number of fields as each of the select statements.

Note: For the purposes of a union query, the Number and Text data types are compatible.

When you use the UNION operator, you can also specify whether the query results should include duplicate rows, if any exist, by using the ALL key word.

The basic SQL syntax for a union query that combines two SELECT statements is as follows:

SELECT field_1
FROM table_1
UNION [ALL]
SELECT field_a
FROM table_a
;

For example, suppose that you have a table named Products and another table named Services. Both tables have fields that contain the name of the product or service, the price, warranty or guarantee availability, and whether you offer the product or service exclusively. Although the Products table stores warranty information, and the Services table stores guarantee information, the basic information is the same (whether a particular product or service includes a promise of quality). You can use a union query, such as the following, to combine the four fields from the two tables:

SELECT name, price, warranty_available, exclusive_offer
FROM Products
UNION ALL
SELECT name, price, guarantee_available, exclusive_offer
FROM Services
;

For more information about how to combine SELECT statements by using the UNION operator, see Combine the results of several select queries by using a union query.

Top of Page

10 comments:

  1. We are offering an investment program where you can earn 5 times your investment in 7 days for example you invest $1500 in 7 days you get $7500 It’s 100% genuine and payouts are sent into your bitcoin wallet immediately after trade …. Stop falling for scams and start earning good profit with a help of a professional trader send a Message now +27633586789 OR Email: wilsontradeszone@gmail.com to get started

    ReplyDelete
  2. Please. I quickly want to use this medium to share a testimony on how God directed me to a real loan lender who has transformed my life from grass to grace, from being poor to a rich man who can now boast of a healthy and wealthy life without stress or financial difficulties. After so many months of trying to get a loan on the internet and was scammed the sum of $2,200, I became so desperate in getting a loan from a legit loan lender online who will not add to my pains, Then i decided to contact a friend of mine who recently got a loan online and we discussed about the issue and to our conclusion he told me about a loan company called {CREDIT UNION PRIVATE FINANCE COMPANY LIMITED} So i applied for a loan sum of ($45,000.00 USD) with low interest rate so the loan was approved easily without stress and all the preparations were made concerning the loan transfer and in less than three(3) days the loan was deposited into my bank account i thought it was a joke until i received a call from my bank that my account have been credited with $45,000.00 USD. I became so happy that finally God answered my prayers by directing me to a real loan lender who was able to grant my heart's desires. Big thanks to {CREDIT UNION PRIVATE FINANCE COMPANY LIMITED } for making life reasonable for me so i am advising everybody who is interested in getting a loan to kindly contact Them via email creditunion16@gmail.com, That was how i was able to get my loan, So i was able to pay off my bills. So thanks as you took out your time to read about my success story and i pray god will also do his will in your life as you request for yours.

    ReplyDelete
  3. While considering a parttime .net engineer to recruit there is a sure range of abilities to look for. A .net full stack engineer independent up-and-comer should be skilled with the accompanying:

    HTML - A .net engineer parttime, whether it is an independent junior .net designer, or an asp.net independent engineer should have serious areas of strength for an of one of the most strong dialects to foster a site page to effectively learn through.
    Bootstrap - system to plan a website page
    CSS - CSS is about style and great searches for the site
    jQuery - a cordial method for carrying JavaScript to the site for more intuitive experience
    JavaScript - object-situated prearranging language a .net engineer parttime will utilize chiefly for creating applications.
    Precise - A .net developer independent is profoundly esteemed for having skill in working Rakish usefulness like start to finish tooling, definitive layouts, and reliance infusion.
    AJAX - The innovation that grants advancement of quicker and substantially more intuitive applications with the help of XML, JS, HTML, and CSS.
    C# - The language for running complex codes.A independent asp.net web designer is expected to be familiar with it, particularly while hoping to improve an independent net engineer hourly rate.
    Information base - MS-SQL Waiter, MySQL Waiter, Prophet capability will serve a full-stack independent .Net engineer, an independent asp.net developer, or a .net designer independent junior to guarantee that a .net developer hourly rate will get repaid modestly (yet the manner in which the organization actually feels OK with).
    .NET Center - An asp.net engineer independent, a full-stack independent .Net software engineer, and a .net programming designer parttime should be capable with a .Net Center highlights (order line devices, Microsoft support, cross-stage, across engineering consistency, similarity, and organization adaptability)>> .net developer salary per hour

    ReplyDelete
  4. Hello! Hiring IT specialists for your company or project has many advantages and many companies around the world choose to hire remote employees to save their budget. Use the services of staff augmentation agency because we have been providing remote employees to clients all over the world for many years!

    ReplyDelete
  5. Outsourcing companies from Ukraine are a very profitable solution when you need to pay attention to the angular developer salary. Come to us and you will be able to choose a specialist you are interested in or assemble a whole development department that will work smoothly on a remote basis according to your financial limit!

    ReplyDelete
  6. Are you looking for devops cloud automation services for your business? Then I recommend that you get more information about it directly from this link! Here you hire an experienced employee from Ukraine for basic outsourcing or a whole team, depending on your needs, preferences and the required skill set of candidates.

    ReplyDelete
  7. If you think that you have too many requirements and wishes for an employee, our company will be able to select and provide an expert in any case, as each specialist is carefully selected and checked. We provide and recommend the dedicated offshore development center because of its quality and advantages, despite the fact that it is quite new.

    ReplyDelete
  8. Hello! A popular and most proven method of guided AI training is the provision of previously prepared training datasets from our specialists. data labeler highlights the necessary objects for your AI on the information provided. If you are interested in hiring these setlists, then they have a lot of experience in working with this type of training.

    ReplyDelete
  9. Hello! If you want to hire a data labeling and annotation services specialist, then I recommend that you do not waste time selecting a specialist yourself, because this process can drag on for a long time and spend a lot of your budget. Contact us because we have vast experience in remotely hiring data labeling specialists!

    ReplyDelete
  10. An automatic paragraph writer is a time-saving tool that assists in the process of crafting well-structured essays. It generates coherent and logically organized paragraphs, ensuring a smooth flow of ideas and seamless transitions. By utilizing an automatic paragraph writer, writers can focus on developing their arguments and expressing their thoughts effectively, without getting bogged down by the complexities of paragraph structuring.

    ReplyDelete