Introduction To SQL
Introduction To SQL
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
SQL is a Standard - BUT....
Although SQL is an ANSI/ISO 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!
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
To use a server-side scripting language, like PHP or ASP
To use SQL to get the data you want
To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Database Management System.
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.
Look at the "Customers" table:
Example
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields in the Customers table
consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country.
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.
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access
and MS SQL Server).
Below is a selection from the "Customers" table:
CustomerI CustomerName ContactName Address City PostalCode Country
D
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
SQL Statements
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
SELECT * FROM Customers;
In this tutorial we will teach you all about the different SQL statements.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
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:
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName, City FROM Customers
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
SQL SELECT DISTINCT Statement
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.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The following SQL statement selects ALL (including the duplicates) values from the "Country"
column in the "Customers" table:
Example
SELECT Country FROM Customers;
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
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Note: The example above will not work in Firefox and Microsoft Edge! Because
COUNT(DISTINCT column_name) is not supported in Microsoft Access databases. Firefox and
Microsoft Edge are using Microsoft Access in our examples.
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
SQL WHERE Clause
The SQL WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE,
DELETE statement, etc.!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico
Emparedados y helados 2222
3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow double
quotes).
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Operators in The WHERE Clause
<> Not equal. Note: In some versions of SQL SELECT * FROM Products
this operator may be written as != WHERE Price <> 18;
BETWEEN Between a certain range SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;
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 are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
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.
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany"
OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
Combining AND, OR and NOT
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
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany" and NOT "USA":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
SQL ORDER BY Keyword
The SQL ORDER BY Keyword
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
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
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.
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
ORDER BY Several Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted ascending
by the "Country" and descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
SQL INSERT INTO Statement
The SQL INSERT INTO Statement
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:
89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B
The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B
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
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
If a field in a table is optional, it is possible to insert a new record or update a record without
adding a value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a
NULL value is one that has been left blank during record creation!
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
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.
UPDATE Table
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.
4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
Update Warning!
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
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) 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 Sq. London WA1 1DP UK
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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:
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
Example
DELETE FROM Customers;
SQL TOP, LIMIT or ROWNUM Clause
The SQL SELECT TOP Clause
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 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
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT clause:
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM:
Example
SELECT * FROM Customers
WHERE ROWNUM <= 3;
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the records from the "Customers" table:
Example
SELECT TOP 50 PERCENT * FROM Customers;
ADD a WHERE CLAUSE
The following SQL statement selects the first three records from the "Customers" table, where
the country is "Germany":
Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example using the LIMIT clause:
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example using ROWNUM:
Example
SELECT * FROM Customers
WHERE Country='Germany' AND ROWNUM <= 3;
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() Functions
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
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
Practical
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Exercises