SQL query statement Essence

Source: Internet
Author: User
SQL query statement Essence

1. Simple Query
A simple Transact-SQL query only includes the select list, from clause, and where clause. They respectively describe the queried columns and the queried
Tables or views, and search conditions.
For example, the following statement queries the nick name and email fields in the testtable table with the name "Zhang San.
Select nickname, email
From testtable
Where name = 'zhangsan'

(1) Select a list
Select_list indicates the queried column. It can be a list of column names, asterisks, expressions, and variables (including local variables ).
And global variables.

1. Select all columns
For example, the following statement shows the data of all columns in the testtable table:
Select *
From testtable

2. Select some columns and specify their display order
The data in the query result set is arranged in the same order as the column name in the selected list.
For example:
Select nickname, email
From testtable

3. Change the column title
In the selection list, you can re-specify the column title. Definition Format:
Column Title = column name
Column name column title
If the specified column title is not in the standard identifier format, use the quotation mark ("). For example, the following statement uses Chinese characters to display Columns
Title:
Select nickname = nickname, email = Email
From testtable

4. Delete duplicate rows
Use the all or distinct option in the SELECT statement to display all rows that meet the conditions in the table or delete duplicate data rows. The default value is
Is all. When the distinct option is used, only one row is retained for all duplicate data rows in the result set returned by the SELECT statement.

5. Limit the number of returned rows
Use the Top N [percent] Option to limit the number of returned data rows. Top N indicates that N rows are returned, while Top N indicates that N is
Indicates the one hundred score, and the number of returned rows is equal to a few percent of the total number of rows.
For example:
Select Top 2 *
From testtable
Select top 20 percent *
From testtable

(2) From clause
The from clause specifies the tables or views related to the query of select statements. Up to 256 tables or views can be specified in the from clause,
They are separated by commas.
When the from clause specifies multiple tables or views at the same time, if the same column exists in the selected list, use the object name to limit these columns.
The table or view. For example, if the cityid Column exists in both the usertable and citytable tables
Use the following statement format to limit:
Select username, citytable. cityid
From usertable, citytable
Where usertable. cityid = citytable. cityid
You can specify aliases for tables or views in the from clause in the following two formats:
Table name as Alias
Table Name alias

(2) From clause
The from clause specifies the tables or views related to the query of select statements. Up to 256 tables or views can be specified in the from clause,
They are separated by commas.
When the from clause specifies multiple tables or views at the same time, if the same column exists in the selected list, use the object name to limit these columns.
The table or view. For example, if the cityid Column exists in both the usertable and citytable tables
Use the following statement format to limit:
Select username, citytable. cityid
From usertable, citytable
Where usertable. cityid = citytable. cityid
You can specify aliases for tables or views in the from clause in the following two formats:
Table name as Alias
Table Name alias
For example, the alias format of the table available in the preceding statement is as follows:
Select username, B. cityid
From usertable A, citytable B
Where a. cityid = B. cityid
Select can not only retrieve data from tables or views, but also query data from the result set returned by other query statements.
For example:
Select a. au_fname + A. au_lname
From authors A, titleauthor Ta
(Select title_id, title
From titles
Where ytd_sales> 10000
) As T
Where a. au_id = TA. au_id
And ta. title_id = T. title_id
In this example, the result set returned by select is given an alias T, and then the data is retrieved.

(3) Use the WHERE clause to set query conditions
The where clause sets query conditions to filter out unwanted data rows. For example, the following statement queries data older than 20:
Select *
From usertable
Where age> 20
The where clause can contain various conditional operators:
Comparison operators (size comparison):>, >=, =, <, <=, <>,!> ,! <
Range operator (whether the expression value is in the specified range):... And...
Not... And...
List operator (determines whether the expression is a specified item in the list): In (item 1, item 2 ......)
Not in (item 1, item 2 ......)
Pattern match character (determine whether the value matches the specified character wildcard format): Like, not like
Null Value identifier (whether the expression is null): Is null, not is null
Logical operators (for multi-condition logical connections): Not, And, or
1. Range operator example: age between 10 and 30 is equivalent to age> = 10 and age <= 30
2. List operator example: Country in ('Germany ', 'China ')
3. pattern matching example: it is often used for fuzzy search to determine whether the column value matches the specified string format. Can be used for char,
Queries of varchar, text, ntext, datetime, and smalldatetime types.
You can use the following wildcard characters:
Percent sign %: It can match characters of any type and length. If it is Chinese, use two percent signs (%.
Underline _: matches any character. It is often used to limit the character length of an expression.
Square brackets []: Specifies a character, string, or range. The matching object must be any of them.
[^]: The value is [] the same, but the matching object must be any character other than the specified character.
For example:
End with Hing, use like '% Hing'
It must start with a: Like '[a] %'
Restrict the outer class starting with a: Like '[^ A] %'
4. null value judgment operator example where age is null
5. logical operators: the priority is not, and, or
(4) sorting of query results
Use the order by clause to sort the query results by one or more columns. The syntax format of the order by clause is:
Order by {column_name [ASC | DESC]} [,… N]
ASC indicates Ascending Order, which is the default value and desc indicates descending order. Order by cannot be sorted by ntext, text, or image data type
.
For example:
Select *
From usertable
Order by age DESC, userid ASC
In addition, you can sort data by expressions.

2. Joint Query
The Union operator can combine the query result sets of two or more select statements into one result set for display.
Query. The syntax format of union is:
Select_statement
Union [all] selectstatement
[Union [all] selectstatement] [… N]
Selectstatement is the SELECT query statement to be combined.
The all option combines all rows into the result set. If this item is not specified, only one repeat row is retained in the Union query result set.
Line.
During a joint query, the column title of the query result is the column title of the first query statement. Therefore, to define a column title, the column title must be in the first query language.
Sentence definition. To sort the Union query results, you must also use the column name, column title, or column number in the first query statement.
When using the Union operator, make sure that each union query statement has the same number of expressions in the selection list, and each query selects
The expressions should have the same data type, or they can be automatically converted to the same data type. During automatic conversion
The system converts low-precision data types to high-precision data types.
In Union statements that contain multiple queries, the execution sequence is from left to right. Brackets can be used to change the execution sequence. For example:
Query 1 Union (query 2 Union query 3)

Iii. Connection Query
You can use the join operator to query multiple tables. Connection is the main feature of the relational database "target = _ blank> database model. It is also different from other types.
Database "target = _ blank> A mark of the database management system.
In the relational database "target = _ blank> database management system, when a table is created, the relationship between the data does not have to be determined, and all information about an object is often stored in
A table. When retrieving data, you can use the join operation to query information about different entities in multiple tables. Connection operation
With great flexibility, they can add new data types at any time. Create a new table for different entities and then connect to the table.
Query.
The connection can be established in the from clause or where clause of the SELECT statement. It may be helpful to indicate the connection in the from clause.
Separate the join operation from the search condition in the WHERE clause. Therefore, this method is recommended in transact-SQL.
The connection syntax format for the from clause defined by the SQL-92 standard is:
From join_table join_type join_table
[On (join_condition)]
Join_table indicates the name of the table involved in the join operation. The join operation can be performed on the same table or on multiple tables.
Table operations.
Join_type indicates the connection type, which can be divided into three types: internal connection, external connection, and cross connection. Inner join usage ratio
Compare data in one or more columns between tables using comparison operators, and list data rows that match the connection conditions in these tables. Based on
Internal connections are classified into three types: equivalent connections, natural connections, and unequal connections.
Outer Join is divided into left Outer Join (left Outer Join or left join), right Outer Join (right Outer Join or right join)
Full outer join or full join. Different from the internal connection, the external connection not only lists the matches with the connection conditions
To list all the rows that meet the search criteria in the left table (left Outer Join), right table (right Outer Join), or two tables (full outer join ).
Data rows.
Cross join does not have a where clause. It returns the Cartesian product of all data rows in the join table.
The number of rows equals to the number of rows that meet the query conditions in the first table multiplied by the number of rows that meet the query conditions in the second table.
The ON (join_condition) clause in the Join Operation specifies the join condition, which is composed of columns in the connected table, comparison operators, and logic
Operator.
No connection can be used to directly connect columns of the text, ntext, or image data type, but these columns can be indirectly connected.
Connection. For example:
Select p1.pub _ id, p2.pub _ id, p1.pr _ INFO
From pub_info as P1 inner join pub_info as p2
On datalength (p1.pr _ INFO) = datalength (p2.pr _ INFO)

(1) inner connection
The inner join query operation lists the data rows that match the connection condition. It uses the comparison operator to compare the column values of the connected columns. Internal Connection score
Three types:
1. equijoin: Use the equal sign (=) operator in the connection condition to compare the column values in the connected column. The joined column values are listed in the query results.
All columns in the table, including duplicate columns.
2. Unequal join: Use a comparison operator other than the equal operator to compare the column values of the connected columns. These
Operators include >,>=, <=, <,!> ,! <And <>.
3. Natural join: Use the equal to (=) operator in the connection condition to compare the column value of the connected column, but it uses the selection list to indicate the query.
The columns included in the result set, and the duplicate columns in the connection table are deleted.
For example, the following uses equijoin to list authors and publishers in the same city in the authors and publishers tables:
Select *
From authors as a inner join publishers as P
On a. City = P. City
If you use a natural connection, delete the duplicate columns (city and state) in the authors and publishers tables in the selection list ):
Select a. *, P. pub_id, P. pub_name, P. Country
From authors as a inner join publishers as P
On a. City = P. City
(2) External Connection
When the connection is in, only the where search condition or having condition and the connection condition in the returned query result set are met.
. When an external connection is used, it returns to the query result set that contains not only rows that meet the connection conditions, but also the left table (left Outer ).
All data rows in the connected table, right table (right Outer Join), or two edge tables (all Outer Join.
For example, use the left outer link to connect the Forum content to the author information:
Select a. *, B. * From luntan left join usertable as B
On a. Username = B. Username
Next we will use a full outer join to list all the authors in the city table, all the authors in the User table, and their cities:
Select a. *, B .*
From City as a full outer join user as B
On a. Username = B. Username

(3) cross join
The cross join clause does not contain the WHERE clause. It returns the Cartesian product of all data rows in the two joined tables and the number returned to the result set.
The number of rows equals to the number of rows that meet the query conditions in the first table multiplied by the number of rows that meet the query conditions in the second table.
For example, if there are 6 types of books in the titles table, and there are 8 publishers in the publishers table, the number of records retrieved by the following crossover will be
Rows 6*8 = 48.
Select Type, pub_name
From titles cross join publishers
Order by type

(4) A fast statement for Time query in SQL Server
The SQL statement for comparing time in access is simple, such as select * from table where thetime> # "& now () &" #.
This is not the case in MSSQL. Use the datediff statement and the getdate () function for comparison.

For example, if select count (*) from table where datediff (S, getdate (), thetime)> 0, I made a special 0.5 million-piece data table, it takes about 1200 milliseconds to execute this statement.

Later, I studied it and found that the datediff function is not required. You can use> to compare it directly. The statement is as follows: Select count (*) from table where thetime> getdate (), in this way, it takes about 750 milliseconds, which is nearly 500 milliseconds faster.

 

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.