Sie sind auf Seite 1von 60

SQL, the Structured

Query Language
Overview
Introduction
DDL Commands
DML Commands
SQL Statements, Operators, Clauses
Aggregate Functions
Structured Query Language (SQL)
The ANSI standard language for the definition
and manipulation of relational database.

Includes data definition language (DDL),


statements that specify and modify database
schemas.

Includes a data manipulation language (DML),


statements that manipulate database content.
Some Facts on SQL
SQL data is case-sensitive, SQL commands are not.

First Version was developed at IBM by Donald D.


Chamberlin and Raymond F. Boyce. [SQL]

Developed using Dr. E.F. Codd's paper, “A Relational


Model of Data for Large Shared Data Banks.”

SQL query includes references to tuples variables


and the attributes of those variables
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 views in a database
 SQL can set permissions on tables, procedures,
and views
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


RDBMS
A Relational database management system
(RDBMS) is a database management system
(DBMS) that is based on the relational model as
introduced by E. F. Codd.

Relational model database is defined as a


database that group data into one or more
independent tables that can be related to one
another by fields common to each other.
What is table?
The data in RDBMS is stored in database objects called tables.
The table is a collection of related data entries and it consists
of columns and rows.
What is field?
Every table is broken up into smaller entities called
fields. The fields in the CUSTOMERS table consist
of :
ID, NAME, AGE, ADDRESS and SALARY.

A field is a column in a table that is designed to


maintain specific information about every record in
the table.
What is record or row?

A record, also called a row of data, is each individual


entry that exists in a table. For example there are
7 records in the above CUSTOMERS table.
SQL itself consists of four
principal sublanguages:
DDL (Data Definition Language) is used to define data
structures stored in the database. DDL statements allow
to create, modify or destroy individual database objects.

DML (Data Manipulation Language) is used to query and


change data stored in the database. DML statements
allow to select, insert, update and delete data in the
tables.
DCL (Data Control Language) is used to control access to data stored in
the database. DCL statements operate with privileges and allow
to grant and revoke privileges on applying certain DDL and DML
commands to certain database objects

TCL (Transaction Control Language) is used to control processing of


transactions in the database. Usual TCL statements
are commit to apply the changes introduced by the
transaction, rollback to undo them and savepoint to divide the
transaction into several smaller parts
CREATE DATABASE

Once a database is created, you can check it in


the list of databases as follows:
The SQL DROP DATABASE statement is used
to drop an existing database in SQL schema.

The SQL USE statement is used to select any


existing database in SQL schema.
SQL: DDL Commands
CREATE TABLE: used to create a table.

ALTER TABLE: modifies a table after it was created.

DROP TABLE: removes a table from a database.


SQL: CREATE TABLE Statement
Things to consider before you create your table are:
The type of data
the table name
what column(s) will make up the primary key
the names of the columns
Example to create a table
We can verify if table has been created successfully by
looking at the message displayed by the SQL server,
otherwise you can use DESC command as follows:
The SQL DROP TABLE statement is used to remove
a table definition and all data, indexes, triggers,
constraints, and permission specifications for that
table.

Now, if DESC command is used, then it would get error as


follows:
The SQL ALTER TABLE command is used to add, delete or
modify columns in an existing table. ALTER TABLE command
can add and drop various constraints on a an existing table.

The basic syntax of ALTER TABLE to add a new column in an


existing table is as follows:

The basic syntax of ALTER TABLE to drop column in an


existing table is as follows:
To change the name of the column
The basic syntax of ALTER TABLE to change the DATA
TYPE of a column in a table is as follows:

To create a PRIMARY KEY constraint on the "PId" column


when the table is already created, use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (PId)

To drop a PRIMARY KEY constraint, use the following SQL:


SQL: ALTER TABLE Statement
To add or drop columns on existing tables.
ALTER TABLE statement syntax:

ALTER TABLE <table name>


ADD attr datatype;
or
DROP COLUMN attr;
Example:
CREATE TABLE FoodCart (
date varchar(10),
food varchar(20), FoodCart
profit float date food profit
);

ALTER TABLE FoodCart FoodCart


ADD sold int; date food profit sold
ALTER TABLE FoodCart
FoodCart
DROP COLUMN profit;
date food sold
DROP TABLE FoodCart;
SQL: DML Commands
INSERT: adds new rows to a table.

UPDATE: modifies one or more attributes.

DELETE: deletes one or more rows from a table.


SQL: INSERT Statement
To insert a row into a table, it is necessary to have a value
for each attribute, and order matters.
INSERT statement syntax:
INSERT into <table name> VALUES ('value1', 'value2', NULL);

Example:
INSERT INTO countries VALUES('C1','India',1001);
Insert multiple rows by a single insert
statement
INSERT INTO countries VALUES
('C0001','India',1001),
('C0002','USA',1007),
('C0003','UK',1003);
SQL: UPDATE Statement
To update the content of the table:
UPDATE statement syntax:
UPDATE <table name> SET <attr> = <value>
WHERE <selection condition>;
Example: UPDATE employees SET SALARY = 8000
WHERE employee_id = 105 AND salary < 5000;
SQL: DELETE Statement
To delete rows from the table:
DELETE statement syntax:
DELETE FROM <table name>
WHERE <condition>;
Example: SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;

after
query

Note: If the WHERE clause is omitted all rows of data are deleted from the table.
SQL Statements, Operations, Clauses
SQL Statements:
Select
SQL Operations:
Join
Left Join
Right Join
Like
SQL Clauses:
Order By
Group By
Having
SQL: SELECT Statement
A basic SELECT statement includes 3 clauses

SELECT <attribute name> FROM <tables> WHERE <condition>

SELECT FROM WHERE


Specifies the Specifies the Specifies the
attributes that are tables that serve selection condition,
part of the as the input to the including the join
resulting relation statement condition.

Note: that you don't need to use WHERE


SQL: SELECT Statement (cont.)
Using a “*” in a select statement indicates that
every attribute of the input table is to be
selected.
Example: SELECT * FROM … WHERE …;

To get unique rows, type the keyword


DISTINCT after SELECT.
Example: SELECT DISTINCT * FROM …
WHERE …;
Example:
1)SELECT * FROM customers
WHERE favorite_website = 'techonthenet.com‘;

after
query

2)SELECT * FROM products WHERE product_name =


'Pear‘ OR product_name = 'Apple';

after
query
SQL: Join operation
A join can be specified in the FROM clause
which list the two input relations and the
WHERE clause which lists the join condition.
SQL: Join operation (cont.)
INNER JOIN
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Inner Join

CUSTOMERS after ORDERS


query
SQL: Join operation (cont.)
LEFT JOIN
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Left Join

after
CUSTOMERS query ORDERS
SQL: Join operation (cont.)
RIGHT JOIN
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
RIGHT JOIN ORDERS ON CUSTOMERS.ID = RDERS.CUSTOMER_ID;

RIGHT Join

after
CUSTOMERS query ORDERS
SQL: Like operation
Pattern matching selection
% (arbitrary string)
SELECT *
FROM emp
WHERE ID like ‘%01’;
 finds ID that ends with 01, e.g. 1001, 2001, etc
_ (a single character)
SELECT *
FROM emp
WHERE ID like ‘_01_’;
 finds ID that has the second and third character
as 01, e.g. 1010, 1011, 1012, 1013, etc
SQL: The ORDER BY Clause

asc (ascending order) desc (descending order)

SELECT * FROM CUSTOMERS SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY; ORDER BY NAME DESC;

after after
query query
SQL: The GROUP BY Clause
The function to divide the tuples into groups and
returns an aggregate for each group.
Usually, it is an aggregate function’s companion
EXAMPLE: SELECT NAME, SUM(SALARY) FROM
CUSTOMERS GROUP BY NAME;

after
query
SQL: The HAVING Clause

The substitute of WHERE for aggregate functions


Usually, it is an aggregate function’s companion
EXAMPLE: SELECT SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS GROUP BY age HAVING COUNT(age) >= 2;

after
query
SQL: Aggregate Functions
Are used to provide summarization information for
SQL statements, which return a single value.

 COUNT(attr)
 SUM(attr)
 MAX(attr)
 MIN(attr)
 AVG(attr)

Note: when using aggregate functions, NULL values


are not considered, except in COUNT(*) .
SQL: Aggregate Functions (cont.)

COUNT(attr): SELECT COUNT(*) FROM employee_tbl WHERE


name="Zara"; -> output : 2

SUM(attr): SELECT SUM(daily_typing_pages) FROM employee_tbl;


-> output : 1610

MAX(attr): SELECT MAX(daily_typing_pages) FROM employee_tbl;


-> output: 350
SQL: Aggregate Functions (cont.)

MIN(attr): SELECT MIN(daily_typing_pages) FROM employee_tbl;


-> output: 100

AVG(attr): SELECT AVG(daily_typing_pages) FROM employee_tbl;


-> output: 230.0000
Query Optimization
Techniques:
1. Optimize Your Queries For the Query Cache

The reason query cache does not work in the first line is the usage of the CURDATE()
function. This applies to all non-deterministic functions like NOW() and RAND() etc... Since
the return result of the function can change, MySQL decides to disable query caching for that
query.
Query Optimization
Techniques:
2. EXPLAIN Your SELECT Queries

Using the EXPLAIN keyword can give you insight on what MySQL is doing to execute your
query. This can help you spot the bottlenecks and other problems with your query or table
structures. The results of an EXPLAIN query will show you which indexes are being utilized,
how the table is being scanned and sorted.
Query Optimization
Techniques:
LIMIT 1 When Getting a Unique Row

Example:

Without Limit:
$r = mysql_query("SELECT * FROM user WHERE username= user1'");

With Limit:
$r = mysql_query("SELECT * FROM user WHERE username= user1' LIMIT 1");
Query Optimization
Techniques:
4. Index the Search Fields
Query Optimization
Techniques:
5. Index and Use Same Column Types for Joins

Example:

$r = mysql_query("SELECT company_name FROM users LEFT JOIN companies ON


(users.state = companies.state) WHERE users.id = $user_id");

If your application contains many JOIN queries, you need to make sure that the columns you
join by are indexed on both tables. This affects how MySQL internally optimizes the join
operation.
Query Optimization
Techniques:
6. Do Not ORDER BY RAND()

7. Avoid SELECT *

The more data is read from the tables, the slower the query will become. It increases the time
it takes for the disk operations. Also when the database server is separate from the web
server, you will have longer network delays due to the data having to be transferred between
the servers.
Query Optimization
Techniques:
8. Always Have an id Field

In every table have an id column that is the PRIMARY KEY, AUTO_INCREMENT and one of
the flavors of INT. Also preferably UNSIGNED, since the value can not be negative.

9. Use ENUM over VARCHAR

ENUM type columns are very fast and compact. Internally they are stored like TINYINT, yet
they can contain and display string values. This makes them a perfect candidate for certain
fields.

If you have a field, which will contain only a few different kinds of values, use ENUM instead
of VARCHAR. For example, it could be a column named "status", and only contain values
such as "active", "inactive", "pending", "expired" etc...

10. Use NOT NULL If You Can

NULL columns require additional space and they can add complexity to your comparison
statements. Just avoid them when you can. However, I understand some people might have
very specific reasons to have NULL values, which is not always a bad thing.
Query Optimization
Techniques:
11. Prepared Statements

In every table have an id column that is the PRIMARY KEY, AUTO_INCREMENT and one of
the flavors of INT. Also preferably UNSIGNED, since the value can not be negative.

$state = ‘Punjab’;

$stmt = $mysqli->prepare("SELECT username FROM user WHERE state=?")) {

// bind parameters
$stmt->bind_param(1, $state);
CREATE A NEW USER
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES


GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

REVOKE A PERMISSION
REVOKE [type of permission] ON [database name].[table name] FROM ‘[username]’@‘localhost’;
LIST OF COMMON POSSIBLE PERMISSIONS
FOR USER:
1. CREATE- allows them to create new tables or databases

2. DROP- allows them to them to delete tables or databases

3. DELETE- allows them to delete rows from tables

4. INSERT- allows them to insert rows into tables

5. SELECT- allows them to use the Select command to read through databases

6. UPDATE- allow them to update table rows

7. GRANT OPTION- allows them to grant or remove other users' privileges


TCL command:
Transaction Control Language(TCL) commands are used to manage transactions in
database.These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.

1. Commit command: Commit command is used to permanently save any transaaction into
database.

Syntax: commit;

2. Savepoint command: This command is used to temporarily save a transaction so that


you can rollback to that point whenever necessary.

Syntax: savepoint savepoint-name;

3. Rollback command: This command restores the database to last commited state. It is
also use with savepoint command to jump to a savepoint in a transaction.

Syntax: rollback to savepoint-name;


References
Riccardi, Greg. Principles of Database Systems with Internet and Java Applications.
Addison Wesley, 2001.

Ronald R. Plew, Ryan K. Stephens. Teach Yourself SQL in 24 Hours 3rd Edition.
Sams Publishing, 2003.

SQL http://en.wikipedia.org/wiki/SQL

W3C http://www.w3schools.com/sql/sql_tryit.asp

Wikipedia - SQL http://en.wikipedia.org/wiki/SQL

Wikipedia - join http://en.wikipedia.org/wiki/Join_(SQL)

Tutorialspoint https://www.tutorialspoint.com