Introduction To SQL: What Is SQL? SQL Data Manipulation Language (DML)
Introduction To SQL: What Is SQL? SQL Data Manipulation Language (DML)
Svendson
Pettersen
SQL is a standard computer language for accessing and manipulating
databases.
Note: Some database systems require a semicolon at the end of the
SQL statement. We don't use the semicolon in our tutorials.
What is SQL?
SQL stands for Structured Query Language SQL Data Manipulation Language (DML)
SQL allows you to access a database
SQL is an ANSI standard computer language SQL (Structured Query Language) is a syntax for executing queries.
SQL can execute queries against a database But the SQL language also includes a syntax to update, insert, and
SQL can retrieve data from a database delete records.
SQL can insert new records in a database
SQL can delete records from a database
SQL can update records in a database These query and update commands together form the Data
Manipulation Language (DML) part of SQL:
SQL is easy to learn
SELECT - extracts data from a database table
UPDATE - updates data in a database table
DELETE - deletes data from a database table
SQL is a Standard - BUT.... INSERT INTO - inserts new data into a database table
The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).
SQL Queries
With SQL, we can query a database and have a result set returned.
LastName
SQL DML Statements functions, like: Move-To-First-Record, Get-Record-Content, Move-
To-Next-Record, etc.
SQL SELECT Statement Programming functions like these are not a part of this tutorial. To
learn about accessing data with function calls, please visit our ADO
tutorial.
The SQL SELECT Statement
Some SQL tutorials end each SQL statement with a semicolon. Is this
Note: SQL statements are not case sensitive. SELECT is the same necessary? We are using MS Access and SQL Server 2000 and we do
as select. not have to put a semicolon after each SQL statement, but some
database programs force you to use it.
SELECT LastName,FirstName FROM Persons The SELECT statement returns information from table columns. But
what if we only want to select distinct elements?
The database table "Persons":
With SQL, all we need to do is to add a DISTINCT keyword to the
SELECT statement:
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes Syntax
Svendson Tove Borgvn 23 Sandnes SELECT DISTINCT column_name(s)
FROM table_name
Pettersen Kari Storgt 20 Stavanger
The result
Using the DISTINCT keyword
LastName FirstName
Hansen Ola To select ALL values from the column named "Company" we use a
SELECT statement like this:
Svendson Tove
Pettersen Kari
SELECT Company FROM Orders
"Orders" table
Select All Columns
Company OrderNumber
To select all columns from the "Persons" table, use a * symbol
instead of column names, like this: Sega 3412
W3Schools 2312
SELECT * FROM Persons
Trio 4678
W3Schools 6798
Result
Result
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes Company
Svendson Tove Borgvn 23 Sandnes Sega
Pettersen Kari Storgt 20 Stavanger W3Schools
Trio
W3Schools
The Result Set Note that "W3Schools" is listed twice in the result-set.
The result from a SQL query is stored in a result-set. Most database To select only DIFFERENT values from the column named
software systems allow navigation of the result set with programming "Company" we use a SELECT DISTINCT statement like this:
SELECT DISTINCT Company FROM Orders Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Result:
Using Quotes
Company
Sega
Note that we have used single quotes around the conditional values in
W3Schools the examples.
Trio
SQL uses single quotes around text values (most database systems
Now "W3Schools" is listed only once in the result-set. will also accept double quotes). Numeric values should not be
enclosed in quotes.
To conditionally select data from a table, a WHERE clause can be This is correct:
SELECT * FROM Persons WHERE Year>1965
added to the SELECT statement. This is wrong:
SELECT * FROM Persons WHERE Year>'1965'
Syntax
SELECT column FROM table
WHERE column operator value
The LIKE Condition
With the WHERE clause, the following operators can be used:
The LIKE condition is used to specify a search for a pattern in a
column.
Operator Description
= Equal Syntax
<> Not equal SELECT column FROM table
WHERE column LIKE pattern
> Greater than
< Less than
>= Greater than or equal A "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Using LIKE
Note: In some versions of SQL the <> operator may be written as !=
The following SQL statement will return persons with first names
that start with an 'O':
"Persons" table
The following SQL statement will return persons with first names
that contain the pattern 'la':
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951 SELECT * FROM Persons
Svendson Tove Borgvn 23 Sandnes 1978 WHERE FirstName LIKE '%la%'
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960
Result
SQL ORDER BY
The ORDER BY keyword is used to sort the result.
LastName FirstName Address City Year
Example
Sort the Rows To display the companies in reverse alphabetical order AND the
ordernumbers in numerical order:
The ORDER BY clause is used to sort the rows.
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC, OrderNumber ASC
Orders:
Result:
Company OrderNumber
Sega 3412
ABC Shop 5678 Company OrderNumber
W3Schools 2312 W3Schools 2312
W3Schools 6798 W3Schools 6798
Sega 3412
ABC Shop 5678
Example
Result: Use AND to display each person with the first name equal to "Tove",
and the last name equal to "Svendson":
Company OrderNumber
SELECT * FROM Persons
ABC Shop 5678 WHERE FirstName='Tove'
Sega 3412 AND LastName='Svendson'
W3Schools 2312
W3Schools 6798 Result:
Result:
Example 1
LastName FirstName Address City
To display the persons alphabetically between (and including)
Svendson Tove Borgvn 23 Sandnes "Hansen" and exclusive "Pettersen", use the following SQL:
Svendson Stephen Kaivn 18 Sandnes
SELECT * FROM Persons WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
SQL IN Result:
IN
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
The IN operator may be used if you know the exact value you want to
return for at least one of the columns. Nordmann Anna Neset 18 Sandnes
Example 2
Example 1
To display the persons outside the range used in the previous
To display the persons with LastName equal to "Hansen" or example, use the NOT operator:
"Pettersen", use the following SQL:
SELECT * FROM Persons WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
Result:
Result:
LastName FirstName Address City
LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger
Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
SQL Alias
SQL BETWEEN
With SQL, aliases can be used for column names and table names.
BETWEEN ... AND
The BETWEEN ... AND operator selects a range of data between two
values. These values can be numbers, text, or dates. Column Name Alias
Example
SQL JOIN
Who ordered a printer?
Joins and Keys
SELECT Employees.Name
FROM Employees, Orders
Sometimes we have to select data from two or more tables to make WHERE Employees.Employee_ID=Orders.Employee_ID
our result complete. We have to perform a join. AND Orders.Product='Printer'
Tables in a database can be related to each other with keys. A primary Result
key is a column with a unique value for each row. The purpose is to
Name SELECT field1, field2, field3
FROM first_table
Hansen, Ola RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Example INNER JOIN The RIGHT JOIN returns all the rows from the second table (Orders),
even if there are no matches in the first table (Employees). If there
Syntax had been any rows in Orders that did not have matches in Employees,
those rows also would have been listed.
SELECT field1, field2, field3
FROM first_table Result
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Name Product
Who has ordered a product, and what did they order? Hansen, Ola Printer
Svendson, Stephen Table
SELECT Employees.Name, Orders.Product Svendson, Stephen Chair
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID Example
The INNER JOIN returns all rows from both tables where there is a Who ordered a printer?
match. If there are rows in Employees that do not have matches in
Orders, those rows will not be listed.
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
Result ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'
Name Product
Hansen, Ola Printer Result
Svendson, Stephen Table
Svendson, Stephen Chair Name
Hansen, Ola
Example LEFT JOIN
Syntax
SQL UNION and UNION ALL
SELECT field1, field2, field3
FROM first_table UNION
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
The UNION command is used to select related information from two
tables, much like the JOIN command. However, when using the
List all employees, and their orders - if any. UNION command all selected columns need to be of the same data
type.
SELECT Employees.Name, Orders.Product
FROM Employees Note: With UNION, only distinct values are selected.
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
SQL Statement 1
UNION
The LEFT JOIN returns all the rows from the first table (Employees), SQL Statement 2
even if there are no matches in the second table (Orders). If there are
rows in Employees that do not have matches in Orders, those rows
also will be listed.
Result Employees_Norway:
Types of Functions
Result
There are several basic types and categories of functions in SQL. The
Name basic types of functions are:
Hansen, Ola
Svendson, Tove Aggregate Functions
Svendson, Stephen Scalar functions
Pettersen, Kari
Turner, Sally
Kent, Clark
Aggregate functions
Scott, Stephen
Aggregate functions operate against a collection of values, but return
Note: This command cannot be used to list all employees in Norway a single value.
and USA. In the example above we have two employees with equal
names, and only one of them is listed. The UNION command only
selects distinct values. Note: If used among many other expressions in the item list of a
SELECT statement, the SELECT must have a GROUP BY clause!!
Example
Result:
This example returns the sum of ages for persons that are more than
2 20 years old:
Syntax
SELECT MAX(column) FROM table SQL GROUP BY and HAVING
Example Aggregate functions (like SUM) often need an added GROUP BY
functionality.
SELECT MAX(Age) FROM Persons
Result:
GROUP BY...
45
GROUP BY... was added to SQL because aggregate functions (like
SUM) return the aggregate of all column values every time they are
Note: The MIN and MAX functions can also be used on text called, and without the GROUP BY function it was impossible to find
columns, to find the highest or lowest value in alphabetical order. the sum for each individual group of column values.
Example
Company Amount
W3Schools 5500
SELECT MIN(Age) FROM Persons
IBM 4500
W3Schools 7100
Result:
And This SQL:
19
The above code is invalid because the column returned is not part of
an aggregate. A GROUP BY clause will solve this problem:
Company SUM(Amount)
W3Schools 12600
IBM 4500
HAVING...
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
This SQL:
Company SUM(Amount)
W3Schools 12600
SQL SELECT INTO Statement Insert a New Row
The following example makes a backup copy of the "Persons" table: LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
SELECT * INTO Persons_backup
Hetland Camilla Hagabakka 24 Sandnes
FROM Persons
If you only want to copy a few fields, you can do so by listing them LastName FirstName Address City
after the SELECT statement: Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
SELECT LastName,FirstName INTO Persons_backup
FROM Persons
And This SQL statement:
You can also add a WHERE clause. The following example creates a
"Persons_backup" table with two columns (FirstName and INSERT INTO Persons (LastName, Address)
LastName) by extracting the persons who lives in "Sandnes" from the VALUES ('Rasmussen', 'Storgt 67')
"Persons" table:
Will give this result:
SELECT LastName,Firstname INTO Persons_backup
FROM Persons
WHERE City='Sandnes' LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Selecting data from more than one table is also possible. The Hetland Camilla Hagabakka 24 Sandnes
following example creates a new table "Empl_Ord_backup" that Rasmussen Storgt 67
contains data from the two tables Employees and Orders:
SELECT Employees.Name,Orders.Product
INTO Empl_Ord_backup
FROM Employees
INNER JOIN Orders
SQL UPDATE Statement
ON Employees.Employee_ID=Orders.Employee_ID
The Update Statement
SQL INSERT INTO Statement The UPDATE statement is used to modify the data in a table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....) Person:
You can also specify the columns for which you want to insert data: LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....) Rasmussen Storgt 67
Update one Column in a Row Delete All Rows
We want to add a first name to the person with a last name of It is possible to delete all rows in a table without deleting the table.
"Rasmussen": This means that the table structure, attributes, and indexes will be
intact:
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen' DELETE FROM table_name
or
DELETE * FROM table_name
Result:
We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'
Result:
Syntax
DELETE FROM table_name
WHERE column_name = some_value
Person:
Delete a Row
Result
If you want to index more than one column you can list the column
The data type specifies what type of data the column can hold. The names within the parentheses, separated by commas:
table below contains the most common data types in SQL:
To delete a database:
Truncate a Table
What if we only want to get rid of the data inside a table, and not the
table itself? Use the TRUNCATE TABLE command (deletes only the
data inside the table):
Person:
Example
Note: The database design and structure will NOT be affected by the
functions, where, or join statements in a view.
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine
recreates the data, using the view's SELECT statement, every time a
user queries a view.
Using Views