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

Introduction To SQL: What Is SQL? SQL Data Manipulation Language (DML)

SQL is a standard language for accessing and manipulating databases. It allows users to retrieve, insert, update and delete data. SQL statements include SELECT to extract data, INSERT to add data, UPDATE to modify data, and DELETE to remove data. SQL also includes statements like CREATE TABLE to make new tables and DROP TABLE to remove tables.

Uploaded by

Sandra Victoria
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Introduction To SQL: What Is SQL? SQL Data Manipulation Language (DML)

SQL is a standard language for accessing and manipulating databases. It allows users to retrieve, insert, update and delete data. SQL statements include SELECT to extract data, INSERT to add data, UPDATE to modify data, and DELETE to remove data. SQL also includes statements like CREATE TABLE to make new tables and DROP TABLE to remove tables.

Uploaded by

Sandra Victoria
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Introduction to SQL Hansen

Svendson
Pettersen
SQL is a standard computer language for accessing and manipulating
databases.
Note: Some database systems require a semicolon at the end of the
SQL statement. We don't use the semicolon in our tutorials.

What is SQL?

 SQL stands for Structured Query Language SQL Data Manipulation Language (DML)
 SQL allows you to access a database
 SQL is an ANSI standard computer language SQL (Structured Query Language) is a syntax for executing queries.
 SQL can execute queries against a database But the SQL language also includes a syntax to update, insert, and
 SQL can retrieve data from a database delete records.
 SQL can insert new records in a database
 SQL can delete records from a database
 SQL can update records in a database These query and update commands together form the Data
Manipulation Language (DML) part of SQL:
 SQL is easy to learn
 SELECT - extracts data from a database table
 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
SQL is a Standard - BUT....  INSERT INTO - inserts new data into a database table

SQL is an ANSI (American National Standards Institute) standard


computer language for accessing and manipulating database systems.
SQL statements are used to retrieve and update data in a database.
SQL works with database programs like MS Access, DB2, Informix, SQL Data Definition Language (DDL)
MS SQL Server, Oracle, Sybase, etc.
The Data Definition Language (DDL) part of SQL permits database
Unfortunately, there are many different versions of the SQL tables to be created or deleted. We can also define indexes (keys),
language, but to be in compliance with the ANSI standard, they must specify links between tables, and impose constraints between
support the same major keywords in a similar manner (such as database tables.
SELECT, UPDATE, DELETE, INSERT, WHERE, and others).
The most important DDL statements in SQL are: 
Note: Most of the SQL database programs also have their own
proprietary extensions in addition to the SQL standard!  CREATE TABLE - creates a new database table
 ALTER TABLE - alters (changes) a database table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
SQL Database Tables

A database most often contains one or more tables. Each table is


identified by a name (e.g. "Customers" or "Orders"). Tables contain
records (rows) with data.

Below is an example of a table called "Persons":

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).

SQL Queries

With SQL, we can query a database and have a result set returned.

A query like this:

SELECT LastName FROM Persons

Gives a result set like this:

LastName
SQL DML Statements functions, like: Move-To-First-Record, Get-Record-Content, Move-
To-Next-Record, etc.

SQL SELECT Statement Programming functions like these are not a part of this tutorial. To
learn about accessing data with function calls, please visit our ADO
tutorial.
The SQL SELECT Statement

The SELECT statement is used to select data from a table. The


tabular result is stored in a result table (called the result-set). Semicolon after SQL Statements?

Syntax Semicolon is the standard way to separate each SQL statement in


database systems that allow more than one SQL statement to be
SELECT column_name(s) executed in the same call to the server.
FROM table_name

Some SQL tutorials end each SQL statement with a semicolon. Is this
Note: SQL statements are not case sensitive. SELECT is the same necessary? We are using MS Access and SQL Server 2000 and we do
as select. not have to put a semicolon after each SQL statement, but some
database programs force you to use it.

SQL SELECT Example


The SELECT DISTINCT Statement
To select the content of columns named "LastName" and
"FirstName", from the database table called "Persons", use a The DISTINCT keyword is used to return only distinct (different)
SELECT statement like this: values.

SELECT LastName,FirstName FROM Persons The SELECT statement returns information from table columns. But
what if we only want to select distinct elements?
The database table "Persons":
With SQL, all we need to do is to add a DISTINCT keyword to the
SELECT statement:
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes Syntax
Svendson Tove Borgvn 23 Sandnes SELECT DISTINCT column_name(s)
FROM table_name
Pettersen Kari Storgt 20 Stavanger

The result
Using the DISTINCT keyword
LastName FirstName
Hansen Ola To select ALL values from the column named "Company" we use a
SELECT statement like this:
Svendson Tove
Pettersen Kari
SELECT Company FROM Orders

"Orders" table
Select All Columns
Company OrderNumber
To select all columns from the "Persons" table, use a * symbol
instead of column names, like this:  Sega 3412
W3Schools 2312
SELECT * FROM Persons
Trio 4678
W3Schools 6798
Result
Result
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes Company
Svendson Tove Borgvn 23 Sandnes Sega
Pettersen Kari Storgt 20 Stavanger W3Schools
Trio
W3Schools

The Result Set Note that "W3Schools" is listed twice in the result-set.

The result from a SQL query is stored in a result-set. Most database To select only DIFFERENT values from the column named
software systems allow navigation of the result set with programming "Company" we use a SELECT DISTINCT statement like this:
SELECT DISTINCT Company FROM Orders Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980

Result:

Using Quotes
Company
Sega
Note that we have used single quotes around the conditional values in
W3Schools the examples.
Trio
SQL uses single quotes around text values (most database systems
Now "W3Schools" is listed only once in the result-set. will also accept double quotes). Numeric values should not be
enclosed in quotes.

SQL WHERE Clause For text values:

The WHERE clause is used to specify a selection criterion. This is correct:


SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove

The WHERE Clause  For numeric values:

To conditionally select data from a table, a WHERE clause can be This is correct:
SELECT * FROM Persons WHERE Year>1965
added to the SELECT statement. This is wrong:
SELECT * FROM Persons WHERE Year>'1965'

Syntax
SELECT column FROM table
WHERE column operator value
The LIKE Condition
With the WHERE clause, the following operators can be used:
The LIKE condition is used to specify a search for a pattern in a
column.
Operator Description
= Equal Syntax
<> Not equal SELECT column FROM table
WHERE column LIKE pattern
> Greater than
< Less than
>= Greater than or equal A "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Using LIKE
Note: In some versions of SQL the <> operator may be written as !=
The following SQL statement will return persons with first names
that start with an 'O':

Using the WHERE Clause SELECT * FROM Persons


WHERE FirstName LIKE 'O%'

To select only the persons living in the city "Sandnes", we add a


WHERE clause to the SELECT statement:  The following SQL statement will return persons with first names
that end with an 'a':
SELECT * FROM Persons
WHERE City='Sandnes' SELECT * FROM Persons
WHERE FirstName LIKE '%a'

"Persons" table
The following SQL statement will return persons with first names
that contain the pattern 'la':
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951 SELECT * FROM Persons
Svendson Tove Borgvn 23 Sandnes 1978 WHERE FirstName LIKE '%la%'
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960

Result
SQL ORDER BY
The ORDER BY keyword is used to sort the result.
LastName FirstName Address City Year
Example

Sort the Rows To display the companies in reverse alphabetical order AND the
ordernumbers in numerical order:
The ORDER BY clause is used to sort the rows.
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC, OrderNumber ASC
Orders:

Result:
Company OrderNumber
Sega 3412
ABC Shop 5678 Company OrderNumber
W3Schools 2312 W3Schools 2312
W3Schools 6798 W3Schools 6798
Sega 3412
ABC Shop 5678

Example

To display the companies in alphabetical order:


SQL AND & OR
AND & OR
SELECT Company, OrderNumber FROM Orders
ORDER BY Company
AND and OR join two or more conditions in a WHERE clause.
Result:
The AND operator displays a row if ALL conditions listed are true.
The OR operator displays a row if ANY of the conditions listed are
Company OrderNumber true.
ABC Shop  5678
Sega 3412
W3Schools 6798
W3Schools 2312 Original Table (used in the examples)
LastName FirstName Address City
Example Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
To display the companies in alphabetical order AND the Svendson Stephen Kaivn 18 Sandnes
ordernumbers in numerical order:

SELECT Company, OrderNumber FROM Orders


ORDER BY Company, OrderNumber Example

Result: Use AND to display each person with the first name equal to "Tove",
and the last name equal to "Svendson":
Company OrderNumber
SELECT * FROM Persons
ABC Shop 5678 WHERE FirstName='Tove'
Sega 3412 AND LastName='Svendson'

W3Schools 2312
W3Schools 6798 Result:

Example LastName FirstName Address City


Svendson Tove Borgvn 23 Sandnes
To display the companies in reverse alphabetical order:
Example
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC
Use OR to display each person with the first name equal to "Tove", or
the last name equal to "Svendson":
Result:
SELECT * FROM Persons
WHERE firstname='Tove'
Company OrderNumber OR lastname='Svendson'
W3Schools 6798
W3Schools 2312 Result:
Sega 3412
ABC Shop 5678 LastName FirstName Address City
Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes
Example Original Table (used in the examples)
LastName FirstName Address City
You can also combine AND and OR (use parentheses to form Hansen Ola Timoteivn 10 Sandnes
complex expressions):
Nordmann Anna Neset 18 Sandnes
Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons WHERE
(FirstName='Tove' OR FirstName='Stephen') Svendson Tove Borgvn 23 Sandnes
AND LastName='Svendson'

Result:
Example 1
LastName FirstName Address City
To display the persons alphabetically between (and including)
Svendson Tove Borgvn 23 Sandnes "Hansen" and exclusive "Pettersen", use the following SQL:
Svendson Stephen Kaivn 18 Sandnes
SELECT * FROM Persons WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'

SQL IN Result:

IN
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
The IN operator may be used if you know the exact value you want to
return for at least one of the columns. Nordmann Anna Neset 18 Sandnes

SELECT column_name FROM table_name IMPORTANT! The BETWEEN...AND operator is treated


WHERE column_name IN (value1,value2,..) differently in different databases. With some databases a person with
the LastName of "Hansen" or "Pettersen" will not be listed
(BETWEEN..AND only selects fields that are between and excluding
the test values). With some databases a person with the last name of
"Hansen" or "Pettersen" will be listed (BETWEEN..AND selects
Original Table (used in the examples) fields that are between and including the test values). With other
LastName FirstName Address City databases a person with the last name of "Hansen" will be listed, but
"Pettersen" will not be listed (BETWEEN..AND selects fields
Hansen Ola Timoteivn 10 Sandnes between the test values, including the first test value and excluding
Nordmann Anna Neset 18 Sandnes the last test value). Therefore: Check how your database treats the
Pettersen Kari Storgt 20 Stavanger BETWEEN....AND operator!
Svendson Tove Borgvn 23 Sandnes

Example 2
Example 1
To display the persons outside the range used in the previous
To display the persons with LastName equal to "Hansen" or example, use the NOT operator:
"Pettersen", use the following SQL:
SELECT * FROM Persons WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
Result:
Result:
LastName FirstName Address City
LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger
Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

SQL Alias
SQL BETWEEN
With SQL, aliases can be used for column names and table names.
BETWEEN ... AND

The BETWEEN ... AND operator selects a range of data between two
values. These values can be numbers, text, or dates. Column Name Alias

SELECT column_name FROM table_name The syntax is:


WHERE column_name
BETWEEN value1 AND value2
SELECT column AS column_alias FROM table
Table Name Alias bind data together, across tables, without repeating all of the data in
every table.
The syntax is:
In the "Employees" table below, the "Employee_ID" column is the
primary key, meaning that no two rows can have the same
SELECT column FROM table AS table_alias Employee_ID. The Employee_ID distinguishes two persons even if
they have the same name.

When you look at the example tables below, notice that: 


Example: Using a Column Alias
 The "Employee_ID" column is the primary key of the
This table (Persons): "Employees" table
 The "Prod_ID" column is the primary key of the "Orders"
table
LastName FirstName Address City  The "Employee_ID" column in the "Orders" table is used to
Hansen Ola Timoteivn 10 Sandnes refer to the persons in the "Employees" table without using
their names
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

And this SQL: Employees:

SELECT LastName AS Family, FirstName AS Name


FROM Persons Employee_ID Name
01 Hansen, Ola
Returns this result: 02 Svendson, Tove
03 Svendson, Stephen
Family Name 04 Pettersen, Kari
Hansen Ola
Svendson Tove Orders:
Pettersen Kari
Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
Example: Using a Table Alias 865 Chair 03
This table (Persons):

LastName FirstName Address City Referring to Two Tables


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes We can select data from two tables by referring to two tables, like
this:
Pettersen Kari Storgt 20 Stavanger
Example
And this SQL:
Who has ordered a product, and what did they order?
SELECT LastName, FirstName
FROM Persons AS Employees
SELECT Employees.Name, Orders.Product
FROM Employees, Orders
Returns this result: WHERE Employees.Employee_ID=Orders.Employee_ID

Table Employees: Result

LastName FirstName Name Product


Hansen Ola Hansen, Ola Printer
Svendson Tove Svendson, Stephen Table
Pettersen Kari Svendson, Stephen Chair

Example
SQL JOIN
Who ordered a printer?
Joins and Keys
SELECT Employees.Name
FROM Employees, Orders
Sometimes we have to select data from two or more tables to make WHERE Employees.Employee_ID=Orders.Employee_ID
our result complete. We have to perform a join. AND Orders.Product='Printer'

Tables in a database can be related to each other with keys. A primary Result
key is a column with a unique value for each row. The purpose is to
Name SELECT field1, field2, field3
FROM first_table
Hansen, Ola RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

List all orders, and who has ordered - if any.


Using Joins
SELECT Employees.Name, Orders.Product
OR we can select data from two tables with the JOIN keyword, like FROM Employees
RIGHT JOIN Orders
this: ON Employees.Employee_ID=Orders.Employee_ID

Example INNER JOIN The RIGHT JOIN returns all the rows from the second table (Orders),
even if there are no matches in the first table (Employees). If there
Syntax had been any rows in Orders that did not have matches in Employees,
those rows also would have been listed.
SELECT field1, field2, field3
FROM first_table Result
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Name Product
Who has ordered a product, and what did they order? Hansen, Ola Printer
Svendson, Stephen Table
SELECT Employees.Name, Orders.Product Svendson, Stephen Chair
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID Example

The INNER JOIN returns all rows from both tables where there is a Who ordered a printer?
match. If there are rows in Employees that do not have matches in
Orders, those rows will not be listed.
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
Result ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'

Name Product
Hansen, Ola Printer Result
Svendson, Stephen Table
Svendson, Stephen Chair Name
Hansen, Ola
Example LEFT JOIN

Syntax
SQL UNION and UNION ALL
SELECT field1, field2, field3
FROM first_table UNION
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
The UNION command is used to select related information from two
tables, much like the JOIN command. However, when using the
List all employees, and their orders - if any. UNION command all selected columns need to be of the same data
type.
SELECT Employees.Name, Orders.Product
FROM Employees Note: With UNION, only distinct values are selected.
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
SQL Statement 1
UNION
The LEFT JOIN returns all the rows from the first table (Employees), SQL Statement 2
even if there are no matches in the second table (Orders). If there are
rows in Employees that do not have matches in Orders, those rows
also will be listed.

Result Employees_Norway:

Name Product Employee_ID E_Name


Hansen, Ola Printer 01 Hansen, Ola
Svendson, Tove   02 Svendson, Tove
Svendson, Stephen Table 03 Svendson, Stephen
Svendson, Stephen Chair 04 Pettersen, Kari
Pettersen, Kari  
Employees_USA:
Example RIGHT JOIN
Employee_ID E_Name
Syntax 01 Turner, Sally
02
03
Kent, Clark
Svendson, Stephen
SQL Functions
04 Scott, Stephen
SQL has a lot of built-in functions for counting and calculations.

Using the UNION Command


Function Syntax
Example
The syntax for built-in SQL functions is:
List all different employee names in Norway and USA:
SELECT function(column) FROM table
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA

Types of Functions
Result
There are several basic types and categories of functions in SQL. The
Name basic types of functions are:
Hansen, Ola
Svendson, Tove  Aggregate Functions
Svendson, Stephen  Scalar functions
Pettersen, Kari
Turner, Sally
Kent, Clark
Aggregate functions
Scott, Stephen
Aggregate functions operate against a collection of values, but return
Note: This command cannot be used to list all employees in Norway a single value.
and USA. In the example above we have two employees with equal
names, and only one of them is listed. The UNION command only
selects distinct values. Note: If used among many other expressions in the item list of a
SELECT statement, the SELECT must have a GROUP BY clause!!

"Persons" table (used in most examples)


UNION ALL Name Age
Hansen, Ola 34
The UNION ALL command is equal to the UNION command, except Svendson, Tove 45
that UNION ALL selects all values. Pettersen, Kari 19

SQL Statement 1 Aggregate functions in MS Access


UNION ALL
SQL Statement 2 Function Description
AVG(column) Returns the average value of a column
COUNT(column) Returns the number of rows (without a
NULL value) of a column
Using the UNION ALL Command COUNT(*) Returns the number of selected rows
FIRST(column) Returns the value of the first record in a
Example specified field
LAST(column) Returns the value of the last record in a
List all employees in Norway and USA: specified field
MAX(column) Returns the highest value of a column
SELECT E_Name FROM Employees_Norway MIN(column) Returns the lowest value of a column
UNION ALL
SELECT E_Name FROM Employees_USA STDEV(column)  
STDEVP(column)  
Result SUM(column) Returns the total sum of a column
VAR(column)  
VARP(column)  
Name
Hansen, Ola
Aggregate functions in SQL Server
Svendson, Tove
Svendson, Stephen Function Description
Pettersen, Kari AVG(column) Returns the average value of a column
Turner, Sally BINARY_CHECKSU  
M
Kent, Clark
CHECKSUM  
Svendson, Stephen
CHECKSUM_AGG  
Scott, Stephen
COUNT(column) Returns the number of rows (without a
NULL value) of a column
COUNT(*) Returns the number of selected rows Example
COUNT(DISTINCT Returns the number of distinct results
column) This example returns the average age for persons that are older than
FIRST(column) Returns the value of the first record in a 20 years:
specified field (not supported in
SQLServer2K) SELECT AVG(Age) FROM Persons WHERE Age>20
LAST(column) Returns the value of the last record in a
specified field (not supported in
SQLServer2K) Result
MAX(column) Returns the highest value of a column
MIN(column) Returns the lowest value of a column 39.5
STDEV(column)  
STDEVP(column)  
SUM(column)
VAR(column)
Returns the total sum of a column
 
SQL COUNT Function
VARP(column)  
The COUNT(column)  function returns the number of rows without a
NULL value in the specified column.

Scalar functions Syntax


SELECT COUNT(column) FROM table
Scalar functions operate against a single value, and return a single
value based on the input value.
Example
Useful Scalar Functions in MS Access
With this "Persons" Table:
Function Description
UCASE(c) Converts a field to upper case
Name Age
LCASE(c) Converts a field to lower case
Hansen, Ola 34
MID(c,start[,end]) Extract characters from a text field
Svendson, Tove 45
LEN(c) Returns the length of a text field
Pettersen, Kari  
INSTR(c,char) Returns the numeric position of a named
character within a text field
LEFT(c,number_of_char) Return the left part of a text field This example finds the number of persons with a value in the "Age"
requested field in the "Persons" table:
RIGHT(c,number_of_char Return the right part of a text field
) requested SELECT COUNT(Age) FROM Persons
ROUND(c,decimals) Rounds a numeric field to the number of
decimals specified
MOD(x,y) Returns the remainder of a division Result:
operation
NOW() Returns the current system date 2
FORMAT(c,format) Changes the way a field is displayed
DATEDIFF(d,date1,date2) Used to perform date calculations The COUNT(column) function is handy for finding columns without
a value. Note that the result is one less than the number of rows in the
original table because one of the persons does not have an age value
stored.

