What Is SQL? Using SQL in Your Web Site
What Is SQL? Using SQL in Your Web Site
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
However, to be compliant with the ANSI standard, they all support at least
the major commands (such as SELECT, UPDATE, DELETE, INSERT,
WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
SQL
HTML / CSS
RDBMS is the basis for SQL, and for all modern database systems like MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
RDBMS
SQL Syntax
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.
We are using MS Access and SQL Server 2000 and we do not have to put a
semicolon after each SQL statement, but some database programs force you
to use it.
P_Id
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 five
columns (P_Id, LastName, FirstName, Address, and City).
SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements.
The following SQL statement will select all the records in the "Persons"
table:
SELECT * FROM Persons
Now we want to select the content of the columns named "LastName" and
"FirstName" from the table above. We use the following SELECT statement:
SELECT LastName,FirstName FROM Persons
LastName
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
SELECT column_name(s)
FROM table_name
and
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
The WHERE clause is used to filter records. It is used to extract only those
records that fulfill a specified criterion. SQL WHERE Syntax is:
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
P_Id
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Hansen
Ola
Timoteivn 10
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select only the distinct values from the column named
"City" from the table above.
We use the following SELECT statement:
SELECT DISTINCT City FROM Persons
Now we want to select only the persons living in the city "Sandnes" from
the table above. We use the following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
>=
<=
BETWE
Between an inclusive range
EN
LIKE
IN
Equal
<> or !
Not equal
=
>
Greater than
<
Less than
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
5
Pettersen
Kari
Storgt 20
Stavanger
You can also combine AND and OR (use parenthesis to form complex
expressions).
Now we want to select only the persons with the first name equal to "Tove"
AND the last name equal to "Svendson":
Now we want to select only the persons with the last name equal to
"Svendson" AND the first name equal to "Tove" OR to "Ola":
P_Id
LastName
FirstName
Address
City
P_Id
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Now we want to select only the persons with the first name equal to "Tove"
OR the first name equal to "Ola":
SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola'
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
LastName
FirstName
Address
City
6
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
P_Id
LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
Nilsen
Tom
Vingvn 23
Stavanger
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Tom
Vingvn 23
Stavanger
Hansen
Ola
Timoteivn 10
Sandnes
Now we want to select all the persons from the table above, however, we
want to sort the persons by their last name.
SELECT * FROM Persons
ORDER BY LastName
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Nilsen
Tom
Vingvn 23
Stavanger
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
The second form specifies both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to insert a new row in the "Persons" table. We use the
following SQL statement:
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE
clause specifies which record or records that should be updated. If you omit
the WHERE clause, all records will be updated!
The "Persons" table:
P_Id
LastName
FirstName
Address
City
8
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Nissestien 67
Sandnes
Svendson
Tove
Nissestien 67
Sandnes
Pettersen
Kari
Nissestien 67
Sandnes
Nilsen
Johan
Nissestien 67
Sandnes
Tjessem
Jakob
Nissestien 67
Sandnes
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Nissestien 67
Sandnes
Note: Notice the WHERE clause in the DELETE syntax. The WHERE
clause specifies which record or records that should be deleted. If you omit
the WHERE clause, all records will be deleted!
It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
Tjessem
Jakob
Nissestien 67
Sandnes
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
Note: Be very careful when deleting records. You cannot undo this
statement!
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Johan
Bakken 2
Stavanger
10
Example
SELECT *
FROM Persons
LIMIT 5
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number
Example
SELECT *
FROM Persons
WHERE ROWNUM <= 5
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
SQL IN Operator
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Nilsen
Tom
Vingvn 23
Stavanger
Now we want to select only the two first records in the table above. We use
the following SELECT statement:
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1,value2,...)
Now we want to select the persons with a last name equal to "Hansen" or
"Pettersen" from the person table.
LastName
FirstName
Address
City
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
The "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
Next, we want to select the persons living in a city that ends with an "s"
from the "Persons" table. We use the following SELECT statement:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons living in a city that starts with "s" from
the table above.
We use the following SELECT statement:
SELECT * FROM Persons
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Next, we want to select the persons living in a city that contains the pattern
"tav" from the "Persons" table. We use the following SELECT statement:
SELECT * FROM Persons
WHERE City LIKE '%tav%'
12
P_Id
LastName
FirstName
Address
City
[charlist]
Pettersen
Kari
Storgt 20
Stavanger
It is also possible to select the persons living in a city that NOT contains the
pattern "tav" from the "Persons" table, by using the NOT keyword.
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for
data in a database. SQL wildcards must be used with the SQL LIKE
operator.
With SQL, the following wildcards can be used:
Wildcard
Description
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
13
Next, we want to select the persons living in a city that contains the pattern
"nes" from the "Persons" table. We use the following SELECT statement:
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
LastName
Hansen
FirstName
Ola
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Now we want to select the persons with a first name that starts with any
character, followed by "la" from the "Persons" table. We use the following
SELECT statement:
P_Id
P_Id
Address
Timoteivn 10
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
City
Sandnes
Next, we want to select the persons with a last name that starts with "S",
followed by any character, followed by "end", followed by any character,
followed by "on" from the "Persons" table.
Next, we want to select the persons with a last name that do not start with
"b" or "s" or "p" from the "Persons" table.
SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'
14
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons with a last name alphabetically between
"Hansen" and "Pettersen" from the table above.
SELECT * FROM Persons
WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
To display the persons outside the range in the previous example, use NOT
BETWEEN:
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
15
Pettersen
Kari
Storgt 20
Stavanger
SQL Alias
You can give a table or a column another name by using an alias. This can
be a good thing to do if you have very long or complex table names or
column names.
As you'll see from the two SELECT statements above; aliases can make
queries easier to both write and to read.
SQL Joins
SELECT column_name(s)
FROM table_name
AS alias_name
The JOIN keyword is used in an SQL statement to query data from two or
more tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
Now we want to list all the orders that "Ola Hansen" is responsible for.
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
16
Note that the "P_Id" column is the primary key in the "Persons" table. This
means that no two rows can have the same P_Id. The P_Id distinguishes two
persons even if they have the same name. Next, we have the "Orders" table:
O_Id
OrderNo
P_Id
77895
44678
22456
24562
34764
15
Note that the "O_Id" column is the primary key in the "Orders" table and
that the "P_Id" column refers to the persons in the "Persons" table without
using their names.
Notice that the relationship between the two tables above is the "P_Id"
column.
FirstName
OrderNo
Hansen
Ola
22456
Hansen
Ola
24562
Pettersen
Kari
77895
17
Pettersen
Kari
44678
Hansen
Ola
24562
The INNER JOIN keyword return rows when there is at least one match in
both tables. If there are rows in "Persons" that do not have matches in
"Orders", those rows will NOT be listed.
Pettersen
Kari
77895
Pettersen
Kari
44678
Svendson
Tove
The LEFT JOIN keyword returns all rows from the left table (table_name1),
even if there are no matches in the right table (table_name2).
The LEFT JOIN keyword returns all the rows from the left table (Persons),
even if there are no matches in the right table (Orders).
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
The RIGHT JOIN keyword Return all rows from the right table
(table_name2), even if there are no matches in the left table (table_name1).
LastName
FirstName
OrderNo
Hansen
Ola
22456
Now we want to list all the orders with containing persons - if any, from the
tables "Persons" and "Orders".
18
FirstName
OrderNo
Hansen
Ola
22456
Hansen
Ola
24562
Pettersen
Kari
77895
Pettersen
Kari
44678
34764
The RIGHT JOIN keyword returns all the rows from the right table
(Orders), even if there are no matches in the left table (Persons).
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Now we want to list all the persons and their orders, and all the orders with
their persons. We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
FirstName
OrderNo
Hansen
Ola
22456
Hansen
Ola
24562
Pettersen
Kari
77895
Pettersen
Kari
44678
Svendson
Tove
34764
The FULL JOIN keyword returns all the rows from the left table (Persons),
and all the rows from the right table (Orders). If there are rows in "Persons"
that do not have matches in "Orders", or if there are rows in "Orders" that do
not have matches in "Persons", those rows will be listed as well.
19
01
Hansen, Ola
02
Svendson, Tove
03
Svendson, Stephen
04
Pettersen, Kari
Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
PS: The column names in the result-set of a UNION are always equal to the
column names in the first SELECT statement in the UNION.
"Employees_USA":
E_ID
E_Name
01
Turner, Sally
02
Kent, Clark
03
Svendson, Stephen
04
Scott, Stephen
Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
E_Name
Svendson, Tove
Turner, Sally
Svendson, Stephen
Kent, Clark
Pettersen, Kari
Svendson, Stephen
Turner, Sally
Scott, Stephen
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and
USA. In the example above we have two employees with equal names, and
only one of them will be listed. The UNION command selects only distinct
values.
The SQL SELECT INTO statement can be used to create backup copies of
tables.
The SELECT INTO statement selects data from one table and inserts it into
a different table. The SELECT INTO statement is most often used to create
backup copies of tables.
Result
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
E_Name
Hansen, Ola
Or we can select only the columns we want into the new table:
Svendson, Tove
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename
Svendson, Stephen
Pettersen, Kari
21
Make a Backup Copy - Now we want to make an exact copy of the data in
our "Persons" table.
SELECT *
INTO Persons_Backup
FROM Persons
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
We can also use the IN clause to copy the table into another database:
SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons
We can also copy only a few fields into the new table:
SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons
22
The empty table can be filled with data with the INSERT INTO statement.
column_name2 data_type,
column_name3 data_type,
....
)
The data type specifies what type of data the column can hold. For a
complete reference of all the data types available in MS Access, MySQL,
and SQL Server, go to our complete Data Types reference.
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
The P_Id column is of type int and will hold a number. The LastName,
FirstName, Address, and City columns are of type varchar with a maximum
length of 255 characters.
The empty "Persons" table will now look like this:
P_Id
LastName
SQL Constraints
FirstName
Address
City
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
23
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This
means that you cannot insert a new record, or update a record without
adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column
to not accept NULL values:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Note that you can have have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
24
MySQL:
ALTER TABLE Persons
DROP INDEX uc_PersonID
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
26
Note: If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) must already have been declared to not contain
NULL values (when the table was first created).
Let's illustrate the foreign key with an example. Look at the following two
tables:
The "Persons" table:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY
OrderNo
P_Id
77895
44678
22456
24562
Note that the "P_Id" column in the "Orders" table points to the "P_Id"
column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy
link between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted
into the foreign key column, because it has to be one of the values contained
in the table it points to.
28
The following SQL creates a CHECK constraint on the "P_Id" column when
the "Persons" table is created. The CHECK constraint specifies that the
column "P_Id" must only include integers greater than 0.
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders
My SQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
29
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
31
Note: The syntax for creating indexes varies amongst different databases.
Therefore: Check the syntax for creating indexes in your database.
Indexes
An index can be created in a table to find data more quickly and efficiently.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
The users cannot see the indexes, they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than
updating a table without (because the indexes also need an
update). So you should only create indexes on columns (and
tables) that will be frequently searched against.
Indexes, tables, and databases can easily be deleted/removed with the DROP
statement.
What if we only want to delete the data inside the table, and not the table
itself?
Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
Notice that the new column, "DateOfBirth", is of type date and is going to
hold a date. The data type specifies what type of data the column can hold.
For a complete reference of all the data types available in MS Access,
MySQL, and SQL Server, go to our complete Data Types reference.
The "Persons" table will now like this:
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
P_Id
LastNam FirstNam
Address
e
e
Hansen
Svendson Tove
Borgvn 23
Sandnes
Pettersen Kari
Storgt 20
Stavanger
Ola
City
DateOfBirth
Timoteivn 10 Sandnes
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Now we want to change the data type of the column named "DateOfBirth"
in the "Persons" table.
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Notice that the "DateOfBirth" column is now of type year and is going to
hold a year in a two-digit or four-digit format.
34
Very often we would like the value of the primary key field to be created
automatically every time a new record is inserted.
We would like to create an auto-increment field in a table.
The following SQL statement defines the "P_Id" column to be an autoincrement primary key field in the "Persons" table:
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
To insert a new record into the "Persons" table, we will not have to specify a
value for the "P_Id" column (a unique value will be added automatically):
35
The SQL statement above would insert a new record into the "Persons"
table. The "P_Id" column would be assigned a unique value. The
"FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
The MS SQL Server uses the IDENTITY keyword to perform an autoincrement feature.
By default, the starting value for IDENTITY is 1, and it will increment by 1
for each new record.
To specify that the "P_Id" column should start at value 10 and increment by
5, change the identity to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will not have to specify a
value for the "P_Id" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
The SQL statement above would insert a new record into the "Persons"
table. The "P_Id" column would be assigned a unique value. The
"FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
36
The SQL statement above would insert a new record into the "Persons"
table. The "P_Id" column would be assigned a unique value. The
"FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
SQL Views
The code above creates a sequence object called seq_person, that starts with
1 and will increment by 1. It will also cache up to 10 values for
performance. The cache option specifies how many sequence values will be
stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the
nextval function (this function retrieves the next value from seq_person
sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons"
table. The "P_Id" column would be assigned the next number from the
Note: A view always shows up-to-date data! The database engine recreates
the data, using the view's SQL statement, every time a user queries a view.
37
We can also add a condition to the query. Now we want to see the total sale
only for the category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
Another view in the Northwind sample database selects every product in the
"Products" table with a unit price 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)
Another view in the Northwind database calculates the total sale for each
category in 1997. Note that this view selects its data from another view
called "Product Sales for 1997":
Now we want to add the "Category" column to the "Current Product List"
view. We will update the view with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
38
The following table lists the most important built-in date functions in
MySQL:
Function
Description
NOW()
CURDATE()
CURTIME()
DATE()
EXTRACT()
DATE_ADD()
DATE_SUB()
DATEDIFF()
SQL Dates
The most difficult part when working with dates is to be sure that the
format of the date you are trying to insert, matches the format of the date
column in the database.
As long as your data contains only the date portion, your queries will work
as expected. However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at
the most important built-in functions for working with dates.
DATE_FORMAT
Displays date/time data in different formats
()
Description
GETDATE()
For an overview of all data types available, go to our complete Data Types
reference.
DATEPART()
DATEADD()
DATEDIFF()
CONVERT()
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
ProductName
OrderDate
Geitost
2008-11-11
Camembert Pierrot
2008-11-09
Mozzarella di Giovanni
2008-11-11
Mascarpone Fabioli
2008-10-29
OrderId
ProductName
OrderDate
Geitost
2008-11-11
Mozzarella di Giovanni
2008-11-11
Note: The date types are chosen for a column when you create a new table
in your database!
40
This chapter will explain the IS NULL and IS NOT NULL operators.
OrderId
ProductName
OrderDate
Geitost
2008-11-11 13:23:44
Camembert Pierrot
2008-11-09 15:45:21
Mozzarella di Giovanni
2008-11-11 11:12:01
Mascarpone Fabioli
2008-10-29 14:56:59
we will get no result! This is because the query is looking only for dates
with no time portion.
Tip: If you want to keep your queries simple and easy to maintain, do not
allow time components in your dates!
LastName
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
Address
City
Sandnes
Borgvn 23
Sandnes
Stavanger
41
Suppose that the "Address" column in the "Persons" table is optional. This
means that if we insert a record with no value for the "Address" column, the
"Address" column will be saved with a NULL value.
How can we test for NULL values?
It is not possible to test for NULL values with comparison operators, such as
=, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
SQL IS NULL
LastNam FirstNam
Address
e
e
How do we select only the records with NULL values in the "Address"
column?
Svendson Tove
In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and
COALESCE() functions.
Borgvn 23
Ola
Pettersen
Kari
42
Jarlsberg
10.45
16
Mascarpone
32.56
23
Gorgonzola
15.67
15
Oracle
Oracle does not have an ISNULL() function. However, we can use the
NVL() function to achieve the same result:
20
In the example above, if any of the "UnitsOnOrder" values are NULL, the
result is NULL.
Microsoft's ISNULL() function is used to specify how we want to treat
NULL values.
SELECT
ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products
MySQL
MySQL does have an ISNULL() function. However, it works a little bit
different from Microsoft's ISNULL() function.
In MySQL we can use the IFNULL() function, like this:
SELECT
ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
SELECT
ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
Data types and ranges for Microsoft Access, MySQL and SQL Server.
Data type
Description
Text
Memo
Byte
1 byte
Integer
2
bytes
Long
4
bytes
Single
4
bytes
Double
8
bytes
Currency
Stora
ge
4
bytes
44
Date/Time
8
bytes
Yes/No
TINYTEXT
TEXT
Ole Object
BLOB
Hyperlink
Lookup
Wizard
up to
1GB
LONGBLOB
ENUM(x,y,z,e Let you enter a list of possible values. You can list up
tc.)
to 65535 values in an ENUM list. If a value is
inserted that is not in the list, a blank value will be
inserted.
Data type
Description
Note: The values are sorted in the order you enter them.
CHAR(size)
SET
Number types:
45
Data type
Description
BIGINT(size)
-9223372036854775808 to 9223372036854775807
normal. 0 to 18446744073709551615 UNSIGNED*.
The maximum number of digits may be specified in
parenthesis
*The integer types have an extra option called UNSIGNED. Normally, the
integer goes from an negative to positive value. Adding the UNSIGNED
attribute will move that range up so it starts at zero instead of a negative
number.
Date types:
Data type
Description
DATE()
TIME()
*Even if DATETIME and TIMESTAMP return the same format, they work
very differently. In an INSERT or UPDATE query, the TIMESTAMP
automatically set itself to the current date and time. TIMESTAMP also
accepts various formats, like YYYYMMDDHHMMSS,
YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.
characters
nvarchar(ma Variable-length Unicode data. Maximum
x)
536,870,912 characters
ntext
Binary types:
Character strings:
Data type
Description
Stora
ge
char(n)
varchar(n)
nchar(n)
bit
Allows 0, 1, or NULL
binary(n)
image
Stora
ge
Number types:
Unicode strings:
Description
Description
Data type
Data type
Stora
ge
Data type
Description
Stora
ge
tinyint
1 byte
smallint
int
bigint
32,767
bytes
4
bytes
8
bytes
5-17
bytes
float(n)
5-17
bytes
Data type
Description
Stora
ge
datetime
8
bytes
datetime2
4
bytes
money
bytes
Date types:
-922,337,203,685,477.5808 to
922,337,203,685,477.5807
4
bytes
date
3
bytes
time
3-5
bytes
48
timestamp
Description
sql_variant
cursor
table
SQL Functions
Tip: The aggregate functions and the scalar functions will be explained in
details in the next chapters.
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
950
Now we want to find the customers that have an OrderPrice value higher
then the average OrderPrice value.
We use the following SQL statement:
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
Nilsen
Jensen
The COUNT() function returns the number of rows that matches a specified
criteria.
O_Id
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
The result of the SQL statement above will be 2, because the customer
Nilsen has made 2 orders in total:
51
CustomerNilsen
NumberOfCustomers
3
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
52
The LAST() function returns the last value of the selected column.
2
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
O_Id
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
FirstOrderPrice
2008/09/03
300
Hansen
1000
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
LastOrderPrice
2008/09/03
300
Hansen
100
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
The MAX() function returns the largest value of the selected column.
LargestOrderPrice
2000
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
The MIN() function returns the smallest value of the selected column.
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
54
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
O_Id
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
SmallestOrderPrice
2008/09/03
300
Hansen
100
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
55
OrderTotal
O_Id
OrderDate
OrderPrice
Customer
5700
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
Customer SUM(OrderPrice)
56
Hansen
2000
Nilsen
1700
Jensen
2000
us the correct result. However, you have seen that the GROUP BY statement
solves this problem.
Hansen
5700
Nilsen
5700
Hansen
5700
Hansen
5700
Jensen
5700
The HAVING clause was added to SQL because the WHERE keyword
could not be used with aggregate functions.
Nilsen
5700
57
O_Id
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
2000
Jensen
2000
Now we want to find if any of the customers have a total order of less than
2000.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
Customer SUM(OrderPrice)
Nilsen
1700
58
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
LastName
FirstName
Svendson
Tove
Borgvn 23
Sandnes
HANSEN
Ola
Pettersen
Kari
Storgt 20
Stavanger
SVENDSON
Tove
PETTERSEN
Kari
59
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
Length
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Now we want to extract the first four characters of the "City" column above.
SmallCity
Sand
Sand
Stav
60
Now we want to select the length of the values in the "Address" column
above.
We use the following SELECT statement:
SELECT LEN(Address) as LengthOfAddress FROM Persons
12
The LEN() function returns the length of the value in a text field.
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
61
Parameter Description
column_nam Required. The field to round.
e
Decimals
Jarlsberg
10
Mascarpone
33
Gorgonzola
16
ProductName
Unit
UnitPrice
Jarlsberg
1000 g
10.45
Mascarpone
1000 g
32.56
Gorgonzola
1000 g
15.67
Now we want to display the product name and the price rounded to the
nearest integer.
We use the following SELECT statement:
UnitPrice
Prod_Id
ProductName
Unit
UnitPrice
Jarlsberg
1000 g
10.45
62
Mascarpone
1000 g
32.56
Gorgonzola
1000 g
15.67
Parameter Description
Now we want to display the products and prices per today's date.
We use the following SELECT statement:
SELECT ProductName, UnitPrice, Now() as PerDate FROM Products
UnitPrice
PerDate
Jarlsberg
10.45
10/7/2008 11:25:02 AM
Mascarpone
32.56
10/7/2008 11:25:02 AM
Gorgonzola
15.67
10/7/2008 11:25:02 AM
ProductName
Unit
UnitPrice
Jarlsberg
1000 g
10.45
Mascarpone
1000 g
32.56
Gorgonzola
1000 g
15.67
63
UnitPrice
PerDate
Jarlsberg
10.45
2008-10-07
Mascarpone
32.56
2008-10-07
Gorgonzola
15.67
2008-10-07
or
SELECT column_name
FROM table_name AS table_alias
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE
DATABASE
CREATE TABLE
CREATE INDEX
ALTER TABLE
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
or
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
DELETE
or
ALTER TABLE table_name
DROP COLUMN column_name
AS (alias)
64
IN (value1,value2,..)
or
INSERT INTO
or
DROP TABLE
GROUP BY
SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING
IN
SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name)
operator value
SELECT column_name(s)
FROM table_name
WHERE column_name
INNER JOIN
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
LEFT JOIN
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
RIGHT JOIN
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
FULL JOIN
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
65
LIKE
ORDER BY
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
UPDATE
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
SELECT
SELECT column_name(s)
FROM table_name
SELECT *
SELECT *
FROM table_name
SQL Hosting
SELECT TOP
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name
or
If you want your web site to be able to store and display data from a
database, your web server should have access to a database system that uses
the SQL language.
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
If your web server will be hosted by an Internet Service Provider (ISP), you
will have to look for SQL hosting plans.
The most common SQL hosting databases are MySQL, MS SQL Server, and
MS Access.
UNION ALL
SQL Hosting
You can have SQL databases on both Windows and Linux/UNIX operating
systems.
Below is an overview of which database system that runs on which OS.
MS SQL Server
Runs only on Windows OS.
66
MySQL
If you want to learn more about MySQL, please visit our PHP tutorial.
SQL Summary
This SQL tutorial has taught you the standard computer language for
accessing and manipulating database systems.
You have learned how to execute queries, retrieve data, insert new records,
delete records and update records in a database with SQL.
You have also learned how to create databases, tables, and indexes with
SQL, and how to drop them.
You have learned the most important aggregate functions in SQL.
You now know that SQL is the standard language that works with all the
well-known database systems like MS SQL Server, IBM DB2, Oracle,
MySQL, and MS Access.