The data table used in the following example
LastName |
FirstName |
Address |
| City
| Year
Adams |
John |
Oxford Street |
London |
1970 |
Bush |
George |
Fifth Avenue |
New York |
1975 |
Carter |
Thomas |
Changan Street |
Beijing |
1980 |
Gates |
Bill |
Xuanwumen 10 |
Beijing |
1985 |
SELECT
Select statements are used to select data from a table, and the results are stored in a result table, called a result set. Common syntax is as follows
1. Select all the corresponding columns 1 and 2 from the data table
SELECT column 1 name, column 2 name from table name
2. Select the data from the data table for all columns , and the asterisk (*) is a shortcut for selecting all columns.
SELECT * FROM table name
3. In the table, duplicate values may be included. That's not a problem, but sometimes you might want to just list different values (distinct). Keyword DISTINCT is used to return only different values, and repeated values will display only one in the result set.
SELECT DISTINCT column name from table name
Example
SELECT City DISTINCT from Persons
Navigating in the result set (Result-set)
The results obtained by the SQL query program are stored in a result set. Most database software systems allow the use of programming functions to navigate the result set, such as: Move-to-first-record, Get-record-content, Move-to-next-record, and so on.
Similar to these programming functions are not listed in this tutorial. To learn about accessing data through function calls, please visit our ADO tutorials and PHP tutorials.
WHERE
The WHERE clause is used to specify the criteria for selection. If you need to conditionally select data from a table, you can add a WHERE clause to the SELECT statement with the following syntax
SELECT column name from table name WHERE column operator value
The following operators can be used in the WHERE clause
operator |
Description |
= |
Equals |
<> |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
Between |
Within a range |
Like |
Search for a pattern |
Note: In some versions of SQL, the operator <> can be written as! =.
For example
SELECT * from Persons WHERE city = ' Beijing '
Use of quotation marks
Note that the above condition values in the example use single quotes around the
SQL uses single quotes around text values (most database systems also accept double quotes). If it is numeric , do not use quotation marks
Text value
This is the correct select * from Persons where firstname= ' Bush ' This is the wrong select * from Persons where Firstname=bush
Numerical
This is the correct select * from Persons where year>1965 this is the wrong select * from Persons where year> ' 1965 '
Some basic SQL operations (SELECT, DISTINCT, WHERE, quotes)