SQL COUNT(*) Function


SQL AVG Function The COUNT(*) function returns the number of selected rows in a
selection.
The AVG function returns the average value of a column in a
selection. NULL values are not included in the calculation.
Syntax
Syntax SELECT COUNT(*) FROM table

SELECT AVG(column) FROM table


Example
Example
With this "Persons" Table:
This example returns the average age of the persons in the "Persons"
table: Name Age
Hansen, Ola 34
SELECT AVG(Age) FROM Persons Svendson, Tove 45
Pettersen, Kari 19
Result
This example returns the number of rows in the table:
32.67
SELECT COUNT(*) FROM Persons Syntax
SELECT SUM(column) FROM table
Result:
Example
3
This example returns the sum of all ages in the "person" table:

SELECT SUM(Age) FROM Persons


Example
Result:
Return the number of persons that are older than 20 years:
98
SELECT COUNT(*) FROM Persons WHERE Age>20

Example
Result:
This example returns the sum of ages for persons that are more than
2 20 years old:

SELECT SUM(Age) FROM Persons WHERE Age>20

SQL MAX Function Result:


The MAX function returns the highest value in a column. NULL
values are not included in the calculation. 79

Syntax
SELECT MAX(column) FROM table SQL GROUP BY and HAVING
Example Aggregate functions (like SUM) often need an added GROUP BY
functionality.
SELECT MAX(Age) FROM Persons

Result:
GROUP BY...
45
GROUP BY... was added to SQL because aggregate functions (like
SUM) return the aggregate of all column values every time they are
Note: The MIN and MAX functions can also be used on text called, and without the GROUP BY function it was impossible to find
columns, to find the highest or lowest value in alphabetical order. the sum for each individual group of column values.

The syntax for the GROUP BY function is:


SQL MIN Function
SELECT column,SUM(column) FROM table GROUP BY column
The MIN function returns the lowest value in a column. NULL values
are not included in the calculation.

Syntax GROUP BY Example


SELECT MIN(column) FROM table
This "Sales" Table:

Example
Company Amount
W3Schools 5500
SELECT MIN(Age) FROM Persons
IBM 4500
W3Schools 7100
Result:
And This SQL:
19

SELECT Company, SUM(Amount) FROM Sales


Note: The MIN and MAX functions can also be used on text
columns, to find the highest or lowest value in alphabetical order.
Returns this result:

SQL SUM Function Company SUM(Amount)


W3Schools 17100
The SUM function returns the total sum of a column in a given IBM 17100
selection. NULL values are not included in the calculation.
W3Schools 17100

The above code is invalid because the column returned is not part of
an aggregate. A GROUP BY clause will solve this problem:

SELECT Company,SUM(Amount) FROM Sales


GROUP BY Company

Returns this result:

Company SUM(Amount)
W3Schools 12600
IBM 4500

HAVING...

HAVING... was added to SQL because the WHERE keyword could


not be used against aggregate functions (like SUM), and without
HAVING... it would be impossible to test for result conditions.

The syntax for the HAVING function is:

SELECT column,SUM(column) FROM table


GROUP BY column
HAVING SUM(column) condition value

This "Sales" Table:

Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100

This SQL:

SELECT Company,SUM(Amount) FROM Sales


GROUP BY Company
HAVING SUM(Amount)>10000

Returns this result

Company SUM(Amount)
W3Schools 12600
SQL SELECT INTO Statement Insert a New Row

This "Persons" table:


The SELECT INTO Statement
LastName FirstName Address City
The SELECT INTO statement is most often used to create backup
copies of tables or for archiving records. Pettersen Kari Storgt 20 Stavanger

Syntax And this SQL statement:


SELECT column_name(s) INTO newtable [IN externaldatabase]
FROM source
INSERT INTO Persons 
VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')

Will give this result:


Make a Backup Copy

