You are on page 1of 42

1

SQL
Krishnaveni

2
Goals
SQL
3
SQL
SQL is short for Structured Query Language
It is a widely used database language, providing
means of data manipulation and database
creation.
Almost all modern Relational Database
Management Systems like MS SQL Server,
Microsoft Access, MSDE, Oracle, DB2, Sybase,
MySQL, Postgres and Informix use SQL as
standard database language. (each of them
uses different versions and has different names
for it.)
4
SQL: The Structured Query
Language
Developed by IBM (system R) in the
1970s
Need for a standard since it is used by
many vendors
Standards:
SQL-86
SQL-89 (minor revision)
SQL-92 (major revision)
SQL-99 (major extensions, current standard)
5
SQL DDL and DML
SQL statements can be divided into two
categories:
Data definition language (DDL) statements
Used for creating and modifying tables, views, and
other structures
CREATE, DROP, ALTER
Data manipulation language (DML)
statements.
Used for queries and data modification
INSERT, DELETE, UPDATE, SELECT
6
SQL DDL Statements
CREATE
ALTER
DROP
7
CREATE TABLE
CREATE TABLE statement is used for creating
relations
Each column is described with three parts:
column name
data type
optional constraints

8
CREATE TABLE Example
STUDENTS
StudentNumber: INTEGER NOT NULL
StudentLastName: CHAR(18) NOT NULL
StudentFirstName: CHAR(18) NOT NULL
Email: CHAR(50) NULL
PhoneNumber: CHAR(18) NULL
CREATE TABLE Students
(StudentNumber integer,
StudentLastName char(18) NOT NULL,
StudentFirstName char(18) NOT NULL,
Email char(50),
PhoneNumber char(18)
)
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu
312 Red Bob bred@usna.edu 443-451-7865
9
Constraints
Constraints can be defined within the CREATE
TABLE statement, or they can be added to the
table after it is created using the ALTER table
statement
Five types of constraints:
NULL/NOT NULL
PRIMARY KEY may not have null values
UNIQUE may have null values
CHECK
FOREIGN KEY
10
Constraints Examples
STUDENTS
StudentNumber: INTEGER NOT NULL
StudentLastName: CHAR(18) NOT NULL
StudentFirstName: CHAR(18) NOT NULL
Email: CHAR(50) NULL (AK1.1)
PhoneNumber: CHAR(18) NULL
CREATE TABLE Students
(StudentNumber integer,
StudentLastName char(18) NOT NULL,
StudentFirstName char(18) NOT NULL,
Email char(50),
PhoneNumber char(18),
PRIMARY KEY (StudentNumber),
UNIQUE (Email)
)
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu
312 Doe Bob bred@usna.edu 443-451-7865
11
Default Values and Data Constraints
Students table
Default value for
PhoneNumber:
410-123-4567
Email like
*@usna.edu
CREATE TABLE Students
(StudentNumber integer,
StudentLastName char(18) NOT NULL,
StudentFirstName char(18) NOT NULL,
Email char(50),
PhoneNumber char(18) DEFAULT 410-
123-4567,
PRIMARY KEY (StudentNumber),
UNIQUE(Email),
CHECK (Email LIKE *@usna.edu)
)
Syntax depends on DBMS!!!
12
FOREIGN KEY Constraints
Majors
I:SN
U:SN
D:SN
U:C
DEPARTMENTS
DepartmentName: char(18)
Phone: char(18)
Building: char(18)
Room: integer
STUDENTS
StudentNumber: integer
StudentLastName: char(18)
StudentFirstName: char(18)
Email: varchar(50)
PhoneNumber: char(18)
DepartmentName: char(18) (FK)
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber MajorDepartmentName
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu Computer Science
312 Doe Bob bred@usna.edu 443-451-7865 Mathematics
DepartmentName Phone Building Room
Mathematics 410-293-4573 Michelson Hall 308
History 410-293-2255 Sampson Hall 120
Computer Science 410-293-6800 Michelson Hall 340
13
FOREIGN KEY Constraints
Majors
I:SN
U:SN
D:SN
U:C
DEPARTMENTS
DepartmentName: char(18)
Phone: char(18)
Building: char(18)
Room: integer
STUDENTS
StudentNumber: integer
StudentLastName: char(18)
StudentFirstName: char(18)
Email: varchar(50)
PhoneNumber: char(18)
DepartmentName: char(18) (FK)
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber MajorDepartmentName
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu Computer Science
312 Doe Bob bred@usna.edu 443-451-7865 Mathematics
DepartmentName Phone Building Room
Mathematics 410-293-4573 Michelson Hall 308
History 410-293-2255 Sampson Hall 120
Computer Science 410-293-6800 Michelson Hall 340
CREATE TABLE Departments
(DepartmentName char(18),
Phone char(18) NOT NULL,
Building char(18),
Room integer,
PRIMARY KEY (DepartmentName)
)
14
FOREIGN KEY Constraints
CREATE TABLE Students
(StudentNumber integer,
StudentLastName char(18) NOT NULL,
StudentFirstName char(18) NOT NULL,
Email char(50),
PhoneNumber char(18),
MajorDepartmentName char(18),
PRIMARY KEY (StudentNumber),
UNIQUE(Email),
FOREIGN KEY (MajorDepartmentName)
REFERENCES Departments (DepartmentName)
ON DELETE SET NULL
ON UPDATE CASCADE
)
SQL/92 and SQL:1999
support all 4 options on
deletes and updates.
Default is NO ACTION
(delete/update is
rejected)
CASCADE (also delete
all rows that refer to
deleted row)
SET NULL / SET
DEFAULT (sets foreign
key value of referencing
row)

15
ALTER Statement
ALTER statement changes
table structure,
properties, or
constraints
after the table has been created

16
Adding and Dropping Columns
The following statement will add a column
named BirthDate to the Students table:
ALTER TABLE Students ADD COLUMN BirthDate Datetime
NULL;
You can drop an existing column with the
statement:
ALTER TABLE Students DROP COLUMN BirthDate;
17
Adding and Dropping Constraints
ALTER can be used to add a constraint as
follows:
ALTER TABLE Student ADD CONSTRAINT DepartmentFK
FOREIGN KEY (MajorDepartmentName)
REFERENCES Departments (DepartmentName)
ON DELETE NO ACTION
ON UPDATE CASCADE

ALTER can be used to drop a constraint:
ALTER TABLE Student DROP CONSTRAINT DepartmentFK;
18
Removing Tables
SQL DROP TABLE:
DROP TABLE Departments;
If there are constraints:
ALTER TABLE Students
DROP CONSTRAINT DepartmentFK;
DROP TABLE Departments;

19
SQL DDL and DML
Data definition language (DDL)
statements
Used for creating and modifying tables, views, and
other structures
CREATE, ALTER, DROP
Data manipulation language (DML)
statements.
Used for queries and data modification
INSERT, DELETE, UPDATE, SELECT
20
INSERT Statement
INSERT command:
INSERT INTO Students (StudentNumber, StudentLastName,
StudentFirstName)
VALUES (190, Smith', John);

INSERT INTO Students VALUES(190, Smith, John,
jsmith@usna.edu, 410-431-3456)



Bulk INSERT:
INSERT INTO Students (StudentNumber, StudentLastName,
StudentFirstName, Email, PhoneNumber)
SELECT *
FROM Second_Class_Students;
21
UPDATE Statement
UPDATE command:
UPDATE Students
SET PhoneNumber = 410-123-4567
WHERE StudentNumber = 673;

BULK UPDATE command:
UPDATE Students
SET PhoneNumber = 410-123-4567
WHERE StudentLAstName = Doe;

Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu
312 Doe Bob bred@usna.edu 443-451-7865
22
DELETE Statement
DELETE command:
DELETE FROM Students
WHERE StudentNumber = 190;
If you omit the WHERE clause, you will
delete every row in the table!

23
The SQL SELECT Statement
The fundamental framework for SQL query
statement is the SQL SELECT statement:
SELECT {ColumnName(s)}
FROM {TableName(s)}
WHERE {Conditions}
24
Specific Columns on One Table
SELECT StudentNumber,StudentLastName
FROM Students;
StudentNumber StudentLastName
190 Smith
673 Doe
312 Doe
25
Specify Column Order
SELECT StudentLastName,StudentNumber
FROM Students;
StudentLastName StudentNumber
Smith 190
Doe 673
Doe 312
26
The DISTINCT Keyword
SELECT
StudentLastName
FROM Students;
StudentLastName
Smith
Doe
Doe
SELECT DISTINCT
StudentLastName
FROM Students;
StudentLastName
Smith
Doe
27
Selecting All Columns:
The Asterisk (*) Keyword
SELECT *
FROM Students;
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber
190 Smith John jsmith@usna.edu 410-431-3456
673 Doe Jane jdoe@usna.edu
312 Doe Bob bred@usna.edu 443-451-7865
28
Specific Rows from One Table
SELECT *
FROM Students
WHERE StudentLastName = Doe';

NOTE: SQL wants a plain ASCII single quote: ' NOT !
Student
Number
Student
LastName
Student
FirstName
Email PhoneNumber
673 Doe Jane jdoe@usna.edu
312 Doe Bob bred@usna.edu 443-451-7865
29
Specific Columns and Rows from
One Table
SELECT StudentNumber,
StudentLastName,
StudentFirstName
FROM Students
WHERE PhoneNumber NOT NULL;
Student
Number
Student
LastName
Student
FirstName
190 Smith John
312 Doe Bob
Order By
The SQL ORDER BY clause is used to sort the data in ascending or
descending order, based on one or more columns. Some database
sorts query result
SELECT column-list FROM table_name [WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];s in
ascending order by default.
SELECT * FROM Customers ORDER BY DOB
SELECT * FROM Customers ORDER BY DOB DESC
SELECT * FROM Customers ORDER BY DOB, LastName

30
SQL AND
The AND operator allows the existence of multiple conditions in an
SQL statement's WHERE
SELECT column1, column2, columnN FROM table_name WHERE
[condition1] AND [condition2]...AND [conditionN];
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000
AND age < 25;

31
SQL OR
The OR operator is used to combine multiple conditions in an SQL
statement's WHERE clause.
SELECT column1, column2, columnN FROM table_name WHERE
[condition1] OR [condition2]...OR [conditionN]
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000
OR age < 25;

32
SQL LIKE
The SQL LIKE clause is
very useful when you want
to specify a search
condition within your SQL
WHERE clause, based on a
part of a column contents.
SELECT DOB
FROM Customers
WHERE FirstName LIKE
'J%'
Result is: 2/4/1968 and
20/10/1980
The '%' is a so called
wildcard character and
represents any string in our
pattern.
FirstName LastName DOB
John Smith 2/4/1968
Steven Goldfish 4/4/1974
James Smith 20/10/1980
SQL LIKE contd.
Another wildcard character is '_' representing any single
character.
The '[]' specifies a range of characters.
SELECT *
FROM Customers
WHERE Phone LIKE '[4-6]_6%'
This SQL expression will return all customers satisfying
the following conditions:
The Phone column starts with a digit between 4 and 6 ([4-6])
Second character in the Phone column can be anything (_)
The third character in the Phone column is 6 (6)
The remainder of the Phone column can be any character string
(%)
SQL LIKE examples

35
SQL Aggregate functions
COUNT
Used to count number of rows in a given table.
MAX
Allows us to select the highest values for a certain column.
MIN
Allows us to select the lowest values for a certain column.
AVG
Selects the average value for a certain table column.
SUM
Allows selecting the total for a numeric column.
Examples
SELECT COUNT(LastName) AS NumberOfCustomers
FROM Customers
SELECT MAX(Sal) AS Maxsal
FROM Emp
SELECT MIN(Sal) AS Minsal
FROM Emp
SELECT AVG(Sal) AS Avgsal
FROM Emp
SELECT SUM(SaleAmount)
FROM Sales
Types of SQL join
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no
matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are
no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the tables.
SELF JOIN: is used to join a table to itself as if the table were two
tables, temporarily renaming at least one table in the SQL
statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of
records from the two or more joined tables.

38
INNER JOIN
The INNER JOIN creates a new result table by combining column
values of two tables (table1 and table2) based upon the join-
predicate.
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS INNER
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
39
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if
there are no matches in the right table. This means that if the ON
clause matches 0 (zero) records in right table, the join will still return
a row in the result, but with NULL in each column from right table.
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
40

41
42

You might also like