Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

SQL Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Database (SQL) programming

A. SELECT
A common use is to select data from the tables located in a database. Immediately, we see two
keywords: we need to SELECT information FROM a table.

SELECT column_name
FROM table_name

To illustrate the above example, assume that we have the following table:

Table Store_Information

Store_name Sales 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 the stores in this table, we key in:

SELECT Store_name
FROM Store_Information

Result:
Store names
============
Los Angeles
San Diego
Los Angeles
Boston

1
B. DISTINCT
The SELECT keyword allows us to grab all information from a column (or columns) on a table. This,
of course, necessarily means that there will be duplicates. What if we only want to select each
DISTINCT element? All we need to do is to add DISTINCT after SELECT.

The syntax is as follows:

SELECT DISTINCT column_name


FROM table_name

For example, to select all distinct stores in Table Store_Information,

Table Store_Information

Store_name Sales 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 DISTINCT Store_name


FROM Store_Information

Result:
Store names
============
Los Angeles
San Diego
Boston

2
C. WHERE
This is used to conditionally select the data from a table. For example, we may want to only
retrieve stores with sales above $1,000. To do this, we use the WHERE keyword.

The syntax is as follows:

SELECT column_name
FROM table_name
WHERE condition

For example, to select all stores with sales above $1,000 in Table Store_Information,

Table Store_Information

Store_name Sales 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

C1. And/Or (NOT)

SELECT column_name
FROM table_name
WHERE simple condition
AND/OR simple condition
(AND NOT simple condition)

e.g. WHERE Sales > 1000 AND NOT Store_Name = ‘Los Angeles’

C2. In

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

e.g WHERE Store_Name IN (‘Los Angeles’,‘Boston’,‘Las Vegas’)

3
OR WHERE Store_name = ‘Boston’ OR Store_name = ‘NYC’
….etc

C3. Between

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

e.g WHERE Sales BETWEEN 2000 AND 3000

C4. Like
* for Access
SELECT column_name
FROM table_name
WHERE column_name LIKE ‘part of word%’

% = wildcard (meaning anything, same as * in Access)


e.g. heart% will return heart, hearts and heart attack

D. ORDER BY (for sorting)

SELECT column_name
FROM table_name
ORDER BY column_name ASC/DESC

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.

SELECT Store_Name, Sales FROM Store_Information ORDER BY Sales ASC

If a WHERE clause exists, it comes before the ORDER BY clause.

SELECT column_name
FROM table_name
WHERE condition
ORDER BY column_name ASC/DESC

E. INSERT INTO
To add records to a table

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, ...)

4
Assuming that we have a table that has the following structure:

Table Store_Information

Store_name Sales 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 now wish 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.

We will thus use the following SQL script:

INSERT INTO Store_Information (Store_name, Sales, Date)


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

This will add a new record (row) at the end of the table.

Store_name Sales Date


Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Los Angeles $900 Jan-10-1999
Now write another query to insert the store name ‘NYC’ into the table

INSERT INTO Store_information (Store_Name) VALUES (‘NYC’)

The table will now be like this


Store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
NYC

F. DELETE FROM
To delete data from a table (usually used with a WHERE clause)

Sometimes we may wish to get rid of records from a table. To do so, we can use the DELETE FROM
command. The syntax for this is

DELETE FROM table_name


WHERE condition

5
It is easiest to use an example. Say we currently have a table as below:

Table Store_Information

Store_name Sales 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 content of table would look like this:

Table Store_Information

Store_name Sales Date


San Diego $250 Jan-07-1999
Boston $700 Jan-08-1999

6
G. UPDATE & SET
Once there's data in the table, we might find that there is a need to modify the data.
The syntax for this is:

UPDATE table_name
SET column_1 = new value
WHERE condition

For example, say we currently have a table as below:

Table Store_Information

Store_name Sales 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 notice that the sales for Los Angeles on 01/08/1999 is actually $500 instead of $300, and that
particular entry needs to be updated.

To do so, we use the following SQL:


UPDATE Store_Information
SET Sales = 500, Store_name = ‘Las Angeles’
WHERE Store_name = ‘Los Angeles’
AND Date = ‘Jan-08-1999’

The resulting table would look like this:

Table Store_Information
Store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Las Angeles $500 Jan-08-1999
Boston $700 Jan-08-1999

H. Creating calculated fields (like calculating a mark)

The syntax for this is:

SELECT (column_name1 + column_name2)


AS new_field_name
FROM table_name

7
For example, say we currently have a table as below:

Table Store_Information

Store_name Sales Tax


Los Angeles $1500 $150
San Diego $250 $25
Los Angeles $300 $30
Boston $700 $70

A new field called Total must be created that contains the sales + tax. For example, Los Angeles’
total would be $1650 ($1500+$150).

To do so, we use the following SQL:

SELECT Store_name, Sales, Tax, (Sales + Tax) AS Total


FROM Store_Information

This generates a field called Total which holds a calculated value of the two columns added
together.

Store_name Sales Tax Total


Los Angeles $1500 $150 $1650
San Diego $250 $25 $275
Los Angeles $300 $30 $330
Boston $700 $70 $770

Another example:

Table Learner_Table

Learner_name Mark1 Mark2 Mark3


Bobby 66 68 70
Sammy 75 65 55
Thando 88 92 90
Sipho 45 44 43

A new field called Term_Mark must be calculated. Term_Mark is calculated by adding the three
marks together and dividing them by 3.

