Data Base Chapter Seven
Data Base Chapter Seven
Introduction to SQL
What is SQL?
SQL stands for Structured Query Language
SQL allows you to access a database
SQL is an ANSI standard computer language
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
SQL can update records in a database
SQL is easy to learn
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:
Note: Some database systems require a semicolon at the end of the SQL statement.
We don't use the semicolon in our tutorials.
"Persons" table
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Result
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Using Quotes
Note that we have used single quotes around the conditional values in the examples.
SQL uses single quotes around text values (most database systems will also accept
double quotes). Numeric values should not be enclosed in quotes.
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
This is correct:
SELECT * FROM Persons WHERE Year>1965
This is wrong:
SELECT * FROM Persons WHERE Year>'1965'
A "%" sign can be used to define wildcards (missing letters in the pattern) both
before and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start with an
'O':
The following SQL statement will return persons with first names that end with an
'a':
The following SQL statement will return persons with first names that contain the
pattern 'la':
You can also specify the columns for which you want to insert data:
Person:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67
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
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:
Result
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
SQL ORDER BY
The ORDER BY keyword is used to sort the result.
Example
To display the companies in alphabetical order:
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 6798
W3Schools 2312
Example
To display the companies in alphabetical order AND the ordernumbers in numerical
order:
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 2312
W3Schools 6798
Result:
Company OrderNumber
W3Schools 6798
W3Schools 2312
Sega 3412
ABC Shop 5678
Example
To display the companies in reverse alphabetical order AND the ordernumbers in
numerical order:
Result:
Company OrderNumber
W3Schools 2312
W3Schools 6798
Sega 3412
ABC Shop 5678
Example
Use AND to display each person with the first name equal to "Tove", and the last
name equal to "Svendson":
Result:
LastName FirstName Address City
Svendson Tove Borgvn 23 Sandnes
Example
Use OR to display each person with the first name equal to "Tove", or the last name
equal to "Svendson":
Result:
LastName FirstName Address City
Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes
Example
You can also combine AND and OR (use parentheses to form complex
expressions):
SELECT * FROM Persons WHERE
(FirstName='Tove' OR FirstName='Stephen')
AND LastName='Svendson'
Result:
SQL IN
IN
The IN operator may be used if you know the exact value you want to return for at
least one of the columns.
Example 1
To display the persons with LastName equal to "Hansen" or "Pettersen", use the
following SQL:
Result:
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Pettersen Kari Storgt 20 Stavanger
SQL Alias
With SQL, aliases can be used for column names and table names.
Orders:
Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
865 Chair 03
Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result
Name
Hansen, Ola
SQL UNION
The UNION command is used to select related information from two tables, much like
the JOIN command. However, when using the UNION command all selected columns
need to be of the same data type.
Note: With UNION, only distinct values are selected.
SQL Statement 1
UNION
SQL Statement 2
Employees_Norway:
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
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 is
listed. The UNION command only selects distinct values.
Example
This example demonstrates how you can create a table named "Person", with four
columns. The column names will be "LastName", "FirstName", "Address", and "Age":
This example demonstrates how you can specify a maximum length for some
columns:
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by
the constraint.
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already
created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)
Let's illustrate the foreign key with an example. Look at the following two tables:
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 "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it
points to.
MySQL:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
MySQL:
If you define a CHECK constraint on a single column it allows only certain values for
this column.
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.
MySQL:
MySQL:
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:
The DEFAULT constraint can also be used to insert system values, by using functions
like GETDATE():
To create a DEFAULT constraint on the "City" column when the table is already
created, use the following SQL:
MySQL:
Oracle:
MySQL:
Create Index
Indices are created in an existing table to locate rows more quickly 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 see the indexes, they are just used to speed up
queries.
Note: Updating a table containing indexes takes more time than 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.
A Unique Index
Creates a unique index on a table. A unique index means that two rows cannot have
the same index value.
If you want to index the values in a column in descending order, you can add the
reserved word
DESC after the column name
If you want to index more than one column you can list the column names within the
parentheses, separated by commas:
To delete a database:
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):
Person:
LastName FirstName Address
Pettersen Kari Storgt 20
Example
To add a column named "City" in the "Person" table:
Example
To drop the "Address" column in the "Person" table:
Result:
LastName FirstName City
Pettersen Kari
SQL Functions
SQL has a lot of built-in functions for counting and calculations.
Function Syntax
The syntax for built-in SQL functions is:
Types of Functions
There are several basic types and categories of functions in SQL. The basic types of
functions are:
Aggregate Functions
Scalar functions
Aggregate functions
Aggregate functions operate against a collection of values, but return a single value.
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)
Name Age
Hansen, Ola 34
Svendson, Tove 45
Pettersen, Kari 19
BINARY_CHECKSUM
CHECKSUM
CHECKSUM_AGG
COUNT(column) Returns the number of rows (without a NULL value) of
STDEV(column)
STDEVP(column)
SUM(column) Returns the total sum of a column
VAR(column)
VARP(column)
GROUP BY...
GROUP BY... was added to SQL because aggregate functions (like SUM) return the
aggregate of all column values every time they are called, and without the GROUP
BY function it was impossible to find the sum for each individual group of column
values.
The syntax for the GROUP BY function is:
GROUP BY Example
This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
The above code is invalid because the column returned is not part of an aggregate. A
GROUP BY clause will solve this problem:
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:
DROP
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table.
To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
To change the data type of a column in a table, use the following syntax:
My SQL / Oracle:
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.
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.
DROP COLUMN
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
To let the AUTO_INCREMENT sequence start with another value, use the following
SQL statement:
To insert a new record into the "Persons" table, we will NOT have to specify a value
for the "ID" column (a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table. The
"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".
In the example above, the starting value for IDENTITY is 1, and it will increment by
1 for each new record.
Tip: To specify that the "ID" column should start at value 10 and increment by 5,
change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value
for the "ID" column (a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table. The
"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".
By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for
each new record.
To insert a new record into the "Persons" table, we will NOT have to specify a value
for the "ID" column (a unique value will be added automatically):
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".
You will have to create an auto-increment field with the sequence object (this object
generates a number sequence).
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):
The SQL statement above would insert a new record into the "Persons" table. The
"ID" column would be assigned the next number from the seq_person sequence. The
"FirstName" column would be set to "Lars" and the "LastName" column would be set
to "Monsen".
What is a View?
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:
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":
We can also add a condition to the query. Now we want to see the total sale only for
the category "Beverages":