Vous êtes sur la page 1sur 50

SQL Commands

SQL Commands can be divided into 3 sub


groups.
DDL (Data Definition Language)
DML (Data Manipulation Language)
DCL (Data Control Language)

DDL (Data Definition Language)


It deals with database and descriptions, of how the data
should reside in the database.
CREATE to crate objects in the database
ALTER alters the structure of the database
DROP delete objects from the database

DATABASE (CREATE/ DROP)


To create the database
CREATE DATABAE db1;
To show all databases
SHOW DATABASES;
To drop the database
DROP DATABASE db1;

CREATE TABLE
Staff ( StaffNo, Salary, Lname)
CREATE TABLE Staff (
StaffNo INTEGER,
Salary FLOAT,
Lname VARCHAR(20)
);

Data Types
Integer (INT, INTEGER & SMALLINT)
Real numbers (FLOAT, REAL, DOUBLE)
Formatted numbers DECIMAL(i,j) or DEC(i,j) or NUMERIC(i,j)
Character strings
Fixed length: CHAR(n) or CHARACTER(n)
Variable length: VARCHAR(n)
Date and Time: DATE, TIME, TIME(i) and DATETIME data types

Example :
Professor(P_SSN, Pname, PAge, NIC, Rank)

CREATE TABLE Professor(


P_SSN CHAR(5),
PName VARCHAR(10),
PAge INTEGER,
NIC CHAR(10),
Rank INTEGER
);

Primary Key constraint


CREATE TABLE Professor(
P_SSN CHAR(5),
PName VARCHAR(10),
PAge INTEGER,
NIC CHAR(10),
Rank INTEGER,
PRIMARY KEY (P_SSN)
);
Alternative:

CREATE TABLE Professor(


P_SSN CHAR(5) PRIMARY KEY,
PName VARCHAR(10),
PAge INTEGER,
NIC CHAR(10),
Rank INTEGER
);

Candidate Keys
UNIQUE
CREATE TABLE Professor(
P_SSN CHAR(5),
PName VARCHAR(10),
PAge INTEGER,
NIC CHAR(10),
Rank INTEGER,
PRIMARY KEY (P_SSN),
UNIQUE (NIC)
);

Referential Integrity Constraints


(FOREIGN KEYS)
Professor(P_SSN, Pname, PAge, NIC, Rank)
Project(P_Number, Sponsor, Budget, Sdate, Edate, P_SN)
CREATE TABLE Project(
P_Number INTEGER,
Sponsor VARCHAR(20),
Budget DOUBLE,
Sdate DATETIME,
Edate DATETIME,
P_SN CHAR(5),
PRIMARY KEY (P_Number),
CONSTRAINT fk_Project FOREIGN KEY(P_SN) REFERENCES Professor (P_SSN)
);

NOT NULL and CHECK Constraint


CREATE TABLE Professor(
P_SSN CHAR(5) NOT NULL,
PName VARCHAR(10) NOT NULL,
PAge INTEGER CHECK (PAge BETWEEN 30 AND 65),
NIC CHAR(10),
Rank INTEGER,
PRIMARY KEY (P_SSN),
UNIQUE (NIC)
);
Show all tables of database
SHOW TABLES;
Describe each table of the database
DESCRIBE Professor;

ALTER TABLE
ALTER TABLE can be used to add or drop a column, change a
column definition.

The NOT NULL constraint is not allowed for altered column.


Adding a column
ALTER TABLE Professor ADD Re_Speciality VARCHAR(30);
Deleting a column
ALTER TABLE Staff DROP COLUMN Salary;
Changing column name
ALTER TABLE Staff CHANGE Lname LastName VARCHAR(20);
Changing a column size
ALTER TABLE Professor MODIFY Re_Speciality VARCHAR(40);

DROP TABLE
Used to remove a relation and its definition
The relation can no longer be used in queries, updates, or any
other commands since its description no longer exists
DROP TABLE Staff;
or
DROP TABLE Staff RESTRICT/CASCADE;
RESTRICT drops if no other constraints (such as foreign keys
or views exist)
CASCADE drops all referential constraints

REFERENTIAL INTEGRITY OPTIONS


Operations
ON UPDATE
ON DELETE

Actions
SET NULL
CASCADE
SET DEFAULT

CREATE TABLE Department(


D_Number INT PRIMARY KEY,
DName VARCHAR(20),
Main_Office VARCHAR(20),
PSN CHAR(5),
CONSTRAINT fk_Department FOREIGN KEY(PSN) REFERENCES
Professor (P_SSN) ON DELETE CASCADE ON UPDATE NO ACTION
);
or
ON DELETE SET NULL ON UPDATE CASCADE
or
ON DELETE SET NULL ON UPDATE NO ACTION

DML (Data Manipulation Language)


It deals with data manipulation and includes most common SQL
statements such SELECT, INSERT, UPDATE, DELETE etc, and it is
used to store, modify, retrieve, delete and update data in
database.
SELETE retrieve data from the database
INSERT insert data into a table
UPDATE updates existing data within a table

DELETE delete all records from a database table

Example:
Employee(eid, ename, salary, deptno)

Department(dno, dname, location)

INSERT Statement
Inserting a single row
INSERT INTO Department VALUES ("A0001", "IT", "Colombo");

The order of values must be the same as in the CREATE


TABLE statement.

Inserting to user-specified columns

INSERT INTO Department (dno, dname, location) VALUES


("A0002", "Management", "Galle");
Only the columns are specified and filled with values.
Unspecified columns are filled with NULL if there is no default
values.

Inserting multiple rows

INSERT INTO Employee VALUES


("E1101","Kamal",15000.00,"A0001"),
("E1102","Nimal",16000.00,"A0001");

DELETE Statement
Deleting tuples from table
Deleting all records

eg: DELETE FROM Department;


Deleting only specified records

DELETE FROM <table>


WHERE <selection-condition>

eg: DELETE FROM Department WHERE dno =A0002;

UPDATE Statement
Updating tuples in a table
UPDATE <table>
SET <column> = <expression>
WHERE <selection condition>

Updating all tuples


UPDATE Employee SET salary = 25000.00;

Updating selected tuple


UPDATE Employee
SET salary = 16000.00
WHERE eid = E1103;

SELECT Statement
Basic form of the SQL SELECT statement
SELECT <attribute-list>
FROM <table-list>
WHERE <condition>
<attribute-list> is a list of column names
<table-list> is a list of tables which the query accesses
<condition> is the condition that the output rows must satisfy

Select names of all employees

SELET ename
FROM Employee;

Select names of employees working in the

department A0001
SELECT ename
FROM Employee
WHERE deptNo = A0001;

Select all the columns of Employee table.


SELECT *
FROM Employee;

ALL (by default) allows duplicates


DISTINCT disallow duplicates
SELECT ALL deptno
FROM Employee;
SELECT DISTINCT deptno
FROM Employee;

List all the department names which are in


Colombo
Select Employee name and salary of each
employee who are in department A0005.

Select number and name of department


where are in Kandy

List all the department names which are in Colombo OR

Kandy
SELECT DISTINCT dname

FROM Department
WHERE location = Colombo or location = Kandy;

List all the employee names who are in department


A0001 and salary grater than 10000
SELECT ename

FROM Employee
WHERE deptno=A0001 AND salary>10000;

JOINS
List the employee information with their
department details who are working in
departments

SELECT *
FROM Employee, Department
WHERE deptNo = dno;

Print the names of employees and the names of their

working departments

SELECT ename, dname


FROM Employee, Department
WHERE deptNo = dno;

ALIASES

& RENAME

Sometimes same attribute name appears


in multiple tables. Then we need to use
the table name with attribute name to
identify attributes separately.
Sometime we need to change the field
name for display. Then rename it.

SELECT employee.ename, department.dname


FROM employee, department
WHERE employee.deptNo = department.dno;
SELECT e.ename AS EmployeeName,
d.dname AS DepartmentName
FROM employee e, department d
WHERE e.deptNo = d.dno;
Print the name, salary, department name of each employee whose
salary greater than 15000.

Rename the field names.


ename : Employee_Name
salary : Employee_Salary
dname : Departmeny_Name

LIKE comparison operator can be used with

% : replaces an arbitrary number of


characters
_ : replaces a single character

List the employee names starting with K


SELECT ename
FROM Employee
WHERE ename LIKE K%;

SELECT ename
FROMEmployee
WHERE ename LIKE Kama_;

