STRUCTURED QUERY LANGUAGE
What is SQL?
SQL stands for Structured Query Language
SQL allows you to access a database
SQL is an ANSI standard computer language
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
SQL can update existing records in a database
SQL 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.
Below is an example of a table called "Persons":
LastName FirstName Address City
AAA BBB 123 Street New York
CCC DDD 456 Street Princeton
EEE FFF 789 Street Trenton
The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).
SQL Queries
With SQL, we can query a database and have a result set returned.
A query like this:
SELECT LastName FROM Persons
Gives a result set like this:
LastName
AAA
CCC
EEE
SQL Data Manipulation Language (DML)
SQL (Structured Query Language) is a syntax for executing queries. But the
SQL language also includes a syntax to update, insert, and delete records.
These query and update commands together form the Data Manipulation
Language (DML) part of SQL:
SELECT - extracts data from a database table
UPDATE - updates data in a database table
DELETE - deletes data from a database table
INSERT INTO - inserts new data into a database table
SQL Data Definition Language (DDL)
The Data Definition Language (DDL) part of SQL permits database tables to
be created or deleted. We can also define indexes (keys), specify links
between tables, and impose constraints between database tables.
The most important DDL statements in SQL are:
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
The SELECT Statement
The SELECT statement is used to select data from a table. The tabular result
is stored in a result table (called the result-set).
Syntax
SELECT column_name(s) FROM table_name
Select Some Columns
To select the columns named "LastName" and "FirstName", use a SELECT
statement like this:
SELECT LastName,FirstName FROM Persons
Select All Columns
To select all columns from the "Persons" table, use a * symbol instead of
column names, like this:
SELECT * FROM Persons
The Result Set
The result from a SQL query is stored in a result-set. Most database software
systems allow navigation of the result set with programming functions, like:
Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
The SELECT DISTINCT Statement
The DISTINCT keyword is used to return only distinct (different) values.
The SELECT statement returns information from table columns. But what if
we only want to select distinct elements?
With SQL, all we need to do is to add a DISTINCT keyword to the SELECT
statement:
Syntax
SELECT DISTINCT column_name(s) FROM table_name
The WHERE Clause
To conditionally select data from a table, a WHERE clause can be added to
the SELECT statement.
Syntax
SELECT column FROM table WHERE column operator value With
the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Using the WHERE Clause
To select only the persons living in the city "New York", we add a WHERE
clause to the SELECT statement:
SELECT * FROM Persons WHERE City='New York';
Using Quotes
SQL uses single quotes around text values (most database systems will also
accept double quotes). Numeric values should not be enclosed in quotes.
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in a column.
Syntax
SELECT column FROM table WHERE column LIKE pattern
A "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start
with an 'A':
SELECT * FROM Persons WHERE FirstName LIKE 'A%'
The following SQL statement will return persons with first names that end
with an 'A':
SELECT * FROM Persons WHERE FirstName LIKE '%A'
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into a table.
Syntax
INSERT INTO table_name VALUES (value1, value2,.. .)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,. . .)
The Update Statement
The UPDATE statement is used to modify the data in a table.
Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Update one Column in a Row
We want to add a first name to the person with a last name of "AAA":
UPDATE Person SET FirstName = 'XXX'
WHERE LastName = 'AAA'
The Delete Statement
The DELETE statement is used to delete rows in a table.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
Delete All Rows
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:
DELETE FROM table_name
or
DELETE * FROM table_name
The ORDER BY keyword is used to sort the result.
SELECT * from Persons Order By LastName
AND & OR
AND and OR join two or more conditions in a WHERE clause.
The AND operator displays a row if ALL conditions listed are true. The OR
operator displays a row if ANY of the conditions listed are true.
Syntax
Use AND to display each person with the first name equal to "AAA", and the
last name equal to "BBB":
SELECT * FROM Persons
WHERE FirstName='AAA'
AND LastName='BBB'
Syntax
Use OR to display each person with the first name equal to "AAA", or the last
name equal to "BBB":
SELECT * FROM Persons
WHERE firstname='AAA'
OR lastname='BBB'
IN
The IN operator may be used if you know the exact value you want to return
for at least one of the columns.
SELECT column_name FROM table_name
WHERE column_name IN (value1,value2,..)
BETWEEN ... AND
The BETWEEN ... AND operator selects a range of data between two values.
These values can be numbers, text, or dates.
SELECT column_name FROM table_name
WHERE column_name
BETWEEN value1 AND value2
ALIASES
With SQL, aliases can be used for column names and table names.
Column Name Alias
The syntax is:
SELECT column AS column_alias FROM table
Table Name Alias
The syntax is:
SELECT column FROM table AS table_alias
Joins
Sometimes we have to select data from two or more tables to make our
result complete. We have to perform a join.
Tables in a database can be related to each other with keys. A primary key is
a column with a unique value for each row. The purpose is to bind data
together, across tables, without repeating all of the data in every table.
In the "Employees" table below, the "Employee_ID" column is the primary
key, meaning that no two rows can have the same Employee_ID. The
Employee_ID distinguishes two persons even if they have the same name.
When you look at the example tables below, notice that:
The "Employee_ID" column is the primary key of the "Employees"
table
The "Prod_ID" column is the primary key of the "Orders" table
The "Employee_ID" column in the "Orders" table is used to refer to the
persons in the "Employees" table without using their names
Employees:
Employee_ID Name
01 AAA, BBB
02 CCC, DDD
03 EEE, FFF
04 GGG, HHH
Orders:
Prod_ID Product Employee_ID
111 Printer 01
112 Monitor 03
113 Mouse 03
114 Keyboard 04
Referring to Two Tables
We can select data from two tables by referring to two tables, like this:
Example
Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
Example
Who ordered a keyboard?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Keyboard'
BUILT-IN FUNCTIONS IN SQL
SQL has a lot of built-in functions for counting and calculations.
Function Syntax
The syntax for built-in SQL functions is:
SELECT function(column) FROM table
Types of Functions
There are several basic types and categories of functions in SQL. The basic
types of functions are:
Aggregate Functions
Scalar functions
Aggregate functions
Aggregate functions operate against a collection of values, but return a single
value. When used among many other expressions in the item list of a SELECT
statement, the SELECT must have a GROUP BY clause.
Some of the most commonly used Aggregate functions are
Function Description
AVG(column) Returns the average value of a column
COUNT(column) Returns the number of rows (without a NULL
value) of a column
COUNT(*) Returns the number of selected rows
FIRST(column) Returns the value of the first record in a specified
field
LAST(column) Returns the value of the last record in a specified
field
MAX(column) Returns the highest value of a column
MIN(column) Returns the lowest value of a column
SUM(column) Returns the total sum of a column
Scalar functions
Scalar functions operate against a single value, and return a single value
based on the input value. Scalar functions differ from database to database.
Some of the most commonly used Scalar functions in MS Access are
Function Description
UCASE(c) Converts a field to upper case
LCASE(c) Converts a field to lower case
MID(c,start[,end]) Extract characters from a text field
LEN(c) Returns the length of a text field
INSTR(c) Returns the numeric position of a named
character within a text field
LEFT(c,number_of_char) Return the left part of a text field requested
RIGHT(c,number_of_char) Return the right part of a text field requested
ROUND(c,decimals) Rounds a numeric field to the number of decimals
specified
MOD(x,y) Returns the remainder of a division operation
NOW() Returns the current system date
FORMAT(c,format) Changes the way a field is displayed
DATEDIFF(d,date1,date2) Used to perform date calculations
GROUP BY...
GROUP BY... was added to SQL because aggregate functions (like SUM)
return the aggregate of all column values every time they are called, and
without the GROUP BY function it was impossible to find the sum for each
individual group of column values.
The syntax for the GROUP BY function is:
SELECT column,SUM(column) FROM table GROUP BY column
HAVING...
HAVING... was added to SQL because the WHERE keyword could not be used
against aggregate functions (like SUM), and without HAVING... it would be
impossible to test for result conditions.
The syntax for the HAVING function is:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value