The following example makes a backup copy of the "Persons" table: LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
SELECT * INTO Persons_backup
Hetland Camilla Hagabakka 24 Sandnes
FROM Persons

The IN clause can be used to copy tables into another database:


Insert Data in Specified Columns
SELECT Persons.* INTO Persons IN 'Backup.mdb'
FROM Persons This "Persons" table:

If you only want to copy a few fields, you can do so by listing them LastName FirstName Address City
after the SELECT statement: Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
SELECT LastName,FirstName INTO Persons_backup
FROM Persons
And This SQL statement:
You can also add a WHERE clause. The following example creates a
"Persons_backup" table with two columns (FirstName and INSERT INTO Persons (LastName, Address)
LastName) by extracting the persons who lives in "Sandnes" from the VALUES ('Rasmussen', 'Storgt 67')
"Persons" table:
Will give this result:
SELECT LastName,Firstname INTO Persons_backup
FROM Persons
WHERE City='Sandnes' LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Selecting data from more than one table is also possible. The Hetland Camilla Hagabakka 24 Sandnes
following example creates a new table "Empl_Ord_backup" that Rasmussen   Storgt 67  
contains data from the two tables Employees and Orders:

SELECT Employees.Name,Orders.Product
INTO Empl_Ord_backup
FROM Employees
INNER JOIN Orders
SQL UPDATE Statement
ON Employees.Employee_ID=Orders.Employee_ID
The Update Statement
SQL INSERT INTO Statement The UPDATE statement is used to modify the data in a table.

The INSERT INTO Statement Syntax


UPDATE table_name
SET column_name = new_value
The INSERT INTO statement is used to insert new rows into a table. WHERE column_name = some_value

Syntax
INSERT INTO table_name
VALUES (value1, value2,....) Person:

You can also specify the columns for which you want to insert data: LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....) Rasmussen   Storgt 67  
Update one Column in a Row Delete All Rows

We want to add a first name to the person with a last name of It is possible to delete all rows in a table without deleting the table.
"Rasmussen": This means that the table structure, attributes, and indexes will be
intact:
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen' DELETE FROM table_name
or
DELETE * FROM table_name
Result:

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67  

Update several Columns in a Row

We want to change the address and add the name of the city:

UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'

Result:

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

SQL DELETE Statement


The DELETE Statement

The DELETE statement is used to delete rows in a table.

Syntax
DELETE FROM table_name
WHERE column_name = some_value

Person:

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

Delete a Row

"Nina Rasmussen" is going to be deleted:

DELETE FROM Person WHERE LastName = 'Rasmussen'

Result

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
SQL DDL Statements Create Index

Indices are created in an existing table to locate rows more quickly


SQL Create Database, Table, and efficiently. It is possible to create an index on one or more
columns of a table, and each index is given a name. The users cannot
and Index see the indexes, they are just used to speed up queries. 

Note: Updating a table containing indexes takes more time than


Create a Database updating a table without, this is because the indexes also need an
update. So, it is a good idea to create indexes only on columns that
are often used for a search.
To create a database:
A Unique Index
CREATE DATABASE database_name

Creates a unique index on a table. A unique index means that two


rows cannot have the same index value.
Create a Table
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
To create a table in a database:
The "column_name" specifies the column you want indexed.
CREATE TABLE table_name
(
column_name1 data_type, A Simple Index
column_name2 data_type,
.......
)
Creates a simple index on a table. When the UNIQUE keyword is
omitted, duplicate values are allowed.
Example
CREATE INDEX index_name
This example demonstrates how you can create a table named ON table_name (column_name)
"Person", with four columns. The column names will be "LastName",
"FirstName", "Address", and "Age":
The "column_name" specifies the column you want indexed.
CREATE TABLE Person 
( Example
LastName varchar,
FirstName varchar,
Address varchar, This example creates a simple index, named "PersonIndex", on the
Age int LastName field of the Person table:
)

CREATE INDEX PersonIndex


This example demonstrates how you can specify a maximum length ON Person (LastName)
for some columns:

If you want to index the values in a column in descending order, you


CREATE TABLE Person  can add the reserved word DESC after the column name:
(
LastName varchar(30),
FirstName varchar,
Address varchar, CREATE INDEX PersonIndex
Age int(3)  ON Person (LastName DESC)
)

If you want to index more than one column you can list the column
The data type specifies what type of data the column can hold. The names within the parentheses, separated by commas:
table below contains the most common data types in SQL:

CREATE INDEX PersonIndex


Data Type Description ON Person (LastName, FirstName)
integer(size) Hold integers only. The maximum number of
int(size) digits are specified in parenthesis.
smallint(size)
tinyint(size) SQL Drop Index, Table and
decimal(size,d)
numeric(size,d)
Hold numbers with fractions. The maximum
number of digits are specified in "size". The
maximum number of digits to the right of the
Database
decimal is specified in "d".
char(size) Holds a fixed length string (can contain letters, Drop Index
numbers, and special characters). The fixed size
is specified in parenthesis. You can delete an existing index in a table with the DROP INDEX
varchar(size) Holds a variable length string (can contain statement.
letters, numbers, and special characters). The
maximum size is specified in parenthesis.
Syntax for Microsoft SQLJet (and Microsoft Access):
date(yyyymmdd) Holds a date
DROP INDEX index_name ON table_name
Syntax for MS SQL Server: Result:

DROP INDEX table_name.index_name LastName FirstName Address City


Pettersen Kari Storgt 20  
Syntax for IBM DB2 and Oracle:
Example
DROP INDEX index_name
To drop the "Address" column in the "Person" table:
Syntax for MySQL:
ALTER TABLE Person DROP COLUMN Address
ALTER TABLE table_name DROP INDEX index_name
Result:

Delete a Table or Database LastName FirstName City


Pettersen Kari  
To delete a table (the table structure, attributes, and indexes will also
be deleted):

DROP TABLE table_name

To delete a database:

DROP DATABASE database_name

Truncate a Table

What if we only want to get rid of the data inside a table, and not the
table itself? Use the TRUNCATE TABLE command (deletes only the
data inside the table):

TRUNCATE TABLE table_name

SQL ALTER TABLE


ALTER TABLE

The ALTER TABLE statement is used to add or drop columns in an


existing table.

ALTER TABLE table_name


ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name

Note: Some database systems don't allow the dropping of a column in


a database table (DROP COLUMN column_name).

Person:

LastName FirstName Address


Pettersen Kari Storgt 20

Example

To add a column named "City" in the "Person" table:

ALTER TABLE Person ADD City varchar(30)


SQL CREATE VIEW Statement CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT
CategorySales
CategoryName,Sum(ProductSales) AS
FROM [Product Sales for 1997]
GROUP BY CategoryName
A view is a virtual table based on the result-set of a SELECT
statement.
We can query the view above as follows:

SELECT * FROM [Category Sales For 1997]


What is a View?
We can also add a condition to the query. Now we want to see the
In SQL, a VIEW is a virtual table based on the result-set of a total sale only for the category "Beverages":
SELECT statement.
SELECT * FROM [Category Sales For 1997]
A view contains rows and columns, just like a real table. The fields in WHERE CategoryName='Beverages'
a view are fields from one or more real tables in the database. You
can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from a single table.

Note: The database design and structure will NOT be affected by the
functions, where, or join statements in a view.

Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Note: The database does not store the view data! The database engine
recreates the data, using the view's SELECT statement, every time a
user queries a view.

Using Views

A view could be used from inside a query, a stored procedure, or


from inside another view. By adding functions, joins, etc., to a view,
it allows you to present exactly the data you want to the user.

The sample database Northwind has some views installed by default.


The view "Current Product List" lists all active products (products
that are not discontinued) from the Products table. The view is
created with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

We can query the view above as follows:

SELECT * FROM [Current Product List]

Another view from the Northwind sample database selects every


product in the Products table that has a unit price that is higher than
the average unit price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)

We can query the view above as follows:

SELECT * FROM [Products Above Average Price]

Another example view from the Northwind database calculates the


total sale for each category in 1997. Note that this view select its data
from another view called "Product Sales for 1997":

You might also like