Ordering of results
Using ORDER BY clause &
ASC (default) and DESC clauses

List the employees ID and name of the department IT in

ascending order of the salary


SELECT e.eid, d.dname
FROM Employee e, Department d
WHERE e.deptNo = A0001 and e.deptNo = d.dno
ORDER BY e.salary ASC;

Ordering multiple columns


List the employee ID, department and salary, display the

result in ascending order of department and descending


order of salary

SELECT
FROM
WHERE
ORDER BY

e.eid, d.dname, e.salary


Employee e, Department d
e.deptNo = d.dno
e.deptNo ASC, e.salary DESC;

IS NULL
In SQL, NULLs are considered to be distinct from every other
null.
List the employees who does not have salary

SELECT
FROM
WHERE

ename
Employee
salary IS NULL

IS NOT NULL

List the employees who have salaries


SELECT
FROM
WHERE

ename
Employee
salary IS NOT NULL;

Aggregate Functions & Grouping


Aggregate Functions
SUM, MIN, MAX, COUNT, AVG
Find the average, minimum, maximum salary of employees

SELECT
FROM

MIN(salary), MAX(salary),AVG(salary)
Employee;

COUNT(*) Number of rows


Count the number of employees in the company
SELECT COUNT(*)
FROM Employee;
COUNT(*) returns the number of rows in the result
of the query including NULL rows.

COUNT(DISTINCT ) Count the distinct values


Count the different salary grades in the company
SELECT COUNT(DISTINCT salary)
FROM Employee;
Find the total salary for all the Employees
SELECT SUM(salary) AS Total_Salary
From Employee;

Purchase(pid, product, date, price, quantity)


Example : find total sales for the entire database
SELECT Sum(price * quantity)
FROM Purchase;

Example : find total sales of Banana


SELECT Sum(price * quantity)
FROM Purchase
WHERE product = Banana;

Grouping:
Usually, we want aggregations on certain parts of the relation.
Purchase(pid, product, date, price, quantity)

Find total sales for each product.


SELECT
product, Sum(price*quantity) AS TotalSales
FROM
Purchase
GROUP BY product;

HAVING Clause:

Find total sales for each product that has sold


at least 30 items after 2015/2/1.

SELECT
FROM
WHERE
GROUP BY
HAVING

product, Sum(price * quantity)


Purchase
date > 2015/2/1
product
Sum(quantity) >= 30;

HAVING clause contains conditions on aggregates.

NESTING OF QUERIES
Print

names of employees working for


Engineering department and getting a salary >
Rs. 15,000
SELECT ename
FROM Employee
WHERE salary > 15000 and deptNo =(
SELECT dno
FROM Department
WHERE dname = Engineering);

Find nic and names of employees who work for both project 1
and project 3.
Emp( nic, name
Works_On( enic, pnum
SELECT
FROM
WHERE

e.nic, e.name
Emp e, Works_On w
e.nic = w.enic AND
w.pnum = 3 AND
e.nic IN (SELECT e1.nic
FROM Emp e1, Works_On w1
WHERE e1.nic = w1.enic AND
w1.pnum = 1);

Find nic and names of employees who do not work for


project 5
SELECT
FROM
WHERE

e.nic, e.name
Emp e, Works_On w
e.nic = w.enic AND
e.nic NOT IN
(SELECT enic
FROM Works_On
WHERE pnum = 5);

Correlated Nested Queries


Nested queries referencing tables of outer queries
List the employee who has at least one dependent who

has the same gender as the employee

Employee(NIC, NAME, GENDER)


Dependent(DNIC, ENIC, GENDER)

SELECT
FROM
WHERE

E. NAME
Employee E
E.NIC IN (
SELECT ENIC
FROM Dependent
WHERE GENDER = E.GENDER);

EXISTS
Can be used to check the existence of set

Previous example
SELECT
FROM
WHERE

E.NAME
Employee E
EXISTS (
SELECT *
FROM Dependent
WHERE ENIC = E.NIC AND
GENDER = E.GENDER);

NOT EXISTS
List the names of employees who do not have any
dependents.
SELECT
FROM
WHERE

E.NAME
Employee AS E
NOT EXISTS (
SELECT *
FROM Dependent
WHERE ENIC = E.NIC);

Vous aimerez peut-être aussi