SQL
(
STRUCTURED QUERY
LANGUAGE
)
is a database computer language
designed for the retrieval and
management of data in :
relational database management systems
(RDBMS),
database schema creation and
modifcation, and
SQL is a standard interactive and programming
language for querying and modifying data and managing databases.
Although SQL is both an ANSI and an ISO standard,
many database products support SQL with
proprietary extensions to the standard language.
The core of SQL is formed by a command language
that allows the retrieval, insertion, updating, and deletion of data, and performing management and administrative functions.
SQL also includes a Call Level Interface (SQL/CLI)
The frst version of SQL was developed at IBM by
Donald D. Chamberlin and Raymond F. Boyce in the early 1970s.
This version, initially called SEQUEL, was designed
to manipulate and retrieve data stored in IBM's original relational database product, System R.
IBM patented their version of SQL in 1985, while
the SQL language was not formally standardized until 1986, by the American National Standards Institute (ANSI).
Subsequent versions of the SQL standard have
Originally designed as a declarative query and
data manipulation language, variations of SQL
have been created by SQL database
management system (DBMS) vendors that add:
procedural constructs,
control-of-fow statements, user-defned data types, and
various other language extensions.
With the release of the SQL:1999 standard, many
MYSQL
Is freely available as an open source
software.
Was created in 1990s by Michael
Widenius of TeX DataKonsult AB in
Sweden.
Is currently the world’s most popular
open source database.
Particularly suited for client server
MYSQL
Organizations that used MySQL for their
database needs range from small
not-for-proft organizations to global manufacturing
companies, government agencies,
multinational news organizations, and
major Internet service providers.
MySQL also available for many diferent
LANGUAGE ELEMENTS
The SQL language is sub-divided into several
language elements, including:
Statements which may have a persistent efect on schemas and data, or which may control
transactions, program fow, connections, sessions, or diagnostics.
Queries which retrieve data based on specifc criteria.
Expressions which can produce either scalar
LANGUAGE ELEMENTS
Predicates which specify conditions that can be
evaluated to SQL three-valued logic (3VL) Boolean truth values and which are used to limit the efects of
statements and queries, or to change program fow.
Clauses, which are in some cases optional, constituent
components of statements and queries.
Whitespace is generally ignored in SQL statements and
queries, making it easier to format SQL code for readability.
SQL statements also include the semicolon (";")
QUERIES
The most common operation in SQL databases is
the query, which is performed with the declarative SELECT keyword.
SELECT retrieves data from a specifed table, or
multiple related tables, in a database.
While often grouped with Data Manipulation
Language (DML) statements, the standard SELECT query is considered separate from SQL DML, as it has no persistent efects on the data stored in a database.
Note that there are some platform-specifc
QUERIES
SQL queries allow the user to specify a description of
the desired result set, but it is left to the devices of the database management system (DBMS) to plan,
optimize, and perform the physical operations
necessary to produce that result set in as efcient a manner as possible.
An SQL query includes a list of columns to be included
in the fnal result immediately following the SELECT keyword.
An asterisk ("*") can also be used as a "wildcard"
SELECT IS THE MOST COMPLEX STATEMENT IN
SQL, WITH SEVERAL OPTIONAL KEYWORDS
AND CLAUSES, INCLUDING:
FROM clause
which indicates the source table or tables from which
the data is to be retrieved.
can include optional JOIN clauses to join related tables
to one another based on user-specifed criteria.
WHERE clause
includes a comparison predicate, which is used to
restrict the number of rows returned by the query.
is applied before the GROUP BY clause.
eliminates all rows from the result set where the
SELECT IS THE MOST COMPLEX STATEMENT IN
SQL, WITH SEVERAL OPTIONAL KEYWORDS
AND CLAUSES, INCLUDING:
GROUP BY clause
is used to combine, or group, rows with related values
into elements of a smaller set of rows.
is often used in conjunction with SQL aggregate functions
or to eliminate duplicate rows from a result set.
HAVING clause
includes a comparison predicate used to eliminate rows
after the GROUP BY clause is applied to the result set.
Because it acts on the results of the GROUP BY clause,
SELECT IS THE MOST COMPLEX STATEMENT IN
SQL, WITH SEVERAL OPTIONAL KEYWORDS
AND CLAUSES, INCLUDING:
ORDER BY clause
is used to identify which columns are used to sort
the resulting data, and in which order they should be sorted (options are ascending or descending).
The order of rows returned by an SQL query is
DATA TYPES
DATA
TYPE DESCRIPTION
Char (n) Stores a character string n characters long. You use the char data type for columns that contain letters and special characters and for columns containing numbers that will not be used in any calculations. For example, the REP_NUM and CUSTOMER_NUM columns are both assigned the char data type.
Varchar (n) An alternative to char that stores a character string up to n characters long. Unlike char, all that is stored is the actual character string. If a character string 20 characters long is stored in a char (30) column, it will occupy 30 characters (20 characters + 10 blank spaces). If it is
DATA TYPES
DATA
TYPE DESCRIPTION
Date Stores date data. In MySQL, dates are enclosed in single quotation marks and have the form yyyy-mm-dd (for example, ‘2007-10-15’ is October 15, 2007).
Decimal (p,
q) Stores a decimal number p digits long with q of these digits being decimal places to the right of the decimal point. For example the data type decimal (5, 2) represents a number with three places to the left and two places to the right of the decimal (for example, 100.00). You can use the contents of the decimal columns in
DATA TYPES
DATA
TYPE DESCRIPTION
Int Stores integers, which are numbers without a decimal part. The valid range is -2147483648 to 2147483647. You can use the content of int columns in calculation. If you follow the word int into auto_increment, you create a column for which MySQL will automatically generate a new sequence number each time you add a new row.
Smallint Stores integers, but uses less space than the int data type. The valid range is -32768 to 32767. Smallint is a better choice than int
when you are certain that the column will store numbers within the indicated range. You can use the contents of smallint columns in
SHOW DATABASE
mysql> SHOW
DATABASES;
Use the SHOW
statement to fnd out
what databases
currently exist on the
server
CREATE DATABASE
mysql> CREATE
DATABASE newdb;
Create statement
Database name
The new
USE DATABASE
mysql> USE newdb
Creating a database
does not select it for
use; you must do that
explicitly.
Note that USE, like
QUIT, does not require
a semicolon.
The USE statement is
special in another
way, too: it must be
given on a single line.
SQL command
SHOW TABLES
mysql> SHOW
TABLES;
To create one or
more tables in the
current database,
you can use CREATE
TABLE statement.
It indicates that there is no table in the database.
CREATE TABLE
mysql> CREATE
TABLE
Use a CREATE TABLE
statement to specify
the layout of your
table.
In this case, table
pelajar
will have 4
attributes.
If you want to fnd out about the
structure of a table, the DESCRIBE
command is useful; it displays
information about each of a table's
columns
DESCRIBE
ALTER TABLE is use to modify an existing column It is consists of ADD, MODIFY and DROP column ALTER TABLE statement:
ADD column
MODIFY column
DROP column
ALTER TABLE table
ADD (column datatype [DEFAULT expr][column datatype]….);
ALTER TABLE table
MODIFY (column datatype [DEFAULT expr][column datatype]….);
ALTER TABLE table
Example
Table before add new column
Execute ALTER TABLE statement to ADD:
Table after execute the ALTER TABLE statement to ADD
ename hiredate
JAMES 03-FEB-97
SMITH 20-MAC-90
ADAMS 11-JUL-99
ALTER TABLE emp
ADD (job VARCHAR(9));
ename hiredate job
JAMES 03-FEB-97 PROGRAMMER
Example
Table before MODIFY a column
Execute ALTER TABLE statement to MODIFY:
Table after execute the ALTER TABLE statement to
MODIFY
ename job hiredate
JAMES PROGRAMMER 03-FEB-97
SMITH MANAGER 20-MAC-90
ADAMS CLERK 11-JUL-99
ename job hiredate
JAM PROGRAMMER 03-FEB-97
SMI MANAGER 20-MAC-90 ADA CLERK 11-JUL-99
LIN ACCOUNTANT 05-SEP-09 ALTER TABLE emp
MODIFY (ename VARCHAR(3));
Example
Table before DROP column
Execute ALTER TABLE statement to DROP:
Table after execute the ALTER TABLE statement to DROP:
ename job hiredate
JAMES PROGRAMMER 03-FEB-97
SMITH MANAGER 20-MAC-90
ADAMS CLERK 11-JUL-99
ename hiredate
JAMES 03-FEB-97
SMITH 20-MAC-90 ADAMS 11-JUL-99
LINA 05-SEP-09 ALTER TABLE emp
DROP COLUMN job;
Basic Structures in Query
Design
SELECT to query data in the database
INSERT to insert data into a table
UPDATE to update data in a table
DELETE to delete data from a table
Purpose to retrieve and display data from one or more database
tables.
It is an extremely powerful command capable of performing the
equivalentof the relational algebra’s Selection, Projection and Join operations in a single statement.
It is most frequently used SQL command. Basic select statement:
SELECT identifes what columns FROM identifes which table
SELECT [DISTINCT] {*, column,…} FROM table;
Select all columns
Select specifc columns
Deptno Dname Loc
10 Accounting New York
20 Research Dallas 30 Sales Chicago SELECT * FROM dept;
Outpu t
Deptno Loc
10 New York
20 Dallas 30 Chicago SELECT Deptno, loc FROM dept;Output
SELECT [DISTINCT] {*, column,…} FROM table
WHERE condition(s); • Using WHERE clause.
• It is used to restrict or limiting the rows selected
Using where clause
Select specifc columns
ename job deptno
JAMES CLERK 30
SMITH CLERK 20 ADAMS CLERK 10 SELECT ename, job, deptno
FROM dept
WHERE job = ‘CLERK’
Outpu t
Deptno Loc
10 New York SELECT Deptno, loc
FROM dept
WHERE loc = ‘New York’;
Outpu t
Using BETWEEN operator to display rows based on a range
of values
ename sal
JAMES 14252
SMITH 10000 ADAMS 12000 SELECT ename, sal
FROM emp
WHERE sal BETWEEN 10000 AND 15000;
Outpu t
UPDATE
UPDATE item
SET Quantity =10,UnitPrice =1800.00
WHERE ItemNo = ‘123’;
In this statement , only one row will be
updated since the condition is specifed
in the WHERE clause, if the WHERE
DELETE
To remove one or more rows from a
table. For example , to delete the
ItemNo = ‘123’.
DELETE
FROM item
The syntax for inserting data into a
table one row at a time is as follows:
INSERT INTO "table_name"
("column1", "column2", ...)
VALUES ("value1", "value2", ...)
ASSUMING THAT WE HAVE A TABLE THAT HAS THE
FOLLOWING STRUCTURE :
TABLE STORE_INFORMATION RESULT :
Column Name Data Type
store_name char(50)
Sales float
Date datetime
INSERT INTO
Store_Information (store_name, Sales, Date)
VALUES (‘Ipoh', 900, 'Jan-10-1999')
store_name Sales Date
The second type of
INSERT INTO
allows
us to insert multiple rows into a table.
Unlike the previous example, we now use
a
SELECT
statement to specify the data
that we want to insert into the table.
The syntax is as follows:
INSERT INTO "table1" ("column1", "column2", ...) SELECT "column3", "column4", ...
BEFORE USING INSERT INTO COMMAND
TABLE SALES_INFORMATION TABLE STORE_INFORMATION
store_na
me Branch Sales Date
Alor Setar Kedah 350 Mac- 4-1997 Butterwor
th Penang 500 Sep- 17-1997 Sepang Selang
or 675 Feb- 20-1998 Nilai Ng Sembil an 890 Mei- 15-1998 store_na
me Sales Date
Ipoh 900 Jan-10-1999
Table
Sales_Information
Table
INSERT INTO Store_Information (store_name, Sales, Date) SELECT store_name, Sales, Date
FROM Sales_Information WHERE Year(Date) = 1998
AFTER USING INSERT INTO
COMMAND
store_n
ame Branch Sales Date
Alor
Setar Kedah 350 Mac- 4-1997 Butterwo
rth Penang 500 Sep- 17-1997 Sepang Selango
r 675 Feb- 20-1998 Nilai Ng Sembila n 890 Mei- 15-1998 store_na
me Sales Date
Ipoh 900 Jan-10-1999 Sepang 675
Feb-20-1998 Nilai 890
Mei-15-1998
New information that been added to the table
Table
Sales_Information
Table
CREATE VIEW
Views can be considered as virtual tables.
Generally speaking, a table has a set of
defnition, and it physically stores the data.
A view also has a set of defnitions, which
is build on top of table(s) or other view(s),
and it does not physically store the data.
The syntax for creating a view is as follows:
WE HAVE THE FOLLOWING TABLE
TABLE CUSTOMER
WE WANT TO CREATE A VIEW CALLED V_CUSTOMER THAT CONTAINS ONLY THE
FIRST_NAME, LAST_NAME, AND COUNTRY COLUMNS FROM THIS TABLE , WE WOULD TYPE IN,
CREATE VIEW V_Customer AS SELECT First_Name, Last_Name, Country FROM Customer
Column Name Data Type
NOW WE HAVE A VIEW CALLED V_CUSTOMER WITH THE FOLLOWING STRUCTURE:
View
V_Customer
(First_Name
char(50),
Last_Name
char(50),
Country char(25))
Column Name Data Type
WE CAN ALSO USE A VIEW TO APPLY JOINS TO TWO TABLES. IN THIS CASE, USERS ONLY SEE ONE VIEW RATHER THAN TWO TABLES, AND THE SQL
STATEMENT USERS NEED TO ISSUE BECOMES MUCH SIMPLER. LET'S SAY WE HAVE THE FOLLOWING TWO TABLES
TABLE STORE_INFORMATION TABLE GEOGRAPHY
store_name Sales Date
Los Angeles $1500 Jan-05-1999 San Diego $250 Jan-07-1999 Los Angeles $300 Jan-08-1999 Boston $700 Jan-08-1999
WE WANT TO BUILD A VIEW THAT HAS SALES BY REGION INFORMATION
CREATE VIEW V_REGION_SALES
AS SELECT A1.region_name REGION,
SUM(A2.Sales) SALES
FROM Geography A1, Store_Information A2
WHERE A1.store_name = A2.store_name
GROUP BY A1.region_name
This gives us a view,
V_REGION_SALES
,
SELECT * FROM V_REGION_SALES
EXERCISES:
ACCORDING TO THE TABLE GIVEN, WRITE SQL QUERY FOR EACH OF THE FOLLOWING
QUESTIONS.
Column
Name Data Type
Reg_Num Char(12) Name Char(50) Year_Born Int(4)
1. Add a column called
“TelNum” to this table.
2. Change the column
name for “Reg_Num” to “RegistrationNum”.
3. Modify the data type
of “Year_Born” to date.
4. Delete the column
•
NOT NULL
•
UNIQUE
•
PRIMARY KEY
•
FOREIGN KEY
TABLE CONSTRAINT
You can place constraints to limit the
type of data that can go into a table.
Such constraints can be specifed when
the table when the table is frst created
via the CREATE TABLE statement, or
1)
NOT NULL
By default, a column can hold NULL.
If you not want to allow NULL value in a
column, you will want to place a
constraint on this column specifying
that NULL is now not an allowable
Columns "SID" and "Last_Name" cannot include NULL, while
"First_Name" can include NULL.
2) UNIQUE
The UNIQUE constraint ensures that all
values in a column are distinct.
RESULT :
3) PRIMARY KEY
A primary key is used to uniquely identify each row in a table.
It can either be part of the actual record itself , or it can be an artifcial feld.
A primary key can consist of one or more felds on a table.
When multiple felds are used as a primary key, they are called a composite key.
EXAMPLE :
CREATE TABLE Customer
(SID integer,
Last_Name varchar(30),
First_Name varchar(30),
PRIMARY KEY (SID));
ALTER TABLE Customer ADD PRIMARY KEY
(SID);
RESULT :
4)
FOREIGN KEY
A foreign key is a feld (or felds) that
points to the primary key of another
table.
The purpose of the foreign key is to
ensure referential integrity of the data.
In other words, only values that are
TABLE CUSTOMER TABLE ORDER
Column name Characteristic
SID Primary key First_Name
Last_Name
Column name Characteristic
Order_ID Primary key Order_Date
Customer_SID Foreign key Amount
CREATE TABLE ORDERS
(Order_ID integer, Order_Date date,
Customer_SID integer, Amount double,
Primary Key (Order_ID),
Foreign Key (Customer_SID) references CUSTOMER(SID));
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
MANIPULATION DATA IN SQL
COMMANDS
•SORT BY ROW
•AND
•OR
SORT BY ROW
The ORDER BY clause is used to sort
the rows.
Example :
Company OrderNumber
Sega 3412
ABC Shop 5678
W3Schools 6798
EXAMPLE 1
To display the
company names in
alphabetical order:
SELECT Company,
OrderNumber FROM
OrdersORDER BY
Company
Compan
y OrderNum
ABC Shop 5678
Sega 3412
W3Schools 6798 W3Schools 2312
EXAMPLE 2
To display the
company names in alphabetical order
AND the OrderNumber in numerical order:
SELECT Company, OrderNumber FROM OrdersORDER BY Company, OrderNumber Compan
y OrderNum
ABC Shop 5678
Sega 3412
W3Schools 2312 W3Schools 6798
EXAMPLE 3
To display the
company names in
reverse alphabetical
order:
SELECT Company,
OrderNumber FROM
OrdersORDER BY
Company DESC
Compan
y OrderNum
W3Schools 6798 W3Schools 2312
Sega 3412
ABC Shop 5678
EXAMPLE 4
To display the company names in reverse
alphabetical order AND the OrderNumber in
numerical order: SELECT Company, OrderNumber FROM OrdersORDER BY Company DESC, OrderNumber ASC Compan
y OrderNum
W3Schools 2312 W3Schools 6798
Sega 3412
ABC Shop 5678
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.
L_Name F_Name Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes
EXAMPLE 1
Use AND to display
each person with
the frst name equal
to "Tove", and the
last name equal to
"Svendson“:
SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'
L_Name F_Name Address City
EXAMPLE 2
Use OR to display
each person with
the frst name equal
to "Tove", or the last
name equal to
"Svendson":
SELECT * FROM Persons WHERE frstname='Tove' OR lastname='Svendson'
L_Name F_Name Address City
Svendson Tove Borgvn 23 Sandnes
EXAMPLE 3
You can also
combine AND and
OR (use
parentheses to form
complex
expressions):
SELECT * FROM Persons WHERE
(FirstName='Tove' OR FirstName='Stephen') AND
LastName='Svendson'
L_Name F_Name Address City
Svendson Tove Borgvn 23 Sandnes
IN
The IN operator may be used if you
know the exact value you want to
EXAMPLE 1
To display the
persons with
LastName equal to
"Hansen" or
"Pettersen", use the
following SQL:
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen ')
L_Name F_Name Address City
Hansen Ola Timoteivn 10 Sandnes
BETWEEN ... AND
The BETWEEN ... AND operator selects
a range of data between two values.
These values can be numbers, text, or
EXAMPLE 1
To display the
persons
alphabetically
between (and
including) "Hansen"
and exclusive
"Pettersen“ :
SELECT * FROM Persons
WHERE LastName BETWEEN 'Hansen'
AND 'Pettersen'
L_Name F_Name Address City
Hansen Ola Timoteivn 10 Sandnes
EXAMPLE 2
To display the
persons outside the
range used in the
previous example,
use the NOT
operator:
SELECT * FROM Persons
WHERE LastName NOT BETWEEN
'Hansen' AND 'Pettersen'
L_Name F_Name Address City
Pettersen Kari Storgt 20 Stavanger
Use the LIKE operator to perform wildcard searches of valid search string
values.
Search conditions can contain either literal characters or numbers
- % denotes zero or many characters - _ denotes one characters
ename
LINA
SELECT ename FROM emp
WHERE ename LIKE ‘L%’;
Output
emp_code ename job
001 JAMES PROGRAMMER
003 ADAMS CLERK
002 SMITH MANAGER
004 LINA CLERK
Original table
ename JAMES
ADAMS
SMITH
SELECT ename FROM emp
WHERE ename LIKE ‘_M%’;
Output
emp_code ename job
001 JAMES PROGRAMMER
003 ADAMS CLERK
002 SMITH MANAGER
004 LINA CLERK
Original table
You can use the ESCAPE identifer to search for “%” or “_”
ename
SMITH_WINE
SELECT ename FROM emp
WHERE ename LIKE ‘%\_%’ ESCAPE ‘\’;
Output
emp_code ename job
001 JAMES PROGRAMMER
003 ADAMS CLERK
002 SMITH_WINE MANAGER
004 LINA CLERK
Original table
Use the IN operator to test for
values in a list
SELECT ename, job FROM emp
WHERE emp_code IN (002,004);
Output
emp_code ename job
001 JAMES PROGRAMMER
003 ADAMS CLERK
002 SMITH_WINE MANAGER
004 LINA CLERK
Original table
ename job
AVG
COUNT
MAX
MIN
SUM
VARIANCE
Types of Group Functions
COUNT
function is the simplest
function and very useful in counting the
number of records which are expected
to be returned by a SELECT statement.
Using AVG, MAX, MIN and SUM functions
AVG(sal) MAX(sal) MIN(sal) SUM(sal)
4150 8000 950 12450
SELECT AVG(sal), MAX(sal), MIN(sal), SUM(sal)
FROM emp;
sal 950 8000 3500
MAX function is used to fnd out the record with maximum value among a record set.
To understand MAX function consider an
employee_tbl table which is having following records:
NOW SUPPOSE BASED ON THE ABOVE TABLE YOU WANT TO FETCH MAXIMUM VALUE OF
You can use
MIN
Function alongwith
MAX
function to fnd out minimum
value as well.
AVG function is used to fnd out the average of a feld in various records.
To understand AVG function consider an
employee_tbl table which is having following records: