Vous êtes sur la page 1sur 22

Select Statement

Select components
1. Select (required)
2. Expression (required)
3. From Table (Only optional if table data is not
used)
4. Where Condition (optional)
5. Group By (optional)
6. Having (optional)
7. Order By (optional)
8. Limit (optional)

Select
Is a MySQL keyword at the beginning of a
Structured Query Language (SQL) statement or
more simply a query that retrieves data from a
database.
It can be used in conjunction with the MySQL
command insert, replace, and create table.

Expression
The expression
1.

Selects which columns (by column name) will be retrieved

2.

Apply MySQL functions on the columns of data

Examples
Select * from table

(Selects all columns and rows in a table)

Select temperature * 1.8 + 32 from table

(Apply arithmetic operations on a column)

Select dt, temperature, relative_humidity from table

(choose multiple columns in a single query)

Select speed * sin( direction * pi() / 180 ) from table


Select ave(temperature) from table
counts, maximum and minimum values)

(Apply built-in mathematical functions)

(use special functions (aggregate functions) to calculate sums, averages,

Alias
SQL aliases are used to give a database table, or a column in a
table, a temporary name.
Syntax
SELECT column_name AS alias_name ---- column alias
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name; ---- table alias

Example

Select bdate Birthday from table


Select bdate as Birthday from table
Select bdate as Birth Date from table as MyTable
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;

Distinct
The SELECT DISTINCT statement is used to return
only distinct (different) values.
SELECT DISTINCT column_name,column_name
FROM table_name;
Example
SELECT DISTINCT City FROM Customers;

From
Tells MySQL which table(s) to select from
If multiple tables are used in the expression, they all must be
listed separated by a ,
Example
SELECT CustomerName AS Customer, ContactName FROM Customers;
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders WHERE Customers.CustomerName="Around the
Horn" AND Customers.CustomerID=Orders.CustomerID;

Where
The WHERE clause is used to filter records. It sets the condition of which rows
to select. Useful for eliminating unwanted data from your results.
SQL WHERE Syntax
SELECTcolumn_name,column_name
FROMtable_name
WHEREcolumn_name operator value;

Conditional
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equals
!= Not equals

Logical
and True if both are true
or True if only one is true
() Useful for grouping or
ordering multiple logical
statements

String pattern matching


like a MySQL keyword in-between column and pattern
%
a wildcard that matches all instances in a string
_
a wildcard that matches only the character location

Where Examples
SELECT * FROM Customers WHERE Country='Mexico';
SELECT * FROM Customers WHERE CustomerID=1;
SELECT * FROM Customers WHERE Country='Germany AND
City='Berlin';
SELECT supplier_id FROM suppliers WHERE supplier_name =
'Apple' OR supplier_name = 'Microsoft';
SELECT * FROM suppliers WHERE (state = 'Florida' AND
supplier_name = 'IBM') OR (supplier_id > 5000);
SELECT * FROM Customers WHERE City LIKE 's%';
SELECT * FROM Customers WHERE City LIKE '_erlin';
SELECT * FROM Customers WHERE City LIKE 'L_n_on';

Like
The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Example

SELECT
SELECT
SELECT
SELECT

*
*
*
*

FROM
FROM
FROM
FROM

Customers
Customers
Customers
Customers

WHERE
WHERE
WHERE
WHERE

City LIKE 's%';


City LIKE '%s';
Country LIKE '%land%';
City LIKE '_erlin';

Between
The BETWEEN operator is used to select values within a range.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';

In Operator
The IN operator allows you to specify multiple
values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
SELECT * FROM Customers
WHERE City NOT IN ('Paris','London');

Order By
The ORDER BY keyword is used to sort the result-set by one or more
columns.
The ORDER BY keyword sorts the records in ascending order by
default. To sort the records in a descending order, you can use the
DESC keyword.
SQL ORDER BY Syntax
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;

Example

SELECT
SELECT
SELECT
SELECT

*
*
*
*

FROM
FROM
FROM
FROM

Customers
Customers
Customers
Customers

ORDER
ORDER
ORDER
WHERE

BY
BY
BY
ID

Country;
Country DESC;
Country,CustomerName;
BETWEEN 1 and 100 ORDER BY CustomerName;

USING FUNCTIONS
SQL aggregate functions return a single value,
calculated from values in a column.
Useful aggregate functions:

AVG() - Returns the average value


COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

Using Functions
SQL Scalar functions
SQL scalar functions return a single value, based on the
input value.
Useful scalar functions:

UCASE() - Converts a field to upper case


LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LEN() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimals
specified
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed

The AVG() Function


The AVG() function returns the average value of
a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name

Example
SELECT AVG(Price) AS PriceAverage FROM Products;
SELECT ProductName, Price FROM Products
WHERE Price>(SELECT AVG(Price) FROM Products);

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.
COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;
SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders WHERE CustomerID=7;

COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;

COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;

Group By
Aggregates rows by distinct values in the columns listed in the group by
when using statistical functions (e.g., avg, std, max, min, sum, count, etc.)
Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Example
SELECT Rep_Num, AVG(Balance)
FROM Customer
GROUP BY Rep_Num
ORDER BY Rep_Num
SELECT Rep_Num, AVG(Balance)
FROM Customer
GROUP BY Rep_Num, Customer_Name
ORDER BY Rep_Num

Having
The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.
WHERE vs HAVING
Where used to limit the rows that are included in a querys result
Having used to limit the groups that are included

SQL HAVING Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Example
SELECT Rep_Num, AVG(Balance)
FROM Customer
GROUP BY Rep_Num
HAVING COUNT(*)<4
ORDER BY Rep_Num;

LIMIT
Limits the number of rows from the result set
Example
SELECT *
FROM CUSTOMERS
WHERE Balance <5000
LIMIT 10; ----- 10 rows will be displayed as output

NULLS
NULL values represent missing unknown data. By
default, a table column can hold NULL values.
Example
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL

LOADING FILE TO MYSQL : LOAD


DATA INFILE
The LOAD DATA INFILE statement reads rows from a text file into a table at a very high
speed. The file name must be given as a literal string.
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
[REPLACE | IGNORE]
INTO TABLE tbl_name
[CHARACTER SET charset_name]
[{FIELDS | COLUMNS}
[TERMINATED BY 'string']
[[OPTIONALLY] ENCLOSED BY 'char']
[ESCAPED BY 'char']
]
[LINES
[STARTING BY 'string']
[TERMINATED BY 'string']
]
[IGNORE number LINES]
[(col_name_or_user_var,...)]
[SET col_name = expr,...]

mysql> LOAD DATA LOCAL INFILE '/path/pet.txt'


INTO TABLE pet;
mysql> LOAD DATA LOCAL INFILE '/path/pet.txt'
INTO TABLE pet LINES TERMINATED BY '\r\n';
mysql> LOAD DATA LOCAL INFILE '/path/pet.txt'
INTO TABLE pet FIELDS TERMINATED BY , ENCLOSED
BY LINES TERMINATED BY '\r\n';
mysql> LOAD DATA INFILE
'/home/tonyb/subscribers.txt' REPLACE INTO TABLE
subscribers FIELDS ENCLOSED BY '\"' TERMINATED
BY ';' LINES TERMINATED BY '\n';

Vous aimerez peut-être aussi