Database Tables: SELECT FROM Persons
Database Tables: SELECT FROM Persons
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":
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 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
In this tutorial we will teach you all about the different SQL statements.
SELECT * Example
Now we want to select all the columns from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
Tip: The asterisk (*) is a quick way of selecting all columns!
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
This chapter will explain the SELECT DISTINCT statement.
This is wrong:
= Equal
<> Not equal
IN If you know the exact value you want to return for at least one of the columns
Note: In some versions of SQL the <> operator may be written as !=
The AND & OR operators are used to filter records based on more than one condition.
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola'
The result-set will look like this:
P_Id LastName FirstName Address City
SQL ORDER BY Keyword
« Previous Next Chapter »
ORDER BY Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
SQL INSERT INTO Statement
« Previous Next Chapter »
SQL UPDATE Statement
« Previous Next Chapter »
SQL DELETE Statement
« Previous Next Chapter »
or
Advance SQL
SQL TOP Clause
« Previous Next Chapter »
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
SQL Wildcards
« Previous Next Chapter »
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
% A substitute for zero or more characters
_ A substitute for exactly one character
SQL IN Operator
« Previous Next Chapter »
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,...)
IN Operator Example
The "Persons" table:
P_Id LastName FirstName Address City
SQL BETWEEN Operator
« Previous Next Chapter »
The BETWEEN operator is used in a WHERE clause to select a range of data between two values.
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
The result-set will look like this:
P_Id LastName FirstName Address City
SQL Alias
« Previous Next Chapter »
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.
An alias name could be anything, but usually it is short.
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name
AS alias_name
SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM table_name
Alias Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and
"po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
We use the following SELECT statement:
SELECT po.OrderID, p.LastName, p.FirstName
FROM Persons AS p,
Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola'
The same SELECT statement without aliases:
SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName
FROM Persons,
Product_Orders
WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'
As you'll see from the two SELECT statements above; aliases can make queries easier to both write and to read.
SQL Joins
« Previous Next Chapter »
SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.
SQL JOIN
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.
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be
unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Look at the "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 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.
SQL INNER JOIN Keyword
« Previous Next Chapter »
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons with any orders.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
SQL LEFT JOIN Keyword
« Previous Next Chapter »
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the orders with containing persons - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Hansen Ola 22456
SQL FULL JOIN Keyword
« Previous Next Chapter »
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
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
The result-set will look like this:
LastName FirstName OrderNo
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.
SQL UNION Operator
« Previous Next Chapter »
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
"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
The result-set will look like this:
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
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.
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
SQL SELECT INTO Statement
« Previous Next Chapter »
The SQL SELECT INTO statement can be used to create backup copies of tables.
SQL CREATE TABLE Statement
« Previous Next Chapter »
SQL Constraints
« Previous Next Chapter »
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the
ALTER TABLE statement).
We will focus on the following constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
The next chapters will describe each constraint in details.
SQL NOT NULL Constraint
« Previous Next Chapter »
By default, a table column can hold NULL values.
SQL UNIQUE Constraint
« Previous Next Chapter »
SQL PRIMARY KEY Constraint
« Previous Next Chapter »
2 44678 3
3 22456 2
4 24562 1
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 that invalid data form being inserted into the foreign key column, because it has to
be one of the values contained in the table it points to.
SQL CHECK Constraint
« Previous Next Chapter »
SQL CREATE INDEX Statement
« Previous Next Chapter »
Indexes
An index can be created in a table to find data more quickly and efficiently.
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.
SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes
in your database.
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
SQL ALTER TABLE Statement
« Previous Next Chapter »
SQL AUTO INCREMENT Field
« Previous Next Chapter »
Auto-increment allows a unique number to be generated when a new record is inserted into a table.
SQL Views
« Previous Next Chapter »
SQL Date Functions
« Previous Next Chapter »
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.
You can compare two dates easily if there is no time component involved!
Assume we have the following "Orders" table:
OrderId ProductName OrderDate
1 Geitost 2008-11-11
2 Camembert Pierrot 2008-11-09
Note: It is not possible to compare NULL and 0; they are not equivalent.
SQL IS NULL
How do we select only the records with NULL values in the "Address" column?
We will have to use the IS NULL operator:
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL
The result-set will look like this:
LastName FirstName Address
Hansen Ola
Pettersen Kari
SQL NULL Functions
« Previous Next Chapter »
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
We have the following SELECT statement:
SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products
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.
The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
In this case we want NULL values to be zero.
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL:
SQL Server / MS Access
SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products
Oracle
Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:
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
or we can use the COALESCE() function, like this:
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
SQL Data Types
« Previous Next Chapter »
Data types and ranges for Microsoft Access, MySQL and SQL Server.
Memo Memo is used for larger amounts of text. Stores up to 65,536 characters. Note: You
cannot sort a memo field. However, they are searchable
Byte Allows whole numbers from 0 to 255 1 byte
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal 8 bytes
places. Tip: You can choose which country's currency to use
AutoNumber AutoNumber fields automatically give each record its own number, usually starting at 4 bytes
1
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) up to 1GB
Hyperlink Contain links to other files, including web pages
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down list 4 bytes
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is
specified in parenthesis. Can store up to 255 characters
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum
size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value
than 255 it will be converted to a TEXT type
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is
inserted that is not in the list, a blank value will be inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one
choice
Number types:
Data type Description
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in
parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in
the size parameter. The maximum number of digits to the right of the decimal point is specified in
the d parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in
the size parameter. The maximum number of digits to the right of the decimal point is specified in
the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the right of the decimal
point is specified in the d parameter
*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() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch
('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a bytes
4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds 8 bytes
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
timestamp Stores a unique number that gets updated every time a row gets created or modified.
The timestamp value is based upon an internal clock and does not correspond to real
time. Each table may have only one timestamp variable
Other data types:
Data type Description
sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp