SQL (Structured Query Language)
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.
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).
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 such extensions were formally adopted as part of
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.
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 operating environments, including
BASIC SQL COMMANDS
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 (";") statement terminator. Though not required on every
LANGUAGE ELEMENTS
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. 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
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.
SELECT IS THE MOST COMPLEX STATEMENT IN
SQL, WITH SEVERAL OPTIONAL KEYWORDS
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, aggregate functions can be used in the HAVING clause
SELECT IS THE MOST COMPLEX STATEMENT IN
SQL, WITH SEVERAL OPTIONAL KEYWORDS
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 never guaranteed unless an ORDER BY clause is specifed. DATA TYPES DATA DESCRIPTION TYPE
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 DATA TYPES DATA DESCRIPTION TYPE
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, Stores a decimal number p digits long with q of q) 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 DATA TYPES DATA DESCRIPTION TYPE
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
CREATING DATABASE USING SQL
COMMANDSSHOW DATABASE
mysql> SHOW Use the SHOW DATABASES; statement to fnd out what databases
SQL command currently exist on the server
CREATE DATABASE
mysql> CREATE DATABASE newdb;
Database name Create statement The new database will
USE DATABASE
Creating a database
mysql> USE newdb
does not select it for use; you must do that
SQL command explicitly.
Note that USE, like QUIT, does not require a semicolon.
The USE statement is
Database name SHOW TABLES
mysql> SHOW To create one or TABLES; more tables in the
SQL command current database, you can use CREATE TABLE statement.
It indicates that there is no CREATE TABLE
mysql> CREATE Use a CREATE TABLE TABLE statement to specify the layout of your table.
In this case, table
pelajar will have 4 attributes.
Addres DESCRIBE
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
SQL command Database name
columns
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 STATEMENT Example
Table before add new column
Execute ALTER TABLE statement to ADD:
Table after execute ename hiredate JAMES 03-FEB-97 SMITH 20-MAC-90 ADAMS 11-JUL-99
ALTER TABLE emp
ADD (job VARCHAR(9));
ename hiredate jobALTER TABLE STATEMENT
Example
Table before MODIFY a column
Execute ALTER TABLE statement to MODIFY:
Table after execute
the ALTER TABLE
statement to ename job hiredate JAMES PROGRAMMER 03-FEB-97 SMITH MANAGER 20-MAC-90 ADAMS CLERK 11-JUL-99 ename job hiredate
ALTER TABLE emp MODIFY (ename VARCHAR(3)); ALTER TABLE STATEMENT
Example
Table before DROP column
Execute 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
ALTER TABLE emp DROP COLUMN job; ALTER TABLE STATEMENT
QUERY WITH SQL
Basic Structures in Query
DesignDEFINE THE INSTRUCTION
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
SELECT STATEMENT
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 [DISTINCT] {*, column,…} FROM table;
SELECT identifes what columns
SELECT STATEMENT
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 Loc10 New York
20 Dallas
30 Chicago SELECT Deptno, loc FROM dept;
Outpu
t
SELECT STATEMENT
- Using WHERE clause.
- It is used to restrict or limiting the rows selected
SELECT [DISTINCT] {*, column,…} FROM table WHERE condition(s);
The WHERE clause follows the FROM clause
SELECT STATEMENT
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 Loc10 New York SELECT Deptno, loc FROM dept WHERE loc = ‘New York’;
Outpu
t
SELECT STATEMENT
Using BETWEEN operator to display rows based on a range
of values ename sal JAMES 14252 SMITH 10000 ADAMS 12000SELECT 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 WHERE ItemNo = ‘123’;
INSERT INTO
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 :INSERT INTO
Column Name Data Type Store_Information store_name char(50)
(store_name, Sales, Sales float
Date) Date datetime
VALUES (‘Ipoh', 900, 'Jan-10-1999')
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", ...) TABLE SALES_INFORMATION TABLE STORE_INFORMATION store_na me Branc h Sal es Date
Alor Setar Kedah 350 Mac- 4- 1997
Butterwor th Penan g
500 Sep- 17- 1997
Sepang Selang or 675 Feb-
20-
store_na me Sal es Date
Ipoh 900 Jan-10- 1999
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 Sal es Date
Alor Setar
Kedah 350 Mac- 4- 1997
Butterwo rth Penang 500 Sep-
17- 1997
store_na me Sal es Date
Ipoh 900 Jan-10- 1999
Sepang 675 Feb-20- 1998
Nilai 890 Mei-15- 1998
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:
CUSTOMER TABLE Column Name Data Type
WE WANT TO CREATE A VIEW CALLED THAT
V_CUSTOMER
First_Name char(50)
CONTAINS ONLY THE FIRST_NAME, LAST_NAME, AND
Last_Name char(50)
COUNTRY COLUMNS FROM THIS TABLE , WE WOULD TYPE IN,
Address char(50) City char(50)
CREATE VIEW
Country char(25) V_Customer
AS SELECT
Birth_Date date NOW WE HAVE A VIEW CALLED V_CUSTOMER WITH
THE FOLLOWING STRUCTURE:
View V_Customer
Column Name Data Type
(First_Name First_Name char(50) char(50),
Last_Name char(50) Last_Name
Country char(25) char(50), Country char(25))
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 TABLESTABLE STORE_INFORMATION TABLE GEOGRAPHY store_name Sales Date region_name store_name
Los Angeles $1500 Jan-05-1999 East Boston East New York
San Diego $250 Jan-07-1999 West Los Angeles
Los Angeles $300 Jan-08-1999 West San Diego 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, that has been defned to store sales by
SELECT * FROM V_REGION_SALES
REGION SALES
East $700 West $2050 EXERCISES: ACCORDING TO THE TABLE GIVEN, WRITE SQL
QUERY FOR EACH OF THE FOLLOWING QUESTIONS.
1. Add a column called Column Data
“TelNum” to this Name Type table.
Reg_Num Char(12) 2.
Change the column Name Char(50) name for “Reg_Num” to “RegistrationNum”.
Year_Born Int(4) 3.
Modify the data type of “Year_Born” to
TABLE CONSTRAINTS IN SQL
- NOT NULL
- UNIQUE
- PRIMARY 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 after the table is already created via the ALTER TABLE statement.
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 value.
Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL.
Result :
2) UNIQUE
The UNIQUE constraint ensures that all values in a column are distinct.
“SID” column in customer table is modify so that "SID" column cannot include duplicate values, while such constraint does not hold for columns "Last_Name" and RESULT :
Indicates that “SID” column is unique
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.
Primary keys can be specifed either when the table EXAMPLE :
CREATE TABLE Customer (SID integer, Last_Name varchar(30), First_Name varchar(30),
PRIMARY KEY (SID));
Indicate that “SID” column has been choose to be the primary key. RESULT :
Primary key
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 supposed to appear in the database 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));
Indicates the Customer_SID column in the ORDERS table is a foreign key pointing to the SID column in the CUSTOMER table
ALTER TABLE ORDERS
MANIPULATION DATA IN SQL
COMMANDS- SORT BY ROW
- AND
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
Result :
company names in alphabetical order:
Compan OrderNu y m
SELECT Company,
ABC Shop 5678 Sega 3412
OrderNumber FROM
W3Schools 6798
OrdersORDER BY
W3Schools 2312
Company EXAMPLE 2
To display the Result : company names in alphabetical order AND the OrderNumber Compan OrderNu y m in numerical order:
ABC Shop 5678 Sega 3412 SELECT Company,
W3Schools 2312 OrderNumber FROM
W3Schools 6798 OrdersORDER BY EXAMPLE 3
To display the
Result :
company names in reverse alphabetical
Compan OrderNu
order:
y m W3Schools 6798 W3Schools 2312
SELECT Company,
Sega 3412
OrderNumber FROM
ABC Shop 5678
OrdersORDER BY EXAMPLE 4
To display the company
Result :
names in reverse alphabetical order AND the OrderNumber in
Compan OrderNu
numerical order:
y m W3Schools 2312 W3Schools 6798
SELECT Company,
Sega 3412
OrderNumber FROM
ABC Shop 5678
OrdersORDER BY
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.
Original table
L_Name F_Name Address City
Hansen Ola Timoteivn 10 Sandnes EXAMPLE 1 SELECT * FROM Persons
Use AND to display
WHERE FirstName='Tove'
each person with
AND LastName='Svendson'
the frst name equal to "Tove", and the last name equal to "Svendson“:
L_Name F_Name Address City EXAMPLE 2
SELECT * FROM Persons
Use OR to display
WHERE frstname='Tove'
each person with
OR lastname='Svendson'
the frst name equal to "Tove", or the last name equal to "Svendson":
L_Name F_Name Address City EXAMPLE 3
SELECT * FROM Persons
You can also
WHERE
combine AND and
(FirstName='Tove' OR
OR (use
FirstName='Stephen')
parentheses to form
AND
complex
LastName='Svendson'
expressions):
L_Name F_Name Address City IN
The IN operator may be used if you know the exact value you want to return for at least one of the columns. EXAMPLE 1
SELECT * FROM To display the
Persons persons with
WHERE LastName IN LastName equal to
('Hansen','Pettersen "Hansen" or
') "Pettersen", use the following SQL:
L_Name F_Name Address City BETWEEN ... AND
The BETWEEN ... AND operator selects
a range of data between two values.
These values can be numbers, text, or dates.
EXAMPLE 1
SELECT * FROM To display the
Persons persons
WHERE LastName alphabetically
BETWEEN 'Hansen' between (and
AND 'Pettersen' including) "Hansen" and exclusive "Pettersen“ :
L_Name F_Name Address City EXAMPLE 2
SELECT * FROM
To display the
Persons
persons outside the
WHERE LastName
range used in the
NOT BETWEEN
previous example,
'Hansen' AND
use the NOT
'Pettersen'
operator:
L_Name F_Name Address City
LIKE OPERATOR
emp_code ename job
001 JAMES PROGRAMMER 003 ADAMS CLERK 002 SMITH MANAGER 004 LINA CLERK 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
Original table
LIKE OPERATOR
ename JAMES ADAMS
SELECT ename FROM emp Output emp_code ename job 001 JAMES PROGRAMMER 003 ADAMS CLERK 002 SMITH MANAGER 004 LINA CLERK
Original table
LIKE OPERATOR
You can use the ESCAPE identifer to search for “%” or “_” ename SMITH_WINE
SELECT ename FROM emp 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 Output
emp_code ename job
001 JAMES PROGRAMMER 003 ADAMS CLERK 002 SMITH_WINE MANAGER 004 LINA CLERKOriginal table ename job SMITH_WINE MANAGER
LINA CLERK
MATHEMATICAL FUNCTIONS IN SQL
COMMANDSGROUP BY FUNCTION
Types of Group Functions AVG COUNT MAX MIN COUNT
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 sal 950
SELECT AVG (sal), MAX (sal), MIN (sal), SUM (sal) 8000
FROM emp; 3500
AVG(sal) MAX(sal) MIN(sal) SUM(sal) Output
4150 8000 950 12450 CONSIDER AN EMPLOYEE_TBL TABLE WHICH IS HAVING
FOLLOWING RECORDS:
NOW SUPPOSE BASED ON THE ABOVE TABLE YOU WANT TO COUNT TOTAL NUMBER OF ROWS IN THIS TABLE THEN YOU CAN DO IT AS FOLLOWS:
SIMILARLY YOU WANT TO COUNT THE NUMBER OF RECORDS FOR ZARA THEN IT CAN BE DONE
AS FOLLOWS:
MAX
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
DAILY_TYPING_PAGES, THEN YOU CAN DO SO SIMPLY
MIN & MAX
You can use MIN Function alongwith
MAX function to fnd out minimum value as well. AVG
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: NOW SUPPOSE BASED ON THE ABOVE TABLE YOU