You are on page 1of 67

WHAT IS MYSQL

MySQL is an Oracle-backed open source relational database management system (RDBMS) based on
Structured Query Language (SQL). MySQL runs on virtually all platforms,
including Linux, UNIX and Windows. Although it can be used in a wide range of applications, MySQL is most
often associated with web applications and online publishing.

MySQL is an important component of an open source enterprise stack called LAMP. LAMP is a web


development platform that uses Linux as the operating system, Apache as the web server, MySQL as the
relational database management system and PHP as the object-oriented scripting language.
(Sometimes Perl or Python is used instead of PHP.)

LIST OF MYSQL

1. SQL Commands > Select

The SELECT statement in SQL is used to retrieve data from a relational database.

Number of Columns SQL Syntax


1 SELECT "column_name" FROM "table_name";
More Than 1 SELECT "column_name1"[, "column_name2"] FROM "table_name";
All SELECT * FROM "table_name";

Syntax
"table_name" is the name of the table where data is stored, and "column_name" is the name of the column
containing the data to be retrieved.

To select more than one column, add a comma to the name of the previous column, and then add the
column name. If you are selecting three columns, the syntax will be,

SELECT "column_name1", "column_name2", "column_name3" FROM "table_name";

Note there is no comma after the last column selected.

Examples

We will provide examples for each of the following three use cases:

 Retrieve one column


 Retrieve multiple columns
 Retrieve all columns

Let's use the following table to illustrate all three cases:

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Example 1: Select one column


To select a single column, we specify the column name between SELECT and FROM as follows:

SELECT Store_Name FROM Store_Information;

Result:

Store_Name
Los Angeles
San Diego
Los Angeles
Boston

Example 2: Select multiple columns

We can use the SELECT statement to retrieve more than one column. To select Store_Name and Sales
columns from Store_Information, we use the following SQL:

SELECT Store_Name, Sales FROM Store_Information;

Result:

Store_Name Sales
Los Angeles 1500
San Diego 250
Los Angeles 300
Boston 700

Example 3: Select all columns


There are two ways to select all columns from a table. The first is to list the column name of each column.
The second, and the easier, way is to use the symbol *. For example, to select all columns
from Store_Information, we issue the following SQL:

SELECT * FROM Store_Information;

Result:

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

2. SQL Commands > Distinct

In SQL, the DISTINCT keyword is used in the SELECT statement to retrieve unique values from a database
table. Any value that has a duplicate will only show up once.

Syntax

SELECT DISTINCT "column_name"


FROM "table_name";
"table_name" is the name of the table where data is stored, and "column_name" is the name of the column
containing the data to be retrieved.

Examples

The examples will use the following table:

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Example 1: Use DISTINCT on one column

To select all distinct stores in Table Store_Information, we key in,

SELECT DISTINCT Store_Name FROM Store_Information;

Result:

Store_Name

Los Angeles

San Diego
Boston

Example 2: Use DISTINCT on multiple columns

We can apply DISTINCT to multiple columns. If we want to get a list showing all unique combinations of
stores and transaction dates, we would type in the following,

SELECT DISTINCT Store_Name, Txn_Date FROM Store_Information;

Result:

Store_Name Txn_Date

Los Angeles Jan-05-1999

San Diego Jan-07-1999

Los Angeles Jan-08-1999

Boston Jan-08-1999

3. > SQL Commands > WHERE Clause

The WHERE clause is used to filter the result set based on the condition specified following the
word WHERE.

The WHERE clause can be used with the following types of SQL statements:

 SELECT
 UPDATE
 DELETE

Syntax

The syntax for using WHERE in the SELECT statement is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "condition";

The syntax for using WHERE in the UPDATE statement is as follows:

UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";

The syntax for using WHERE in the DELETE statement is as follows:

DELETE FROM "table_name"


WHERE "condition";

"Condition" can include a single comparison clause (called simple condition) or multiple comparison clauses
combined together using AND or OR operators (compound condition).

Examples

We provide examples here to show how to use WHERE in the SELECT statement.

Example 1: WHERE Clause With Simple Condition

To select all stores with sales above $1,000 in Table Store_Information,


Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

we key in,

SELECT Store_Name
FROM Store_Information
WHERE Sales > 1000;

Result:

Store_Name
Los Angeles

Example 2: WHERE Clause With OR Operator

To view all data with sales greater than $1,000 or with transaction date of 'Jan-08-1999', we use the
following SQL,

SELECT *
FROM Store_Information
WHERE Sales > 1000 OR Txn_Date = 'Jan-08-1999';

Result:
Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Using WHERE With UPDATE and DELETE

As mentioned above, the WHERE clause can be used with UPDATE and DELETE statements in addition to


the SELECT statement. Examples of how to use the WHERE clause with these two commands can be seen
in the UPDATE and DELETE sections.

4. > SQL Commands > Update Statement

The UPDATE statement is used to modify data in a database table.

Syntax

UPDATE can be used to modify one column at a time or multiple columns at a time. The syntax for updating
a single column is as follows:

UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";

The syntax for updating multiple columns is as follows:


UPDATE "table_name"
SET column_1 = [value1], column_2 = [value2], ...
WHERE "condition";

Examples

We use the following table for our examples.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Example 1: Update a single column

We notice that the sales for Los Angeles on Jan-08-1999 is actually $500 instead of $300, and that
particular entry needs to be updated. To do so, we use the following SQL query:

UPDATE Store_Information
SET Sales = 500
WHERE Store_Name = 'Los Angeles'
AND Txn_Date = 'Jan-08-1999';

The resulting table would look like


Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 500 Jan-08-1999

Boston 700 Jan-08-1999

In this case, there is only one row that satisfies the condition in the WHERE clause. If there are multiple rows
that satisfy the condition, all of them will be modified. If no WHERE clause is specified, all rows will be
modified.

Example 2: Update multiple columns

We notice that the 'San Diego' entry has the wrong Sales and TXN_Date information. To fix it, we run the
following SQL statement:

UPDATE Store_Information
SET Sales = 600, Txn_Date = 'Jan-15-1999'
WHERE Store_Name = 'San Diego';

The table now becomes,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999

San Diego 600 Jan-15-1999

Los Angeles 500 Jan-08-1999

Boston 700 Jan-08-1999

IMPORTANT: When using the UPDATE statement, pay special attention to make sure that some type of
filtering criteria is specified. Otherwise, the value of all rows can be changed.

5. > SQL Commands > Delete From Statement

The DELETE FROM statement in SQL is used to remove records from a table.

Please note that the DELETE FROM command cannot delete any rows of data that would violate FOREIGN
KEY or other constraints.

Syntax

The syntax for the DELETE FROM statement is as follows:

DELETE FROM "table_name"


WHERE "condition";

The WHERE clause is important here. Without specifying a condition, all records from the table will be
deleted.

"Condition" can be simple (such as "Sales > 500") or complex (such as from the result of a subquery).
Examples

Two examples of how to use the DELETE FROM statement are shown below.

Example 1: DELETE FROM using a simple condition

We use the following table as the starting point.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

We decide not to keep any information on Los Angeles in this table. To accomplish this, we type the
following SQL:

DELETE FROM Store_Information


WHERE Store_Name = 'Los Angeles';

Now the table becomes,

Table Store_Information

Store_Name Sales Txn_Date


San Diego 250 Jan-07-1999

Boston 700 Jan-08-1999

Example 2: DELETE FROM using the results from a subquery

In Example 1, the criteria we use to determine which rows to delete is quite simple. We can also use a more
complex condition. Below is an example where we use a subquery as the condition. Assume we have the
following two tables:

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name

East Boston
East New York

West Los Angeles

West San Diego

We want to remove data for all stores in the East region from Store_Information (assuming that a store is
either in the East region or the West region—it cannot be in more than one region). We use the following
SQL statement to accomplish this:

DELETE FROM Store_Information


WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'East');

Upon execution, the Store_Information table becomes,

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

If we leave out the WHERE clause in a DELETE FROM command, we will delete all rows from the table.
Most times, this is not what we intend to do. To prevent this, it is a best practice in database management to
always run the corresponding SELECT statement first to make sure the rows selected are the ones we intend
to remove from the table. This can be done by replacing "DELETE" with "SELECT *".
6.  > SQL Commands > And Or

The keywords AND and OR are Boolean operators used to specify compound conditions in
the WHERE clause.

Syntax

The syntax for using AND and OR in a compound condition is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{ [AND|OR] "simple condition"}+;

The { }+ means that the expression inside the bracket will occur one or more times. [AND|OR] means that
either AND or OR can be used. In addition, we can use the parenthesis sign ( ) to indicate the order of the
condition.

Example

We use the following table as our example:

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999


San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

If we want to select all stores with sales greater than $1,000 or all stores with sales less than $500 but
greater than $275 in Table Store_Information, we key in,

SELECT Store_Name
FROM Store_Information
WHERE Sales > 1000
OR (Sales < 500 AND Sales > 275);

Result:

Store_Name

Los Angeles

San Francisco

7. > SQL Commands > In

The IN operator in SQL filters the result set based on a list of discrete values. The list of discrete values can
be simply be listed out or is provided by a separate SELECT statement (this is called a subquery).

The IN operator is always used with the WHERE clause.


Syntax

Below is the syntax for the IN operator when the possible values are listed out directly.

SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...);

The number of values in the parenthesis can be one or more, with each values separated by comma. Values
can be numerical or string characters. If there is only one value inside the parenthesis, this commend is
equivalent to,

WHERE "column_name" = 'value1'

The syntax for the IN operator in a subquery construct is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ( [SELECT STATEMENT] );

Please note that the IN operator cannot be used if the filtering criteria is a continuous range. For example, if
we are looking for any value that is between 0 and 1, we cannot use the IN operator because it is not
possible to list every possible value between 0 and 1.

Example

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

To select all records for the Los Angeles and the San Diego stores in Table Store_Information, we key in,

SELECT *
FROM Store_Information
WHERE Store_Name IN ('Los Angeles', 'San Diego');

Result:

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

For an example of the IN operator used in conjunction with a separate SELECT statement, please see


the Subquery section.

8. > SQL Commands > Between
The BETWEEN operator is used when the filtering criteria is a continuous range with a maximum value and
a minimum value. It is always used in the WHERE clause.

Syntax

The syntax for the BETWEEN operator is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2';

This will select all rows whose column has a value between 'value1' and 'value2.'

Examples

We use the following table for our examples.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

Example 1
To select view all sales information between January 6, 1999, and January 10, 1999, we key in,

SELECT *
FROM Store_Information
WHERE Txn_Date BETWEEN 'Jan-06-1999' AND 'Jan-10-1999';

Note that date may be stored in different formats in different databases. This tutorial simply choose one of
the formats.

Result:

Store_Name Sales Txn_Date

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

BETWEEN is an inclusive operator, meaning that 'value1' and 'value2' are included in the result. If we wish
to exclude 'value1' and 'value2' but include everything in between, we need to change the query to the
following:

SELECT "column_name"
FROM "table_name"
WHERE ("column_name" > 'value1')
AND ("column_name" < 'value2');

Example 2
We can also use the BETWEEN operator to exclude a range of values by adding NOT in front
of BETWEEN. In the above example, if we want to show all rows where the Sales column is not between
280 and 1000, we will use the following SQL:

SELECT *
FROM Store_Information
WHERE Sales NOT BETWEEN 280 and 1000;

Result:

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

9. > SQL Commands > Wildcard

Wildcards are used in SQL to match a string pattern. There are two types of wildcards:

 % (percent sign) represents zero, one, or more characters.


 _ (underscore) represents exactly one character.

Wildcards are used with the LIKE operator in SQL.

Examples

Below are some wildcard examples:


 'A_Z': All string that starts with 'A', another character, and end with 'Z'. For example, 'ABZ' and 'A2Z'
would both satisfy the condition, while 'AKKZ' would not (because there are two characters between A
and Z instead of one).
 'ABC%': All strings that start with 'ABC'. For example, 'ABCD' and 'ABCABC' would both satisfy the
condition.
 '%XYZ': All strings that end with 'XYZ'. For example, 'WXYZ' and 'ZZXYZ' would both satisfy the
condition.
 '%AN%': All strings that contain the pattern 'AN' anywhere. For example, 'LOS ANGELES' and 'SAN
FRANCISCO' would both satisfy the condition.
 '_AN%': All strings that contain a character, then 'AN', followed by anything else. For example, 'SAN
FRANCISCO' would satisfy the condition, while 'LOS ANGELES' would not satisfy the condition.

10. > SQL Commands > Like

The LIKE operator is used to filter the result set based on a string pattern. It is always used in
the WHERE clause.

Syntax

The syntax for the LIKE operator is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN};

{PATTERN} often consists of wildcards. We saw several examples of wildcard matching in the previous
section.
Example

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date

LOS ANGELES 1500 Jan-05-1999

SAN DIEGO 250 Jan-07-1999

SAN FRANCISCO 300 Jan-08-1999

BOSTON 700 Jan-08-1999

We want to find all stores whose name contains 'AN'. To do so, we key in,

SELECT *
FROM Store_Information
WHERE Store_Name LIKE '%AN%';

Result:

Store_Name Sales Txn_Date

LOS ANGELES 1500 Jan-05-1999

SAN DIEGO 250 Jan-07-1999

SAN FRANCISCO 300 Jan-08-1999


The "%" sign before 'AN' means that there may be 0, 1, or more characters before the pattern 'AN.' The "%"
sign after 'AN' means that there may be 0, 1, or more characters after the pattern 'AN.' Out of the four store
names, 'LOS ANGELES,' 'SAN DIEGO,' and 'SAN FRANCISCO' all contain this pattern.

11.  > SQL Commands > Order By

The ORDER BY command in SQL sorts the result set in either ascending or descending order. ORDER
BY usually appears last in a SQL statement because it is performed after the result set has been retrieved.

Syntax

The syntax for an ORDER BY statement is as follows:

SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC];

The [ ] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before
the ORDER BY clause. ASC means that the results will be shown in ascending order, and DESC means
that the results will be shown in descending order. If neither is specified, the default is ASC.

It is possible to order by more than one column. In this case, the ORDER BY clause above becomes

ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]

Assuming that we choose ascending order for both columns, the output will be ordered in ascending order
according to column 1. If there is a tie for the value of column 1, we then sort in ascending order by column
2.

Examples
We use the following table for Examples 1-3.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

Example 1: ORDER BY a single column using column name

To list the contents of Table Store_Information by Sales in descending order, we key in,

SELECT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY Sales DESC;

Result:

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

Boston 700 Jan-08-1999

San Francisco 300 Jan-08-1999

San Diego 250 Jan-07-1999


Example 2: ORDER BY a single column using column position

In addition to column name, we may also use column position (based on the SQL query) to indicate which
column we want to apply the ORDER BY clause. The first column is 1, second column is 2, and so on. In the
above example, we will achieve the same results by the following command:

SELECT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY 2 DESC;

Example 3: ORDER BY a single column using a column not in the SELECT statement

The column(s) we use to sort the result do not need to be in the SELECT clause. For example, the following
SQL,

SELECT Store_Name
FROM Store_Information
ORDER BY Sales DESC;

works fine and will give the following result:

Store_Name

Los Angeles

Boston

San Francisco

San Diego
Example 4: ORDER BY an expression

It is also possible to sort the result by an expression. For example, in the following table,

Table Product_Sales

Product_ID Price Units

1 10 9

2 15 4

3 25 3

we can use the SQL statement below to order the results by Revenue (defined as Price * Units):

SELECT Product_ID, Price*Units Revenue


FROM Product_Sales
ORDER BY Price*Units DESC;

Result:

Product_ID Revenue

1 90

3 75

2 60
12. > SQL Commands > Group By

The GROUP BY clause is used to tell SQL what level of granularity the aggregate function should be
calculated in. The level of granularity is represented by the columns in the SELECT statement that are not
aggregate functions.

Syntax

The syntax for GROUP BY is,

SELECT "column_name1", "function type" ("column_name2")


FROM "table_name"
GROUP BY "column_name1";

More than one column can be specified in the GROUP BY clause, and more than one function can be
included.

GROUP BY is the command that can trip up many beginners, as it is often possible to have a SQL
statement with the correct GROUP BY syntax, yet get the wrong results. A good rule of thumb when
using GROUP BY is to include all the non-aggregate function columns in the SELECT statement in
the GROUP BY clause.

Examples

We use the following table for our examples.

Table Store_Information

Store_Name Product_ID Sales Txn_Date


Los Angeles 1 1500 Jan-05-1999

Los Angeles 2 500 Jan-05-1999

San Diego 1 250 Jan-07-1999

Los Angeles 1 300 Jan-08-1999

Boston 1 700 Jan-08-1999

Example 1: GROUP BY a single column

We want to find total sales for each store. To do so, we would key in,

SELECT Store_Name, SUM(Sales)


FROM Store_Information
GROUP BY Store_Name;

Result:

Store_Name SUM(Sales)

Los Angeles 2300

San Diego 250

Boston 700

Example 2: GROUP BY multiple columns


In Example 1, there is only one column associated with GROUP BY. It is possible to have two or more
columns associated with GROUP BY.

We want to find total sales for each product at each store. To do so, we would key in,

SELECT Store_Name, Product_ID, SUM(Sales)


FROM Store_Information
GROUP BY Store_Name, Product_ID;

Result:

Store_Name Product_ID SUM(Sales)

Los Angeles 1 1800

Los Angeles 2 500

San Diego 1 250

Boston 1 700

Example 3: GROUP BY multiple columns and multiple functions

We want to find total sales and the average sales for each product at each store. To do so, we would key in,

SELECT Store_Name, Product_ID, SUM(Sales), AVG(Sales)


FROM Store_Information
GROUP BY Store_Name, Product_ID;

Result:

Store_Name Product_ID SUM(Sales) AVG(Sales)


Los Angeles 1 1800 900

Los Angeles 2 500 500

San Diego 1 250 250

Boston 1 700 700

Example 4: Group by month / date / week

A common use of the GROUP BY function is on a time period, which can be month, week, day, or even
hour. This type of query is often combined with the ORDER BY keyword to provide a query result that shows
a time series.

For example, to find total daily sales from Store_Information, we use the following SQL:

SELECT Txn_Date, SUM(Sales)


FROM Store_Information
GROUP BY Txn_Date
ORDER BY Txn_Date;

Result:

Txn_Date SUM(Sales)

Jan-05-1999 2000

Jan-07-1999 250

Jan-08-1999 1000
13. > SQL Commands > Having

The HAVING clause is used to filter the result set based on the result of an aggregate function. It is
typically located near or at the end of the SQL statement.

HAVING is often coupled with the presence of the GROUP BY clause, although it is possible to have
a HAVING clause without the GROUP BY clause.

Syntax

The syntax for HAVING is,

The brackets around "column_name1" and GROUP BY "column_name1" means that they are optional.

Note: We may select zero, one, or more columns in addition to the aggregate function. If we do select any
column outside of the aggregate function, there is no need for the GROUP BY clause.

Example

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999


San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

To see only the stores with sales over $1,500, we would type,

SELECT Store_Name, SUM(Sales)


FROM Store_Information
GROUP BY Store_Name
HAVING SUM(Sales) > 1500;

Result:

Store_Name SUM(Sales)

Los Angeles 1800

Total sales for both San Diego and Boston are below $1,500, so the "HAVING SUM(Sales) > 1500" clause
filters out these two stores.

HAVING – Filter with Functions


HAVING can be used with aggregate functions where WHERE can not be used.
1 SELECT Age, COUNT(*) FROM Person GROUP BY Age HAVING COUNT(*) > 20;

14. > SQL Commands > Alias

Alias refers to the practice of using a different temporary name to a database table or a column in a table.

The main advantage of using an alias is to help make the SQL statement more concise and readable. In
addition, the output of the SQL statement can become more understandable with the use of an alias.

Syntax

The syntax for a table alias and a column alias is as follows:

SELECT "table_alias"."column_name1" "column_alias"


FROM "table_name" "table_alias";

Both types of aliases are placed directly after the item they alias for, separate by a white space.

Example

We use the following table for our example.

Table Store_Information
Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

We use the same SQL query as Example 1 in the SQL GROUP BY section, except that we have put in both
the column alias and the table alias:

SELECT A1.Store_Name Store, SUM(A1.Sales) "Total Sales"


FROM Store_Information A1
GROUP BY A1.Store_Name;

Result:

Store Total Sales

Los Angeles 1800

San Diego 250

Boston 700

Notice that difference in the result: the column titles are now different. That is the result of using the column
alias. Instead of the somewhat cryptic "Sum(Sales)", we now have "Total Sales", which is much more
understandable, as the column header. The advantage of using a table alias is not apparent in this example.
However, they will become evident when we look at join operations in SQL.
15. > SQL Commands > AS

The keyword AS is used to assign an alias to the column or a table. It is inserted between the column name
and the column alias or between the table name and the table alias.

Syntax

The syntax for using AS is as follows:

SELECT "table_alias"."column_name1" AS "column_alias"


FROM "table_name" AS "table_alias";

Example

Let's take a look at the same example as we used in the SQL Alias section. Assume we have the following
table, Store_Information,

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999


Boston 700 Jan-08-1999

To find total sales by store using AS as part of the table and column alias, we type in:

SELECT A1.Store_Name Store, SUM(A1.Sales) AS "Total Sales"


FROM Store_Information AS A1
GROUP BY A1.Store_Name;

Result:

Store   Total Sales

Los Angeles   1800

San Diego   250

Boston   700

Is there a difference between using an alias without AS and with AS in SQL? The answer is no, there is no
functional difference, as both versions will accomplish exactly the same thing. The use of AS is simply a
more explicit way of mentioning the alias.

16.  > SQL Commands > Select Unique

The SELECT UNIQUE construct is an Oracle-only SQL statement. It is equivalent to SELECT DISTINCT.


Syntax

The syntax for SELECT UNIQUE is as follows:

SELECT UNIQUE "column_name"


FROM "table_name";

Example

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

To select all distinct stores in Table Store_Information in Oracle, we key in,

SELECT UNIQUE Sales FROM Store_Information;

Result:

Sales
1500

250

300

700

16.  > SQL JOIN

Now we want to look at joins. To do joins correctly in SQL requires many of the elements we have
introduced so far. Let's assume that we have the following two tables,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego
and we want to find out sales by region. We see that table Geography includes information on regions and
stores, and table Store_Information contains sales information for each store. To get the sales information
by region, we have to combine the information from the two tables. Examining the two tables, we find that
they are linked via the common field, "Store_Name". We will first present the SQL statement and explain the
use of each segment later:

SELECT A1.Region_Name REGION, SUM(A2.Sales) SALES


FROM Geography A1, Store_Information A2
WHERE A1.Store_Name = A2.Store_Name
GROUP BY A1.Region_Name;

Result:

REGION   SALES
East   700
West   2050

The first two lines tell SQL to select two fields, the first one is the field "Region_Name" from
table Geography (aliased as REGION), and the second one is the sum of the field "Sales" from
table Store_Information (aliased as SALES). Notice how the table aliases are used here: Geography is
aliased as A1, and Store_Information is aliased as A2. Without the aliasing, the first line would become

SELECT Geography.Region_Name REGION, SUM(Store_Information.Sales) SALES

which is much more cumbersome. In essence, table aliases make the entire SQL statement easier to
understand, especially when multiple tables are included.

An alternative way to specify a join between tables is to use the JOIN and ON keywords. In the current
example, the SQL query would be,
SELECT A1.Region_Name REGION, SUM(A2.Sales) SALES
FROM Geography A1
JOIN Store_Information A2
ON A1.Store_Name = A2.Store_Name
GROUP BY A1.Region_Name;

Several different types of joins can be performed in SQL. The key ones are as follows:

 Inner Join
 Outer Join
 Left Outer Join
 Cross Join

The following sections explain each JOIN type in detail.

17. > SQL JOIN > Inner Join

An inner join in SQL returns rows where there is at least one match on both tables. Let's assume that we
have the following two tables,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999
Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego

We want to find out sales by store, and we only want to see stores with sales listed in the report. To do this,
we can use the following SQL statement using INNER JOIN:

SELECT A1.Store_Name STORE, SUM(A2.Sales) SALES


FROM Geography A1
INNER JOIN Store_Information A2
ON A1.Store_Name = A2.Store_Name
GROUP BY A1.Store_Name;

Result:

STORE SALES
Los Angeles 1800
San Diego 250
Boston 700

By using INNER JOIN, the result shows 3 stores, even though we are selecting from the Geography table,
which has 4 rows. The row "New York" is not selected because it is not present in
the Store_Information table.
18.  > SQL JOIN > Outer Join

Previously, we had looked at left join, or inner join, where we select rows common to the participating tables
to a join. What about the cases where we are interested in selecting elements in a table regardless of
whether they are present in the second table? We will now need to use the SQL OUTER JOIN command.

The syntax for performing an outer join in SQL is database-dependent. For example, in Oracle, we will place
an "(+)" in the WHERE clause on the other side of the table for which we want to include all the rows.

Let's assume that we have the following two tables,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego

and we want to find out the sales amount for all of the stores. If we do a regular join, we will not be able to
get what we want because we will have missed "New York," since it does not appear in
the Store_Information table. Therefore, we need to perform an outer join on the two tables above:

SELECT A1.Store_Name, SUM(A2.Sales) SALES


FROM Geography A1, Store_Information A2
WHERE A1.Store_Name = A2.Store_Name (+)
GROUP BY A1.Store_Name;

Note that in this case, we are using the Oracle syntax for outer join.

Result:

Store_Name SALES
Boston 700
New York
Los Angeles 1800
San Diego 250

Note: NULL is returned when there is no match on the second table. In this case, "New York" does not
appear in the table Store_Information, thus its corresponding "SALES" column is NULL.
19. > SQL JOIN > Left Outer Join

In an left outer join, all rows from the first table mentioned in the SQL query is selected, regardless whether
there is a matching row on the second table mentioned in the SQL query. Let's assume that we have the
following two tables,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego

We want to find out sales by store, and we want to see the results for all stores regardless whether there is a
sale in the Store_Information table. To do this, we can use the following SQL statement using LEFT
OUTER JOIN:
SELECT A1.Store_Name STORE, SUM(A2.Sales) SALES
FROM Geography A1
LEFT OUTER JOIN Store_Information A2
ON A1.Store_Name = A2.Store_Name
GROUP BY A1.Store_Name;

Result:

STORE SALES
Los Angeles 1800
San Diego 250
New York NULL
Boston 700

By using LEFT OUTER JOIN, all four rows in the Geography table is listed. Since there is no match for
"New York" in the Store_Information table, the Sales total for "New York" is NULL. Note that it is NULL and
not 0, as NULL indicates there is no match.

20. > SQL JOIN > Cross Join

A cross join (also called a Cartesian join) is a join of tables without specifying the join condition. In this
scenario, the query would return all possible combination of the tables in the SQL query. To see this in
action, let's use the following example:

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego

The following SQL statement is a Cartesian join between the Store_Information and


the Geography tables:

SELECT A1.Store_Name STORE1, A2.Store_Name STORE2, A2.Sales SALES


FROM Geography A1
JOIN Store_Information A2;

Result:

STORE1 STORE2 SALES


Boston Los Angeles 1500
New York Los Angeles 1500
Los Angeles Los Angeles 1500
San Diego Los Angeles 1500
Boston San Diego 250
New York San Diego 250
Los Angeles San Diego 250
San Diego San Diego 250
Boston Los Angeles 300
New York Los Angeles 300
Los Angeles Los Angeles 300
San Diego Los Angeles 300
Boston Boston 700
New York Boston 700
Los Angeles Boston 700
San Diego Boston 700

An alternative way of specifying a cross join is,

SELECT A1.store_name STORE1, A2.store_name STORE2, A2.Sales SALES


FROM Geography A1, Store_Information A2;

A cross join is seldom the desired result. Rather, it is an indication that some required join condition is
missing in the SQL query.

21.  > SQL Commands > Insert Into Statement

The INSERT INTO statement is used to add new records into a database table.


In SQL, there are basically two ways to INSERT data into a table: One is to insert it one row at a time, the
other is to insert multiple rows at a time. In this section, we'll take a look at the first case.

Syntax

The syntax for inserting data into a table one row at a time is as follows:

INSERT INTO "table_name" ("column1", "column2", ...)


VALUES ("value1", "value2", ...);

Examples

The examples refer to a table that has the following structure,

Table Store_Information

Column Name Data Type

Store_Name char(50)

Manager_ID integer

Sales float

Txn_Date datetime

Example 1: All column names are specified

We want to insert one additional row into the table representing the sales data for Los Angeles on January
10, 1999. On that day, this store had $900 in sales, and the Manager_ID for this store is 10. We will use the
following SQL script:
INSERT INTO Store_Information (Store_Name, Manager_ID, Sales, Txn_Date)
VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

Now the table will hold the following data:

Table Store_Information

Store_Name Manager_ID Sales Txn_Date

Los Angeles 10 900 Jan-10-1999

Please note that we can specify the column names in any order -- the order does not have to be the same
as that of the table. For example, the following SQL statement is equivalent to the SQL statement above:

INSERT INTO Store_Information (Sales, Store_Name, Manager_ID, Txn_Date)


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');

Example 2: None of the column names are specified

If we leave off the column names in the INSERT INTO statement, we will need to make sure that data is
inserted in the same column order as that in the table. For example,

INSERT INTO Store_Information


VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

will give us the desired result, while

INSERT INTO Store_Information


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');
will result in Store_Name being set to 900, Manager_ID being set to 'Los Angeles', and Sales being set to
10. Clearly this is not what we intend to accomplish.

Example 3: Some of the column names are specified

In the first two examples, we insert a value for every column in the table. Sometimes, we may decide to
insert value into some of the columns and leave the rest of the columns blank. For those cases, we simply
specify the column names that we want to insert values into in our SQL statement. Below is an example:

INSERT INTO Store_Information (Store_Name, Sales, Txn_Date)


VALUES ('New York', 500, 'Jan-10-1999');

Now the table becomes:

Table Store_Information

Store_Name Manager_ID Sales Txn_Date

Los Angeles 10 900 Jan-10-1999

New York   500 Jan-10-1999

In this case, the value for the Manager_ID column in the second row is NULL. NULL means that data does
not exist, and we discuss the concept of NULL later in this tutorial.

22. > SQL Commands > Insert Into Select Statement

The INSERT INTO SELECT statement is used to add multiple new records into a database table at one
time.
Syntax

The syntax for INSERT INTO SELECT is as follows:

INSERT INTO "table1" ("column1", "column2", ...)


SELECT "column3", "column4", ...
FROM "table2";

Note that this is the simplest form. The SELECT statement can easily contain WHERE, GROUP BY,
and HAVING clauses, as well as table joins and aliases.

Please note the number of columns specified in the SELECT statement must be the same as the number of
columns specified in the INSERT INTO statement.

Example

We use the following tables for our example.

Table Store_Information

Column Name Data Type

Store_Name char(50)

Sales float

Txn_Date datetime

Table Sales_Data

Column Name Data Type


Store_Name char(50)

Product_ID integer

Sales float

Txn_Date datetime

Table Sales_Data has detailed sales information, while table Store_Information keeps summarized data


on sales by store by day. To copy data from Sales_Data to Store_Information, we type in:

INSERT INTO Store_Information (Store_Name, Sales, Txn_Date)


SELECT Store_Name, SUM(Sales), Txn_Date
FROM Sales_Data
GROUP BY Store_Name, Txn_Date;

Please note that we specified the order of the columns to insert data into in the example above (the first
column is Store_Name, the second column is Sales, and the third column is Txn_Date). While this is not
absolutely necessary, it is a good practice to follow, as this can ensure that we are always inserting data into
the correct column.
Most Useful SQL Commands List with
Examples
BY İSMAIL BAYDAN · PUBLISHED 17/09/2018 · UPDATED 17/09/2018
SQL or Structured Query Language is a standard language used to to create, list, update, delete databases,
tables, records. It provides this functionality with different type of commands. In this tutorial we will learn
popular and useful SQL commands.

Ad by Valueimpression
Command Types
SQL language is very advanced language which provides large command set. The commands are
categorized according to their usage. Here is types of SQL commands.

 DDL – Database Definition Language is used to create,change,delete database, table.


 DML – Data Manipulation Language is used to manupilate data in the database and tables
 DQL – Data Query Language is SELECt and similar query commands.
 DCL – Data Control Language is used to to grant and revoke privileges

ALTER TABLE – Change Table Structure


In SQL tables are created at the start and generally used for long times. But if we need to change like
adding new column to table we need to use ALTER TABLE . In this example we will add a new column
named Age to the table Person. Age column will hold data in integer type.

1 ALTER TABLE Person ADD Age int;

AND – Logic
SQL provides logical operations like AND . We can use AND check multiple conditions if they are True . In
this example we will check if 1=1 and a value is equal to b .
1 SELECT * FROM Person WHERE 1=1 AND a=b;

AS – Rename Column Names


After SELECT we can rename the column name whatever we want. We will use AS after the column name.
In this example we will rename the column Age as YAS .

1 SELECT Age AS YAS FROM Person;

AVG Function – Calculate Average Of Column


Values
In some cases we may need to make simple arithmetic calculations like average. We can calculate average
value of given columns with AVG() function. In this example we will calculate average value of
the Age column.
1 SELECT AVG(Age) FROM Person;

BETWEEN – Defined Range For Where