To do so, we use the following SQL:

SELECT Learner_name, ((Mark1 + Mark2 + Mark3)/ 3) AS Term_Mark


FROM Learner_Table
WHERE (Mark1 + Mark2 + Mark3)/ 3 >50 (you could
Add this)

8
The resulting printout would look like this:

Learner Term Mark


=====================
Bobby 68
Sammy 65
Thando 90

I. Formatting with ROUND and INT


Sometimes, answers should be rounded off or converted to integers.

To use the ROUND function, the syntax is:


SELECT *
Round((column_name1 + column_name2) / value , no_decimals)
AS new_field_name
FROM table_name

Table Learner_Table

Learner_name Mark1 Mark2 Mark3


Bobby 53 68 70
Sammy 71 65 55
Thando 83 92 90
Sipho 41 44 43

A new field called Term_Mark must be calculated. Term_Mark is calculated by adding the three
marks together and dividing them by 3 and rounding the answer off to 2 decimals.

SELECT * ,
ROUND ((Mark1 + Mark2 + Mark3) / 3 , 2 )
AS Term_Mark
FROM Learner_Table

If the answer had to be converted to an integer (int), we would have used the INT function which
throws away any decimals.

For example:

SELECT * ,
Int((Mark1 + Mark2 + Mark3) / 3)
AS Term_Mark
FROM Learner_Table

9
J. Summative functions: SUM, AVG and COUNT
The syntax for using summative functions is:

SELECT function type(column_name)


FROM table_name

For example, if we want to get the sum of all sales from the following table:

Table Store_Information

Store_name Sales 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 would type in:

SELECT Sum(Sales) AS Total


FROM Store_Information

Total
$2750

If we want to get the average of all sales from the same table, we’d type in:

SELECT Avg(Sales) AS AVERAGE


FROM Store_Information

Note: The function is not called Average, but Avg

Another arithmetic function is COUNT. This allows us to COUNT up the number of row in a certain
table. The syntax is:

SELECT Count(column_name)
FROM table_name

For example, if we want to find the number of store entries in our table, Table Store_Information
we'd key in:

SELECT Count(Store_name)
FROM Store_Information

To count the number of records in a table, we use COUNT(*) as follows:

SELECT Count(*)
AS row_count
FROM Store_Information

10
COUNT and DISTINCT can be used together in a statement to fetch the number of distinct entries
in a table. For example, if we want to find out the number of distinct stores, we'd type:

SELECT Count(DISTINCT Store_name)


FROM Store_Information

K. GROUP BY (for keeping related data together)

GROUP BY is always used in conjunction with Summative Functions like SUM or AVERAGE.

SELECT column_name1,
SUM(column_name2) AS new_field_name
FROM table_name
GROUP BY column_name1

Let's illustrate using the following table:

Table Store_Information

Store_name Sales Date


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

We want to find total sales (stored in Total_sales) for each store. To do so, we would key in:

SELECT Store_name, SUM(Sales) AS Total_sales


FROM Store_Information
GROUP BY Store_name

(HAVING Store_Name like ‘s*’)

The output of result set would return the following:

Store Name Total


=====================
Los Angeles 1800
San Diego 600
Boston 700

11
L. Date functions: YEAR, MONTH and DAY
Dates are stored as follows in a database that uses SQL:

YYYY-MM-DD HH:mm:SSss
(Year, Month, Day, Hour, Minute, Second and Milliseconds)

For example:
2007-02-17 00:00:0070

For the following table, you would like to access all the records with a date in a certain month
(May).

Table Store_Information

Store_name Sales Sale_Date


Los Angeles $1500 01-05-2006
San Diego $250 02-07-2007
Los Angeles $300 08-05-1999
Boston $700 12-08-2001
San Diego $350 15-05-2005

The syntax would be:

SELECT Store_Name
FROM Store_Information
WHERE MONTH(Sale_Date) = 5

Note: Days and months are all given numerically (e.g. March = 3, Tuesday = 2, etc.)

You can also use the functions DAY and YEAR

e.g WHERE YEAR(Sale_Date) = 1978

IF YOU RATHER WANT TO TREAT THE DATE AS IF IT IS ON A NUMBER LINE.

Put a # sign in front and behind the date.

e.g SELECT *
FROM Store_Name
WHERE Sale_date > # 12/12/1998 #

12
M. WHERE (revisited) – creating the relationship

WHERE on 2 or more tables at the same time

Sometimes we want to access two (or more) tables in the same SQL statement.

Let's illustrate using the following tables:

Table Store_Info Table Supplier_Info

Store_name Sales Supplier_ID Supplier_ID Supplier_name


Los Angeles $1500 NES021 CAD041 Cadbury
San Diego $250 BEA003 NES021 Nestle
Los Angeles $300 CAD041 BEA003 Beacon
Boston $700 NES021 LIN005 Lindt
San Diego $350 CAD041 COT023 Cote d’Or

FOREIGN KEY PRIMARY KEY

We want to output a list of the store names against the supplier names.
To do so, we would key in:

SELECT Store_name, Supplier_name


FROM Store_Info, Supplier_Info
WHERE Store_Info.Supplier_ID = Supplier_Info.Supplier_ID

The output of result set would return the following:

Store Name Supplier


========================
Los Angeles Nestle
San Diego Beacon
Los Angeles Cadbury
Boston Nestle
San Diego Cadbury

13

You might also like