Basic Syntax of SQL statements

Source: Internet
Author: User

Basic Syntax of SQL statements
Yin Hong wrote this article, but I can't help but stick it here for viewing information.
Because the original text is written in the word, the paragraph is a bit messy.

1. The complete syntax of the Select statement is:
Select [ALL | DISTINCT | DISTINCTROW | TOP]
{* | Talbe. * | [table.] field1 [AS alias1] [, [table.] field2 [AS alias2] [,…]}
FROM tableexpression [,…] [IN externaldatabase]
[Where…]
[Group by…]
[HAVING…]
[Order by…]
[With owneraccess option]
Note:
The Section enclosed by braces ([]) is optional. The section enclosed by braces ({}) indicates that one of them must be selected.

1. 1 FROM clause
The FROM clause specifies the field source in the Select statement. The FROM clause is followed by one or more expressions (separated by commas ), the expression can be a single table name, saved query, or compound result obtained by inner join, left join, or right join. If a table or query is stored IN an external database, specify its complete path after the IN clause.
For example, the following SQL statement returns all customers with orders:
Select OrderID, Customer. mermerid
FROM Orders MERs
Where Orders. CustomerID = Customers. CustomeersID

1. 2 ALL, DISTINCT, DISTINCTROW, TOP predicates
(1) ALL returns ALL records that meet the SQL statement conditions. If this predicate is not specified, the default value is ALL.
Example: Select ALL FirstName, LastName
FROM Employees
(2) DISTINCT if the selected fields of multiple records have the same data, only one is returned.
(3) If DISTINCTROW has repeated records, only one
(4) TOP displays several records at the beginning and end of the query. You can also return the percentage of records. This is to use the top n percent clause (where N represents the percentage)
For example, the maximum order amount of 5% is returned.
Select TOP 5 PERCENT *
FROM [Order Details]
Order by UnitPrice * Quantity * (1-Discount) DESC

I. 3 USE THE AS clause to get an alias for a field
If you want to get a new title for the returned column, or after calculating or summarizing the field, a new value is generated and you want to display it in a new column, it is retained with.
For example, if the returned FirstName field is named nick name
Select FirstName AS NickName, LastName, City
FROM Employees
For example, return a new column to show the inventory value.
Select ProductName, UnitPrice, UnitsInStock, UnitPrice * UnitsInStock AS valueInStock
FROM Products

II. The Where clause specifies the query conditions.

Ii. 1 Comparison Operators
Comparison operator meaning
= Equal
> Greater
<Less
> = Greater than or equal
<= Less than or equal
<> Not equal
!> Not greater
! <Not less
For example, return the order from January 1, January.
Select OrderID, CustomerID, OrderDate
FROM Orders
Where OrderDate> #1/1/96 # AND OrderDate <#1/30/96 #
Note:
In Mcirosoft jet SQL, dates are bounded. The date can also be replaced by the Datevalue () function. When comparing character data, you must add single quotation marks ''. Trailing spaces are ignored during comparison.
Example:
Where OrderDate> #96-1-1 #
It can also be expressed:
Where OrderDate> Datevalue ('2014/1/96 ')
Use the NOT expression to reverse the request.
For example, view the orders placed after January 1, January 1.
Where Not OrderDate <=# 1/1/96 #

2. Range 2 (BETWEEN and not)
BETWEEN... AND... The operator specifies a closed interval to be searched.
For example, an order from January 1, January to January 31, February is returned.
Where OrderDate Between #1/1/96 # And #2/1/96 #

Ii. 3 list (IN, not in)
The IN operator is used to match any value IN the list. An IN clause can replace a series of conditions connected by an OR clause.
For example, you need to find all customers who live in London, Paris, or Berlin.
Select CustomerID, CompanyName, ContactName, City
FROM MERs
Where City In ('London ', 'Paris', 'berlin ')

Ii. 4. pattern matching (LIKE)
The LIKE operator checks whether the value of a field containing string data matches a specified pattern.
Wildcard characters used in the LIKE Operator
Wildcard characters
? Any single character
* Any length of Characters
#0 ~ A single number between 9
[Character List] any value in the Character List
[! Character List] any value not in the Character List
-Specify the character range. The upper and lower limits are the values on both sides.
Example: return the customer whose zip code is between (171) 555-0000 and (171) 555-9999.
Select CustomerID, CompanyName, City, Phone
FROM MERs
Where Phone Like '( 171) 555 -####'
Style and meaning of the LIKE Operator
Invalid style meaning
LIKE 'a * 'a followed by any length of characters Bc, c255
LIKE '5
'5*5 555
LIKE '5? Any character between 5 and 5 is 55, 5wer5
LIKE '5 # 5' 5235,5005 5kd5, 5346
LIKE '[a-z]' any character between a-z 5, %
LIKE '[! 0-9] 'any character other than 0-9, 0, 1
LIKE '[[] '1 ,*

3. Sort the results using the order by clause
The ORDER clause sorts the query results by one or more (up to 16) fields, either ascending or descending. The default value is ascending. The ORDER clause is usually placed at the end of an SQL statement.
Multiple fields are defined in the ORDER clause.
Example:
Select ProductName, UnitPrice, UnitInStock
FROM Products
Order by UnitInStock DESC, UnitPrice DESC, ProductName
In the order by clause, you can replace the field name with the position number in the field selection list. You can mix the field name and position number.
For example, the following statement produces the same effect as the preceding one.
Select ProductName, UnitPrice, UnitInStock
FROM Products
Order by 1 DESC, 2 DESC, 3

4. Multi-Table query using connection relationships
Example: Find the names of suppliers and customers in the same city
Select Customers. CompanyName, Suppliers. ComPany. Name
FROM MERs, Suppliers
Where Customers. City = Suppliers. City
For example, find out the products and orders with the product inventory greater than the order quantity of the same product.
Select ProductName, OrderID, UnitInStock, Quantity
FROM Products, [Order Deails]
Where Product. productID = [Order Details]. ProductID
AND UnitsInStock> Quantity
Another method is to use the jnner join exclusive to Microsof jet SQL.
Syntax:
FROM table1 inner join table2
ON table1.field1 comparision table2.field2
Comparision is the comparison operator used by the Where clause.
Select FirstName, lastName, OrderID, CustomerID, OrderDate
FROM Employees
Inner join Orders ON Employees. EmployeeID = Orders. EmployeeID
Note:
Inner join cannot be used to connect Memo OLE Object Single Double data type fields.
JOIN multiple ON clauses in a JOIN statement
Syntax:
Select fields
FROM table1 inner join table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2 OR
ON table1.field3 compopr table2.field3
Yes.
Select fields
FROM table1 INNER JOIN
(Table2 inner join [(] table3
[Inner joer] [(] tablex [inner join]
ON table1.field1 compopr table2.field1
ON table1.field2 compopr table2.field2
ON table1.field3 compopr table2.field3
External connections return more records and keep unmatched records in the results. No matter there are no records that meet the conditions, all records on the other side are returned.
FROM table [LEFT | RIGHT] JOIN table2
ON table1.field1comparision table. field2
Use the left join to create an external join. All the data in the table on the left of the expression is displayed.
For example, all products are returned regardless of the order quantity.
Select ProductName, OrderID
FROM Products
Left join Orders ON Products. PrductsID = Orders. ProductID
The difference between the right join and the left join is that, no matter whether there are matching records in the left table, it returns all records from the left table.
For example, if you want to know the customer information and calculate the customer distribution in each region, you can use a right connection to return the customer information even if there are no customers in a region.
NULL values do not match each other. You can use an external connection to test whether the fields in a joined table have null values.
Select *
FROM talbe1
Left join table2 ON table1.a = table2.c

Iv. 1 use the Iif function in connection query to display null values with 0 values
Iif expression: Iif (IsNull (Amount, 0, Amout)
For example, whether the order is greater than or less than ¥50, a flag is returned.
Iif ([Amount]> 50 ,? Big order ?,? Small order ?)

Five grouping and summary query results
In SQL syntax, the GROUP BY and HAVING clauses are used to summarize data. The group by clause specifies which fields are grouped. After grouping records, the HAVING clause is used to filter these records.
Group by clause syntax
Select fidldlist
FROM table
Where criteria
[Group by groupfieldlist [HAVING groupcriteria]
Note: Microsoft Jet Database cannot group remarks or OLE object fields.
The Null Value in the group by field is used for grouping, but cannot be ignored.
No Null value is calculated in any SQL aggregate function.
The group by clause can contain up to ten fields, and the sorting priority is arranged from left to right.
For example, After grouping by title in the employee table of the 'wa 'region, find all titles with the same title with more than 1 employee.
Select Title, Count (Title) as Total
FROM Employees
Where Region = 'wa'
Group by Title
HAVING Count (Title)> 1
Accumulation functions in JET SQL
Significance of Aggregate functions
SUM () summation
AVG () Average Value
Number of records in the COUNT () Expression
COUNT (*) calculates the number of records
MAX
MIN minimum
Var variance
STDEV standard error
FIRST Value
LAST Value

6. Use Parameters to declare and create a parameter query
Syntax declared by Parameters:
PARAMETERS name datatype [, name datatype [,…]
Here, name is the identifier of the parameter. You can use the identifier to reference the parameter.
Datatype indicates the Data Type of the parameter.
You must place the PARAMETERS declaration before any other statements.
Example:
PARAMETERS [Low price] Currency, [Beginning date] datatime
Select OrderID, OrderAmount
FROM Orders
Where OrderAMount> [low price]
AND OrderDate> = [Beginning date]

7. Function Query
The so-called function query is actually an operation query, which can perform fast and efficient operations on the database. it selects matching data for the purpose of selecting a query and then processes the data in batches. function query includes update query, delete query, add query, and generate Table query.
VII. 1 update Query
The Update clause can change the data in one or more tables at the same time. It can also change the values of multiple fields at the same time.
Update query syntax:
Update table name
SET new value
Where Criterion
For example, the order volume of UK customers increased by 5% and the cargo volume increased by 3%.
Update OEDERS
SET OrderAmount = OrderAmount * 1.1
, Freight = Freight * 1.03
Where ShipCountry = 'U'

VII. 2 delete a query
The Delete clause allows you to Delete a large amount of outdated or redundant data.
Note: The query object is deleted as a whole record.
Syntax of the Delete clause:
Delete [Table name. *]
FROM source table
Where Criterion
Example: delete all Orders 94 years ago
Delete *
FROM Orders
Where OrderData <#94-1-1 #

VII. 3 append Query
The Insert clause can append one or more records to the end of one or more tables.
The INTO clause specifies the table that accepts the new record.
The valueS keyword specifies the data value included in the new record.
Syntax of the Insert clause:
Insetr into target table or query (Field 1, Field 2 ,...)
ValueS (value 1, value 2 ,...)
Example: Add a customer
Insert INTO Employees (FirstName, LastName, title)
ValueS ('Harry ', 'Washington', 'trainee ')

VII. 4 generate a table Query
All matching records can be copied to a new table at a time. A backup or copy of the records is usually created or serves as the basis of the report.
The Select INTO clause is used to create the query syntax for the generated table:
Select Field 1, Field 2 ,...
INTO new table [IN external database]
FROM source database
Where Criterion
For example, create an archive backup for the order
Select *
INTO OrdersArchive
FROM Orders

8. Joint Query
The UNION operation combines the results of multiple queries into a single result set for display.
General Syntax of UNION operations:
[Table] query 1 UNION [ALL] query 2 UNION...
Example: return the names and cities of all suppliers and customers in Brazil
Select CompanyName, City
FROM Suppliers
Where Country = 'Brazil'
UNION
Select CompanyName, City
FROM MERs
Where Country = 'Brazil'
Note:
By default, the UNION clause does not return repeated records. to display ALL records, add the ALL option.
The UNION operation requires that the query has the same number of fields. However, the field data types do not have to be the same.
You can use the group by clause or HAVING clause to GROUP each query parameter. to display the returned data in the specified order, you can use the oreer by clause at the end of the last query.

9 x Query
A query can calculate the sum, average, Count, or other sum of data. The data is grouped by two types of information: one is displayed on the left of the table, the other is displayed on the top of the table.
Microsoft Jet SQL uses the TRANSFROM statement to create a forward * Table query syntax:
TRANSFORM aggfunction
Select statement
Group by clause
Struct tfield [IN (value1 [, value2 [,…]) ]
Aggfounction refers to the SQL accumulation function,
Select the field as the title in the Select statement,
GROUP BY GROUP
Note:
The field or expression used to create a column title IN the query result set. The optional IN clause is used to limit its value.
Value indicates the fixed value of the created column title.
For example, the number of orders received by each employee in each quarter of 1996 is displayed:
TRANSFORM Count (OrderID)
Select FirstName & ''& LastName AS FullName
FROM Employees inner join Orders
ON Employees. EmployeeID = Orders. EmployeeID
Where DatePart ("yyyy", OrderDate) = '201312'
Group by FirstName & ''& LastName
Order by FirstName & ''& LastName
POVOT DatePart ("q", OrderDate) & 'quarterly'

10. subquery
A subquery can be understood as a set of queries. A subquery is a Select statement.

The value of the 10. 1 expression is compared with the single value returned by the subquery.
Syntax:
Expression comparision [ANY | ALL | SOME] (subquery)
Note:
Any and some predicates are synonyms and are used together with comparison operators (=, <, >,< =, >=. returns a Boolean value of True or False. ANY means that the expression is compared with a series of values returned by the subquery one by one. If a comparison produces a True result, ANY tests return a True value (both the result of the Where clause ), the current record corresponding to this expression will be included in the results of the primary query. the ALL test requires that the expression and a series of values returned by the subquery produce the True result before returning the True value.
For example, the unit price returned by the primary query is higher than the unit price of any product whose discount is greater than or equal to 25%.
Select * FROM Products
Where UnitPrice> ANY
(Select UnitPrice FROM [Order Details] Where Discount> 0.25)

10. 2. Check whether the expression value matches a value of a group returned by the subquery.
Syntax:
[NOT] IN (subquery)
For example, products whose inventory value is greater than or equal to 1000 are returned.
Select ProductName FROM Products
Where ProductID IN
(Select PrdoctID FROM [Order DEtails]
Where UnitPrice * Quantity & gt; = 1000)

10. 2 check whether subqueries return any records
Syntax:
[NOT] EXISTS (subquery)
Example: Search UK customers with EXISTS
Select ComPanyName, ContactName
FROM Orders
Where EXISTS
(Select *
FROM MERs
Where Country = 'uk 'AND
Customers. CustomerID = Orders. CustomerID)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.