While printing records we can specify some conditions for a given value for a range. We can
use BETWEEN to specify the column value should be between given values. In this example we will print
rows where Age is between 18 and 25.

LEARN MORE  How To Get Python String Length?

1 SELECT * FROM Person WHERE Age BETWEEN 18 AND 25;

echo '

'
COUNT – Count Values
We can simply count given column values. Attention this will not sum just COUNT . In this example we will
count with Age column not sum.

1 SELECT COUNT(Age) FROM Person;

CREATE TABLE – Create Table


One of the most popular command is CREATE TABLE which is used to create a table from scratch. We will
provide the table name, columns and their types. In this example we will create a table named Person and
add columns Id , Name , Surname and Age

1 CREATE TABLE Person (

2 Id int,

3 Name varchar;

4 Surname varchar,
5 Age int

6 );

DELETE – Delete Record/Row From Table


What if we need to delete some record from table. We will use DELETE by providing the condition to select
rows we want to delete. In this exmaple we will delete records those Age is equal to 20.

1 DELETE FROM Person WHERE Age=20;

GROUP BY – Group Result


We can group results according to given column. In this exmaple we will group by according to Age .

1 SELECT Age, COUNT(*) FROM Person BROUP BY Age;

HAVING – Filter with Functions


HAVING can be used with aggregate functions where WHERE can not be used.
1 SELECT Age, COUNT(*) FROM Person GROUP BY Age HAVING COUNT(*) > 20;

INNER JOIN – Join Multiple tables


If we need to join multiple tables according to same column we can use INNER JOIN . We will just match
same column from multiple tables. In this tables we will match Id from tables Person and Student

1 SELECT Name, Surname, Age FROM Person JOIN Student ON Person.Id = Student.Id;

INSERT – Add New Row/Record


One of the most used operation on SQL databases is record or row insert simply adding record. We will
use INSERT in to insert new data into table. In this example we will insert data Name , Surname , Age into
table Person .

LEARN MORE  How To Read And Filter Windows Update Log In Command Line
1 INSERT INTO Person (Name, Surname,Age) VALUES ("Ahmet Ali","Baydan","6");

IS NULL – Check Value


There are different types of data. If the given value is not set it will be NULL . We can check whether given
value is null with IS NULL . In this example we will find the records those Age not set properly.

1 SELECT * FROM Person WHERE Age IS NULL;

LIKE – Filter Similar Values


If we want to filter according to a patterns we can use LIKE . In this example we will filter Name which starts
with A .

1 SELECT * FROM Person WHERE LIKE 'A%';


LIMIT – Limit Results By Count
When we run a generic query we may get a lot of record which will slow down database and fill the result
pane. We can limit listed records wit LIMIT keyword by providing the record count we want to list. In this
example we will list first 50 records.

1 SELECT * FROM Person LIMIT 50;

MAX() – Select Maximum Value


We can select maximum value of the given column with MAX() function. In this example we will select the
maximum Age from table Person .

1 SELECT MAX(Age) FROM Person;

MIN() – Select Minimum Value


We can select minimum value of the given column with MIN() function. In this example we will select the
minimum Age from table Person .
1 SELECT MIN(Age) FROM Person;

OR – Logic
SQL supports logic operations like OR . We can or two conditions where meeting one of them will make true.
In this example we will list rows where Age is 20 or 30 .

LEARN MORE  How To Create, Use and Delete SQL View?

1 SELECT * FROM Person WHERE Age=20 OR Age=30;

ORDER BY – Order By Given Option


We can order selected rows with ORDER BY . In this example we will order by Age column values.
1 SELECT * FROM Person ORDER BY Age;

OUTER JOIN – Join Multiple Tables


Outer join is used to join multiple tables where there is not condition met. So every table on the left will be
return and merge with right table. If column value not met NULL will be set for the given column.

1 SELECT * FROM Person LEFT JOIN Student ON Person.Id = Student.Id;

ROUND() – Round Given Column Values


We can round given column and values. In this example we will round Age column.

1 SELECT ROUND(Age) FROM Person;


SELECT – List Given Records/Rows
The most important is listing records. We will use SELECT which will print all columns with * or columns we
provide. In this example we will select columns Name and Age .

1 SELECT Name, Age FROM Person;

SELECT DISTINCT – Return Unique Values


We can select given column in a unique way. We will use columns Name .

1 SELECT DISTINCT Name FROM Person;

SUM() – Sum Given Column Values


We can sum given column values. In this example we will sum Age column.
1 SELECT SUM(Age) FROM Person;

UPDATE – Update Record/Row


We can update given row value with UPDATE . In this example we will update the Age of the
record İsmail .

1 UPDATE Person SET Age=34 WHERE Name='İsmail';

WHERE – Filter Results


We need to generally specify some conditions about the operations . We can use WHERE in order to specify
the condition with the helpers like LIKE , BETWEEN  etc.

1 SELECT * FROM Person WHERE Age < 30;

You might also like