This Ebook Is Created by WWW - Ebooktutorials.in
This Ebook Is Created by WWW - Ebooktutorials.in
This Ebook Is Created by WWW - Ebooktutorials.in
All
Copyrights reserved to www.w3schools.com
Although SQL is an ANSI (American National Standards Institute) standard, there are
different versions of the SQL language.
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!
To build a web site that shows data from a database, you will need:
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of
related data entries and it consists of columns and rows.
Every table is broken up into smaller entities called fields. The fields in the Customers
table consist of CustomerID, CustomerName, ContactName, Address, City and
PostalCode. A field is a column in a table that is designed to maintain specific
information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For example,
there are 91 records in the above Customers table. A record is a horizontal entity in a
table.
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
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.
In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS
SQL Server).
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The table above contains five records (one for each customer) and seven columns (CustomerID,
CustomerName, ContactName, Address, City, PostalCode, and Country).
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example
In this tutorial we will teach you all about the different SQL statements.
SQL keywords are NOT case sensitive: select is the same as SELECT
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more
than one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.
SELECT Syntax
Here, column1, column2, ... are the field names of the table you want to select data from. If you want
to select all the fields available in the table, use the following syntax:
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table:
Example
The following SQL statement selects all the columns from the "Customers" table:
Example
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
The SELECT DISTINCT statement is used to return only distinct (different) values.
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all (and duplicate) values from the "Country" column in the
"Customers" table:
Example
Now, let us use the DISTINCT keyword with the above SELECT statement and see the result.
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
Example
Example
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE
statement, etc.!
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all the customers from the country "Mexico", in the "Customers"
table:
Example
SQL requires single quotes around text values (most database systems will also allow double quotes).
Example
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is TRUE. The
OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
OR Syntax
NOT Syntax
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is
"Berlin":
Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city
must be "Berlin" OR "München" (use parenthesis to form complex expressions):
Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and
NOT "USA":
Example
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:
Example
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by
the "Country" column:
Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
and the "CustomerName" column:
Example
The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:
Example
The first way specifies both the column names and the values to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the column names
in the SQL query. However, make sure the order of the values is in the same order as the columns in
the table. The INSERT INTO syntax would be as follows:
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement inserts a new record in the "Customers" table:
Example
The selection from the "Customers" table will now look like this:
Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically when a
new record is inserted into the table.
The following SQL statement will insert a new record, but only insert data in the "CustomerName",
"City", and "Country" columns (CustomerID will be updated automatically):
Example
The selection from the "Customers" table will now look like this:
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person
and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
It is the WHERE clause that determines how many records that will be updated.
The following SQL statement will update the contactname to "Juan" for all records where country is
"Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
DELETE Syntax
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) that should be deleted. If you omit the
WHERE clause, all records in the table will be deleted!
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
Example
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
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:
or:
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of
records can impact on performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause
to select a limited number of records, while Oracle uses ROWNUM.
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the first three records from the "Customers" table:
Example
The following SQL statement shows the equivalent example using the LIMIT clause:
Example
The following SQL statement shows the equivalent example using ROWNUM:
Example
The following SQL statement selects the first 50% of the records from the "Customers" table:
Example
The following SQL statement selects the first three records from the "Customers" table, where the
country is "Germany":
Example
The following SQL statement shows the equivalent example using the LIMIT clause:
Example
The following SQL statement shows the equivalent example using ROWNUM:
Example
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement finds the price of the cheapest product:
Example
The following SQL statement finds the price of the most expensive product:
Example
The COUNT() function returns the number of rows that matches a specified criteria.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
Example
SELECT COUNT(ProductID)
FROM Products;
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Below is a selection from the "OrderDetails" table in the Northwind sample database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all customers with a CustomerName starting with "a":
Example
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
The following SQL statement selects all customers with a CustomerName that have "or" in any position:
Example
The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:
Example
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at
least 3 characters in length:
Example
The following SQL statement selects all customers with a CustomerName that starts with "a" and ends
with "o":
Example
The following SQL statement selects all customers with a CustomerName that NOT starts with "a":
Example
Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE clause
to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all customers with a City starting with "ber":
Example
The following SQL statement selects all customers with a City containing the pattern "es":
Example
The following SQL statement selects all customers with a City starting with any character, followed by
"erlin":
Example
The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
Example
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
Example
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
The two following SQL statements selects all customers with a City NOT starting with "b", "s", or "p":
Example
Or:
Example
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects all customers that are located in "Germany", "France" and "UK":
Example
The following SQL statement selects all customers that are NOT located in "Germany", "France" or
"UK":
Example
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
The following SQL statement selects all products with a price BETWEEN 10 and 20. In addition; do not
show products with a CategoryID of 1,2, or 3:
Example
The following SQL statement selects all products with a ProductName BETWEEN 'Carnarvon Tigers' and
'Mozzarella di Giovanni':
Example
The following SQL statement selects all products with a ProductName NOT BETWEEN 'Carnarvon Tigers'
and 'Mozzarella di Giovanni':
Example
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
The following SQL statement selects all orders with an OrderDate BETWEEN '04-July-1996' and
'09-July-1996':
Example
SQL aliases are used to give a table, or a column in a table, a temporary name.
SELECT column_name(s)
FROM table_name AS alias_name;
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
10354 58 8 1996-11-14 3
10355 4 6 1996-11-15 1
10356 86 6 1996-11-18 2
The following SQL statement creates two aliases, one for the CustomerID column and one for the
CustomerName column:
Example
The following SQL statement creates two aliases, one for the CustomerName column and one for the
ContactName column. Note: It requires double quotation marks or square brackets if the alias name
contains spaces:
Example
The following SQL statement creates an alias named "Address" that combine four columns (Address,
PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS
Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the
Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o"
respectively (Here we use aliases to make the SQL shorter):
Example
The following SQL statement is the same as above, but without aliases:
Example
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records
that have matching values in both tables:
Example
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from
the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
The INNER JOIN keyword selects records that have matching values in both tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement selects all orders with customer information:
Example
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between
the columns. If there are records in the "Orders" table that do not have matches in "Customers", these
orders will not show!
The following SQL statement selects all orders with customer and shipper information:
Example
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from
the right table (table2). The result is NULL from the right side, if there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will select all customers, and any orders they might have:
Example
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there are no
matches in the right table (Orders).
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records
from the left table (table1). The result is NULL from the left side, when there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will return all employees, and any orders they might have have placed:
Example
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if there are
no matches in the left table (Orders).
The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right
(table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement selects all customers, and all orders:
CustomerName OrderID
Alfreds Futterkiste
10382
10351
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all the
rows from the right table (Orders). If there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will be
listed as well.
A self JOIN is a regular join, but the table is joined with itself.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
The following SQL statement matches customers that are from the same city:
Example
The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
UNION Syntax
Note: The column names in the result-set are usually equal to the column names in the first SELECT
statement in the UNION.
2 New Orleans Cajun Shelley Burke P.O. Box New 70117 USA
Delights 78934 Orleans
The following SQL statement selects all the different cities (only distinct values) from "Customers" and
"Suppliers":
Example
Note: If some customers or suppliers have the same city, each city will only be listed once, because
UNION selects only distinct values. Use UNION ALL to also select duplicate values!
The following SQL statement selects all cities (duplicate values also) from "Customers" and "Suppliers":
Example
The following SQL statement selects all the different German cities (only distinct values) from
"Customers" and "Suppliers":
Example
The following SQL statement selects all German cities (duplicate values also) from "Customers" and
"Suppliers":
Example
Example
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to
group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement lists the number of customers in each country:
Example
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
The following SQL statement lists the number of orders sent by each shipper:
Example
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement lists the number of customers in each country. Only include countries with
more than 5 customers:
Example
The following SQL statement lists the number of customers in each country, sorted high to low (Only
include countries with more than 5 customers):
Example
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
The following SQL statement lists the employees that have registered more than 10 orders:
Example
The following SQL statement lists if the employees "Davolio" or "Fuller" have registered more than 25
orders:
Example
The SELECT INTO statement copies data from one table into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in the old
table. You can create new column names using the AS clause.
The following SQL statement uses the IN clause to copy the table into a new table in
another database:
The following SQL statement copies only a few columns into a new table:
The following SQL statement copies only the German customers into a new table:
The following SQL statement copies data from more than one table into a new table:
Tip: SELECT INTO can also be used to create a new, empty table using the schema of
another. Just add a WHERE clause that causes the query to return no data:
The INSERT INTO SELECT statement copies data from one table and inserts it into another table.
INSERT INTO SELECT requires that data types in source and target tables match
The existing records in the target table are unaffected
Copy only some columns from one table into another table:
2 New Orleans Shelley Burke P.O. Box New 70117 USA (100)
Cajun Delights 78934 Orleans 555-4822
The following SQL statement copies "Suppliers" into "Customers" (the columns that are not filled with
data, will contain NULL):
Example
The following SQL statement copies "Suppliers" into "Customers" (fill all columns):
Example
The following SQL statement copies only the German suppliers into "Customers":
Example
Tip: Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
Tip: Make sure you have admin privilege before dropping any database. Once a
database is dropped, you can check it in the list of databases with the following
SQL command: SHOW DATABASES;
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
The LastName, FirstName, Address, and City columns are of type varchar and will hold
characters, and the maximum length for these fields is 255 characters.
Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO
statement.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table gets the same column definitions. All columns or specific columns can be
selected.
If you create a new table using an existing table, the new table will be filled with the
existing values from the old table.
Note: Be careful before dropping a table. Deleting a table will result in loss of
complete information stored in the table!
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing 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:
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.
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or
four-digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will
NOT accept NULL values:
Tip: If the table has already been created, you can add a NOT NULL constraint to a
column with the ALTER TABLE statement.
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons"
table is created:
MySQL:
To create a UNIQUE constraint on the "ID" column when the table is already created,
use the following SQL:
MySQL:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table
is created:
MySQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However,
the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
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).
MySQL:
"Persons" table:
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
"Orders" table:
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" 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.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already
created, use the following SQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:
MySQL:
The CHECK constraint is used to limit the value range that can be placed in a column.
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.
The following SQL creates a CHECK constraint on the "Age" column when the "Persons"
table is created. The CHECK constraint ensures that you can not have any person below
18 years:
MySQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
To create a CHECK constraint on the "Age" column when the table is already created,
use the following SQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
MySQL:
The default value will be added to all new records IF no other value is specified.
The following SQL sets a DEFAULT value for 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:
Indexes are used to retrieve data from the database very fast. 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, only create indexes on
columns that will be frequently searched against.
Note: The syntax for creating indexes varies among different databases. Therefore:
Check the syntax for creating indexes in your database.
The SQL statement below creates an index named "idx_lastname" on the "LastName"
column in the "Persons" table:
If you want to create an index on a combination of columns, you can list the column
names within the parentheses, separated by commas:
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
Often this is the primary key field that we would like to be created automatically every
time a new record is inserted.
The following SQL statement defines the "ID" column to be an auto-increment primary
key field in the "Persons" table:
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for
each new record.
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".
The following SQL statement defines the "ID" column to be an auto-increment primary
key field in the "Persons" table:
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
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".
The following SQL statement defines the "ID" column to be an auto-increment primary
key field in the "Persons" table:
By default, the starting value for AUTOINCREMENT 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 the autoincrement to AUTOINCREMENT(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
"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".
A view contains rows and columns, just like a real table. The fields in 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 one single table.
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.
If you have the Northwind database you can see that it has several 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 view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:
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":
We can also add a condition to the query. Let's see the total sale only for the category
"Beverages":
Now we want to add the "Category" column to the "Current Product List" view. We will
update the view with the following SQL:
In the previous chapters, you have learned to retrieve (and update) database data,
using SQL.
When SQL is used to display data on a web page, it is common to let web users input
their own search values.
Since SQL statements are text only, it is easy, with a little piece of computer code, to
dynamically change SQL statements to provide the user with selected data:
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user input in SQL
statements.
SQL injection is a technique where malicious users can inject SQL commands into an
SQL statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web
application.
Let's say that the original purpose of the code was to create an SQL statement to select
a user with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can enter
some "smart" input like this:
UserId:
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1
is always true.
Does the example above seem dangerous? What if the Users table contains names and
passwords?
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A smart hacker might get access to all the user names and passwords in a database by
simply inserting 105 or 1=1 into the input box.
User Name:
Password:
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="'
+ uPass + '"'
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
A smart hacker might get access to user names and passwords in a database by simply
inserting " or ""=" into the user name or password text box:
User Name:
Password:
The code at the server will create a valid SQL statement like this:
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since WHERE ""=""
is always true.
The SQL above will return all rows in the Users table, and then delete the table called
Suppliers.
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
User id:
The code at the server would create a valid SQL statement like this:
Some web developers use a "blacklist" of words or characters to search for in SQL
input, to prevent SQL injection attacks.
This is not a very good idea. Many of these words (like delete or drop) and characters
(like semicolons and quotation marks), are used in common language, and should be
allowed in many types of input.
(In fact it should be perfectly legal to input an SQL statement in a database field.)
The only proven way to protect a web site from SQL injection attacks, is to use SQL
parameters.
SQL parameters are values that are added to an SQL query at execution time, in a
controlled manner.
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId =
@0"; db.Execute(txtSQL,txtUserId);
The SQL engine checks each parameter to ensure that it is correct for its column and
are treated literally, and not as part of the SQL to be executed.
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
You have just learned to avoid SQL injection. One of the top website
vulnerabilities.
The following examples shows how to build parameterized queries in some common
web languages.
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId =
@0"; command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
If you want your web site to be able to store and retrieve data from a database, your
web server should have access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look
for SQL hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS
Access.
Microsoft's SQL Server is a popular database software for database-driven web sites
with high traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Oracle is also a popular database software for database-driven web sites with high
traffic.
Oracle is a very powerful, robust and full featured SQL database system.
MySQL is a very powerful, robust and full featured SQL database system.
When a web site requires only a simple database, Microsoft Access can be a solution.
Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL
Server, or Oracle.
SQL aggregate functions return a single value, calculated from values in a column.
Function Description
Function Description
CONCAT()
LEFT()
LTRIM()
PATINDEX()
REPLACE()
RIGHT()
RTRIM()
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement gets the average value of the "Price" column from the "Products" table:
Example
The following SQL statement selects the "ProductName" and "Price" records that have an above
average price:
Example
The COUNT() function returns the number of rows that matches a specified criteria.
The COUNT(column_name) function returns the number of values (NULL values will not
be counted) of the specified column:
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1
The following SQL statement counts the number of orders from "CustomerID"=7 from
the "Orders" table:
The following SQL statement counts the total number of orders in the "Orders" table:
The following SQL statement counts the number of unique customers in the "Orders"
table:
The FIRST() function returns the first value of the selected column.
Example
MySQL Syntax
Example
Oracle Syntax
Example
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the first value of the "CustomerName" column from the
"Customers" table:
Example
The LAST() function returns the last value of the selected column.
Example
MySQL Syntax
Example
Oracle Syntax
Example
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the last value of the "CustomerName" column from the
"Customers" table:
Example
The MAX() function returns the largest value of the selected column.
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
The following SQL statement gets the largest value of the "Price" column from the
"Products" table:
The MIN() function returns the smallest value of the selected column.
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement gets the smallest value of the "Price" column from the "Products" table:
Example
The ROUND() function is used to round a numeric field to the number of decimals specified.
Note: Many database systems do rounding differently than you might expect. When rounding a number
with a fractional part to an integer, our school teachers told us to round .1 through .4 DOWN to the
next lower integer, and .5 through .9 UP to the next higher integer. But if all the digits 1 through 9 are
equally likely, this introduces a slight bias towards infinity, since we always round .5 up. Many database
systems have adopted the IEEE 754 standard for arithmetic operations, according to which the default
rounding behavior is "round half to even." In this scheme, .5 is rounded to the nearest even integer.
So, both 11.5 and 12.5 would be rounded to 12.
Parameter Description
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement selects the product name and rounds the price in the "Products" table:
Example
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
The following SQL statement finds the sum of all the "Quantity" fields for the "OrderDetails" table:
Example
The LEN() function returns the length of the value in a text field.
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the "CustomerName" and the length of the values in the "Address"
column from the "Customers" table:
Example
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table, and converts the "CustomerName" column to lowercase:
Example
Parameter Description
length Optional. The number of characters to return. If omitted, the MID() function
returns the rest of the text
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the first four characters from the "City" column from the
"Customers" table:
Example
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table, and converts the "CustomerName" column to uppercase:
Example
The following table lists the most important built-in date functions in MySQL:
Function Description
The following table lists the most important built-in date functions in SQL Server:
Function Description
Function Description
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 more complicated.
MySQL comes with the following data types for storing a date or a date/time value in the database:
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
Note: The date types are chosen for a column when you create a new table in your database!
For an overview of all data types available, go to our complete Data Types reference.
You can compare two dates easily if there is no time component involved!
1 Geitost 2008-11-11
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
1 Geitost 2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
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!
NOW()
SELECT NOW(),CURDATE(),CURTIME()
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies NOW() as the default value. As a result,
when you insert a row into the table, the current date and time are automatically
inserted into the column.
CURDATE()
SELECT NOW(),CURDATE(),CURTIME()
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies CURRENT_TIMESTAMP as the default value.
As a result, when you insert a row into the table, the current date and time are
automatically inserted into the column.
CURTIME()
SELECT NOW(),CURDATE(),CURTIME()
The DATE() function extracts the date part of a date or date/time expression.
DATE(date)
ProductName OrderDate
The EXTRACT() function is used to return a single part of a date/time, such as year,
month, day, hour, minute, etc.
Where date is a valid date expression and unit can be one of the following:
Unit Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
2014 11 22
Where date is a valid date expression and expr is the number of interval you want to
add.
Type Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Now we want to add 30 days to the "OrderDate", to find the payment date.
Result:
OrderId OrderPayDate
1 2014-12-22 13:23:44.657
Where date is a valid date expression and expr is the number of interval you want to
subtract.
Type Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Result:
OrderId SubtractDate
1 2014-11-17 13:23:44.657
DATEDIFF(date1,date2)
Note: Only the date parts of the values are used in the calculation.
DiffDate
DiffDate
-1
DATE_FORMAT(date,format)
Where date is a valid date and format specifies the output format for the date/time.
Format Description
%f Microseconds (000000-999999)
%H Hour (00-23)
%h Hour (01-12)
%I Hour (01-12)
%k Hour (0-23)
%l Hour (1-12)
%p AM or PM
%S Seconds (00-59)
%s Seconds (00-59)
%V Week (01-53) where Sunday is the first day of week, used with %X
%v Week (01-53) where Monday is the first day of week, used with %x
%X Year for the week where Sunday is the first day of week, four digits,
used with %V
%x Year for the week where Monday is the first day of week, four digits,
used with %v
The following script uses the DATE_FORMAT() function to display different formats. We
will use the NOW() function to get the current date/time:
The GETDATE() function returns the current date and time from the SQL Server.
GETDATE()
CurrentDateTime
2014-11-22 12:45:34.243
Note: The time part above goes all the way to milliseconds.
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies GETDATE() as the default value. As a result,
when you insert a row into the table, the current date and time are automatically
inserted into the column.
The DATEPART() function is used to return a single part of a date/time, such as year,
month, day, hour, minute, etc.
DATEPART(datepart,date)
Where date is a valid date expression and datepart can be one of the following:
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
2014 11 22
The DATEADD() function adds or subtracts a specified time interval from a date.
DATEADD(datepart,number,date)
Where date is a valid date expression and number is the number of interval you want to
add. The number can either be positive, for dates in the future, or negative, for dates in
the past.
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Now we want to add 30 days to the "OrderDate", to find the payment date.
Result:
OrderId OrderPayDate
1 2014-12-22 13:23:44.657
DATEDIFF(datepart,startdate,enddate)
Where startdate and enddate are valid date expressions and datepart can be one of the
following:
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Result:
DiffDate
61
Now we want to get the number of days between two dates (notice that the second
date is "earlier" than the first date, and will result in a negative number).
Result:
DiffDate
-61
The CONVERT() function is a general function that converts an expression of one data
type to another.
The CONVERT() function can be used to display date/time data in different formats.
CONVERT(data_type(length),expression,style)
Value Description
style Specifies the output format for the date/time (see table
below)
6 106 6 = dd mon yy -
106 = dd mon yyyy
8 108 hh:mm:ss -
spaces)
The following script uses the CONVERT() function to display different formats. We will
use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
Parameter Description
2 Chang 1 1 24 - 12 oz bottles 19
The following SQL statement selects the product name, and price for today (formatted like
YYYY-MM-DD) from the "Products" table:
Example
The NOW() function returns the current system date and time.
1 Chais 1 1 10 boxes x 18
20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
The following SQL statement selects the product name, and price for today from the
"Products" table:
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.
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.
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL()
returns a zero if the value is NULL:
MS Access
SELECT ProductName,UnitPrice*
(UnitsInStock+IIF(ISNULL(UnitsOnOrder),0,UnitsOnOrder))
FROM Products
SQL Server
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.
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulo
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
Operator Description
= Equal to
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
Note: ALL and ANY are not supported in Web SQL databases. Chrome, Safari and
Opera are using Web SQL in our examples.
Operator Description
Each column in a database table is required to have a name and a data type.
SQL developers have to decide what types of data will be stored inside each and every
table column when creating a SQL table. The data type is a label and a guideline for
SQL to understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
TIMESTAMP Stores year, month, day, hour, minute, and second values
However, different databases offer different choices for the data type definition.
The following table shows some of the common names of data types between the
various database platforms:
Note: Data types might have different names in different database. And even if
the name is the same, the size and other details may be different! Always check
the documentation!
Data types and ranges for Microsoft Access, MySQL and SQL Server.
Ole Object Can store pictures, audio, video, or other BLOBs (Binary up to
Large OBjects) 1GB
Lookup Let you type a list of options, which can then be chosen 4 bytes
Wizard from a drop-down list
In MySQL there are three main data types : text, number, and Date/Time types.
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
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.
SET Similar to ENUM except that SET may contain up to 64 list items
and can store more than one choice
*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.
*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 YYYYMMDDHHMISS,
YYMMDDHHMISS, YYYYMMDD, or YYMMDD.
datetimeoffset The same as datetime2 with the addition of a time zone 8-10
offset bytes
or
or
SELECT column_name
FROM table_name AS table_alias
or
or
or
SELECT * SELECT *
FROM table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name