Upload
judith-nelson
View
239
Download
0
Embed Size (px)
Citation preview
8/13/2019 Introduction top SQL Syntax
1/63
SQL
Database Design Fundamentals
8/13/2019 Introduction top SQL Syntax
2/63
SQL
SQL stands for Structured Query Language
SQL is a standard language for accessing
databases.
It can be used on many database systems:-
Oracle, MySQL, Access, SQL Server,
8/13/2019 Introduction top SQL Syntax
3/63
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 stored procedures in a database SQL can create views in a database
SQL can set permissions on tables, procedures, andviews
8/13/2019 Introduction top SQL Syntax
4/63
SQL: DDL & DML &DCL
SQL can be divided into three parts:
DDL: Data Definition Language
DML: Data Manipulation Langauge DCL: Data Control Langauge
8/13/2019 Introduction top SQL Syntax
5/63
DDL
The DDL part of SQLpermits database tables to be created ordeleted. It also define indexes (keys), specify links betweentables, and impose constraints between tables. The mostimportant DDL statements in SQL are:
CREATE DATABASE- creates a new database
ALTER DATABASE- modifies a database
CREATE TABLE- creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
8/13/2019 Introduction top SQL Syntax
6/63
DML
The query and update commands form the DML
part of SQL:
SELECT- extracts data from a database
UPDATE- updates data in a database
DELETE- deletes data from a database
INSERT INTO - inserts new data into adatabase
8/13/2019 Introduction top SQL Syntax
7/63
SQL SELECT
The SELECT statement is used to select data from adatabase.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
And
SELECT * FROM table_name
Note:SQL is not case sensitive. SELECT is the same asselect.
8/13/2019 Introduction top SQL Syntax
8/63
SELECT EXAMPLE
SELECT * FROM Persons
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
The Persons table above contains three records (one for each person) and five
columns (P_Id, LastName, FirstName, Address, and City).
8/13/2019 Introduction top SQL Syntax
9/63
Select Example 2
SELECT LastName,FirstName FROM Persons
The result-set will look like this:LastName FirstNameHansen Ola
Svendson Tove
Pettersen Kari
8/13/2019 Introduction top SQL Syntax
10/63
The SQL SELECT DISTINCT Statement
In a table, some of the columns may contain duplicatevalues. This is not a problem, however, sometimes youwill want to list only the different (distinct) values in atable.
The DISTINCT keyword can be used to return only distinct(different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name
8/13/2019 Introduction top SQL Syntax
11/63
DISTINCT EXAMPLE
SELECT DISTINCT City FROM Persons
City
Sandnes
Stavanger
The result-set will look like this:
8/13/2019 Introduction top SQL Syntax
12/63
The WHERE Clause
The WHERE clause is used to filter records.
The WHERE clause is used to extract only thoserecords that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
8/13/2019 Introduction top SQL Syntax
13/63
8/13/2019 Introduction top SQL Syntax
14/63
Quotes around text fields SQL uses single quotes around text values
Numeric values should not be enclosed in quotes.
For text values:
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:SELECT * FROM Persons WHERE FirstName=Tove
For numeric values:
This is correct:
SELECT * FROM Persons WHERE Year=1965This is wrong:
SELECT * FROM Persons WHERE Year='1965'
O t All d i th WHERE
8/13/2019 Introduction top SQL Syntax
15/63
Operators Allowed in the WHERE
Clause
Operator Description
= Equal
Not equal
> Greater than
< Less than
>= Greater than or equal
8/13/2019 Introduction top SQL Syntax
16/63
8/13/2019 Introduction top SQL Syntax
17/63
AND Operator Example
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
The "Persons" table:
Now we want to select only the persons with the first name equal to "Tove" ANDthe last name equal to "Svendson":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'AND LastName='Svendson'
The result-set will look like this:
8/13/2019 Introduction top SQL Syntax
18/63
OR Operator Example
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Now we want to select only the persons with the first name equal to "Tove"
OR the first name equal to "Ola":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove' OR FirstName='Ola
The result-set will look like this:
8/13/2019 Introduction top SQL Syntax
19/63
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set.
The ORDER BY keyword is used to sort the result-set by aspecified column.
The ORDER BY keyword sort the records in ascending order
by default. If you want to sort the records in a descending order, you
can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name ORDER BY column_name(s) ASC|DESC
8/13/2019 Introduction top SQL Syntax
20/63
ORDER BY Example
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
The "Persons" table:
Now we want to select all the persons from the table above, however, we want to
sort the persons by their last name.
We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
4 Nilsen Tom Vingvn 23 Stavanger
3 Pettersen Kari Storgt 20 Stavanger
2 Svendson Tove Borgvn 23 Sandnes
8/13/2019 Introduction top SQL Syntax
21/63
ORDER BY DESC Example
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
1 Hansen Ola Timoteivn 10 Sandnes
Now we want to select all the persons from the table above, however,
we want to sort the persons descending by their last name.
We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName DESC
The result-set will look like this:
The INSERT INTO Statement
8/13/2019 Introduction top SQL Syntax
22/63
The INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will beinserted, only their values:
INSERT INTO table_name VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to beinserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1,value2, value3,...)
8/13/2019 Introduction top SQL Syntax
23/63
8/13/2019 Introduction top SQL Syntax
24/63
Insert Data Only in Specified Columns
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id",
"LastName" and the "FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem',
'Jakob')The "Persons" table will now look like this:
8/13/2019 Introduction top SQL Syntax
25/63
The UPDATE Statement
The UPDATE statement is used to update records in a table.
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note:Notice the WHERE clause in the UPDATE syntax. The WHEREclause specifies which record or records that should be updated. If youomit the WHERE clause, all records will be updated!
8/13/2019 Introduction top SQL Syntax
26/63
SQL UPDATE Example
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes
8/13/2019 Introduction top SQL Syntax
27/63
SQL UPDATE Warning
P_Id LastName FirstName Address City
1 Hansen Ola Nissestien 67 Sandnes
2 Svendson Tove Nissestien 67 Sandnes
3 Pettersen Kari Nissestien 67 Sandnes
4 Nilsen Johan Nissestien 67 Sandnes
5 Tjessem Jakob Nissestien 67 Sandnes
Be careful when updating records. If we had omitted the WHERE clause in theexample above, like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
The "Persons" table would have looked like this:
8/13/2019 Introduction top SQL Syntax
28/63
The Delete Statement
The DELETE statement is used to delete records in atable.
The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_nameWHERE some_column=some_value
Note:Notice the WHERE clause in the DELETE syntax. The
WHERE clause specifies which record or records thatshould be deleted. If you omit the WHERE clause, allrecords will be deleted!
8/13/2019 Introduction top SQL Syntax
29/63
Delete Example
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'
The "Persons" table will now look like this:
8/13/2019 Introduction top SQL Syntax
30/63
Delete All Rows
It is possible to delete all rows in a table withoutdeleting the table. This means that the tablestructure, attributes, and indexes will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name
8/13/2019 Introduction top SQL Syntax
31/63
CREATE DATABASE
CREATE DATABASE database_name
ExampleCREATE DATABASE my_db
8/13/2019 Introduction top SQL Syntax
32/63
CREATE TABLE
The CREATE TABLE statement is used to createa table in a database.
SQL CREATE TABLE Syntax:
CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,
column_name3 data_type,....)
8/13/2019 Introduction top SQL Syntax
33/63
CREATE TABLE EXAMPLE
CREATE TABLE Persons
(P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
8/13/2019 Introduction top SQL Syntax
34/63
Empty Persons Table
P_Id LastName FirstName Address City
The P_Id column is of type int and will hold a number. The LastName, FirstName,
Address, and City columns are of type varchar with a maximum length of 255 characters.The empty "Persons" table will now look like this:
8/13/2019 Introduction top SQL Syntax
35/63
SQL Constraints
Constraints are used to limit the type of data that can go intoa table.
Constraints can be specified when a table is created (with theCREATE TABLE statement) or after the table is created (withthe ALTER TABLE statement).
We will focus on the following constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
8/13/2019 Introduction top SQL Syntax
36/63
SQL NOT NULL ConstraintThe NOT NULL constraint enforces a column to NOT accept NULLvalues.
The NOT NULL constraint enforces a field to always contain a value.This means that you cannot insert a new record, or update a recordwithout adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName"column to not accept NULL values:
CREATE TABLE Persons(P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),City varchar(255)
)
8/13/2019 Introduction top SQL Syntax
37/63
SQL UNIQUE CONSTRAINT
The UNIQUE constraint uniquely identifies eachrecord in a database table.
The UNIQUE and PRIMARY KEY constraints both
provide a guarantee for uniqueness for a columnor set of columns.
A PRIMARY KEY constraint automatically has aUNIQUE constraint defined on it.
Note that you can have many UNIQUE constraintsper table, but only one PRIMARY KEY constraintper table.
8/13/2019 Introduction top SQL Syntax
38/63
Unique Constraint on Create Table
The following SQL creates a UNIQUE constraint on the"P_Id" column when the "Persons" table is created:
CREATE TABLE Persons(P_Id int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),
Address varchar(255),City varchar(255))
SQL UNIQUE Constraint on ALTER
8/13/2019 Introduction top SQL Syntax
39/63
SQL UNIQUE Constraint on ALTER
TABLE
To create a UNIQUE constraint on the "P_Id"
column when the table is already created, use
the following SQL
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE
(P_Id,LastName)
8/13/2019 Introduction top SQL Syntax
40/63
DROP UNIQUE CONSTRAINT
To drop a UNIQUE constraint, use the
following SQL:
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
8/13/2019 Introduction top SQL Syntax
41/63
PRIMARY KEY CONSTRAINT
The PRIMARY KEY constraint uniquely
identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL
values.
Each table should have a primary key, and
each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on
8/13/2019 Introduction top SQL Syntax
42/63
SQL PRIMARY KEY Constraint on
CREATE TABLE
The following SQL creates a PRIMARY KEY on the"P_Id" column when the "Persons" table is created:
CREATE TABLE Persons
(P_Id int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),
City varchar(255))
THIS IS THE EASIEST WAY
8/13/2019 Introduction top SQL Syntax
43/63
OR.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,FirstName varchar(255),
Address varchar(255),
City varchar(255),PRIMARY KEY (P_Id)
)
8/13/2019 Introduction top SQL Syntax
44/63
Composite Primary Keys
To allow naming of a PRIMARY KEY constraint, and for defininga PRIMARY KEY constraint on multiple columns, use thefollowing SQL syntax:
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),
City varchar(255),CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName))
SQL PRIMARY KEY Constraint on
8/13/2019 Introduction top SQL Syntax
45/63
SQL PRIMARY KEY Constraint on
ALTER TABLE
To create a PRIMARY KEY constraint on the
"P_Id" column when the table is already
created, use the following SQL:
ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)
8/13/2019 Introduction top SQL Syntax
46/63
COMPOSITE PRIMARY KEY USING
ALTER
To allow naming of a PRIMARY KEY constraint,and for defining a PRIMARY KEY constraint onmultiple columns, use the following SQL syntax:
ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY(P_Id,LastName)
Note:If you use the ALTER TABLE statement to
add a primary key, the primary key column(s)must already have been declared to not containNULL values (when the table was first created).
i
8/13/2019 Introduction top SQL Syntax
47/63
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the
following SQL:
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
SQL FOREIGN KEY C t i t
8/13/2019 Introduction top SQL Syntax
48/63
SQL FOREIGN KEY Constraint
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables:
The "Persons" table:
The "Orders" table:
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the
"Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
SQL FOREIGN KEY Constraint on
8/13/2019 Introduction top SQL Syntax
49/63
SQL FOREIGN KEY Constraint on
CREATE TABLE
The following SQL creates a FOREIGN KEY on the"P_Id" column when the "Orders" table iscreated:
CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id))
8/13/2019 Introduction top SQL Syntax
50/63
SQL FOREIGN KEY Constraint on
8/13/2019 Introduction top SQL Syntax
51/63
SQL FOREIGN KEY Constraint onALTER TABLE
To create a FOREIGN KEY constraint on the
"P_Id" column when the "Orders" table is
already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
8/13/2019 Introduction top SQL Syntax
52/63
To allow naming of a FOREIGN KEY constraint,
and for defining a FOREIGN KEY constraint onmultiple columns, use the following SQL syntax:
ALTER TABLE OrdersADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
T DROP FOREIGN KEY C t i t
8/13/2019 Introduction top SQL Syntax
53/63
To DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the
following SQL:
ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders
SQL CHECK C t i t
8/13/2019 Introduction top SQL Syntax
54/63
SQL CHECK Constraint
The CHECK constraint is used to limit the value
range that can be placed in a column.
If you define a CHECK constraint on a single
column it allows only certain values for this
column.
If you define a CHECK constraint on a table it
can limit the values in certain columns basedon values in other columns in the row.
SQL CHECK Constraint on CREATE
8/13/2019 Introduction top SQL Syntax
55/63
SQL CHECK Constraint on CREATETABLE
The following SQL creates a CHECK constraint on the"P_Id" column when the "Persons" table is created. TheCHECK constraint specifies that the column "P_Id" mustonly include integers greater than 0.
CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,
FirstName varchar(255),Address varchar(255),
8/13/2019 Introduction top SQL Syntax
56/63
SQL CHECK Constraint on ALTER TABLE
8/13/2019 Introduction top SQL Syntax
57/63
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id"
column when the table is already created, use
the following SQL:
ALTER TABLE Persons
ADD CHECK (P_Id>0)
8/13/2019 Introduction top SQL Syntax
58/63
To allow naming of a CHECK constraint, and for
defining a CHECK constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK (P_Id>0
AND City='Sandnes')
To DROP a CHECK Constraint
8/13/2019 Introduction top SQL Syntax
59/63
To DROP a CHECK Constraint
To drop a CHECK constraint, use the following
SQL:
ALTER TABLE Persons
DROP CONSTRAINT chk_Person
SQL DEFAULT Constraint
8/13/2019 Introduction top SQL Syntax
60/63
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value isspecified.
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" columnwhen the "Persons" table is created:
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),
Address varchar(255),City varchar(255) DEFAULT 'Sandnes')
8/13/2019 Introduction top SQL Syntax
61/63
Default constraint with Functions
The DEFAULT constraint can also be used to insert
system values, by using functions like GETDATE():
CREATE TABLE Orders
(O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
SQL DEFAULT Constraint on ALTER
8/13/2019 Introduction top SQL Syntax
62/63
QTABLE
To create a DEFAULT constraint on the "City"
column when the table is already created, use
the following SQL:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
To DROP a DEFAULT Constraint
8/13/2019 Introduction top SQL Syntax
63/63
To DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the
following SQL:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT