Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Chapter-6 Add From Handout

The document discusses SQL data definition language (DDL) and data manipulation language (DML) statements. It describes common DDL statements such as CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, and DROP INDEX which are used to define and modify database tables. It also describes DML statements like SELECT, UPDATE, DELETE, and INSERT which are used to manipulate the data within database tables. The document provides examples of how to use these SQL statements.

Uploaded by

Mercy Dega
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter-6 Add From Handout

The document discusses SQL data definition language (DDL) and data manipulation language (DML) statements. It describes common DDL statements such as CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, and DROP INDEX which are used to define and modify database tables. It also describes DML statements like SELECT, UPDATE, DELETE, and INSERT which are used to manipulate the data within database tables. The document provides examples of how to use these SQL statements.

Uploaded by

Mercy Dega
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

CHAPTER -6

SQL DATA DEFINITION


LANGUAGE (DDL)
AND

SQL DATA MANIPULATION


LANGUAGE (DML)
OBJECTIVE
 To understand DDL statements in SQL such
as:
 CREATE TABLE - creates a new database table
 ALTER TABLE - alters (changes) a database table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
 To understand DML statements in SQL such as:
 SELECT - extracts data from a database table
 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database table
1
What and why use SQL?
 SQL allows you to access a database
 SQL is an ANSI standard computer language

 SQL can execute queries against a database

 SQL can retrieve data from a database

 SQL can insert new records in a database

 SQL can delete records from a database

 SQL can update records in a database

 SQL is easy to learn

2
SQL Database Tables
 A database is a collection of related data.
 It can also be viewed as a collection of related tables.
 A table is a set of columns and rows.
 Each column is referred to as a field. Each value in a field represents a
single type of data.
 A database most often contains one or more tables.
 Each table is identified by a name (e.g. "Customers" or "Orders").
 Tables contain records (rows) with data.
 Below is an example of a table called "Persons":

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

 The table above contains three records (one for each person) and four
3
columns (LastName, FirstName, Address, and City).
SQL Data Definition Language (DDL)
 The most important DDL statements in SQL
are:
 CREATE TABLE - creates a new database table
 ALTER TABLE - alters (changes) a database
table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

4
Create a Database
 To create a database:
 CREATE DATABASE database_name;
 Create a Table
 To create a table in a database:
CREATE TABLE table_name
(
column_name1 data_type, column_name2 data_type,.......
);
 Example 1
 This example demonstrates how you can create a
table named "Person", with four columns.
 The column names will be "LastName", "FirstName",
"Address", and "Age":
5
…CON’T
 SQL Query for Example 1 previous
CREATE TABLE Person
(
LastName varchar(30),
FirstName varchar(20),
Address varchar(40),
Age int(3)
);

6
DATA TYPES
 The data type specifies what type of data the column can hold.
 The table below contains the most common data types in SQL:

Data Type Description


integer(size) int(size) Hold integers only. The maximum number of digits are
smallint(size) specified in parenthesis.
tinyint(size)

decimal(size,d) Hold numbers with fractions. The maximum number of


numeric(size,d) digits are specified in "size". The maximum numb er of
digits to the righ t of the decimal is specified in "d".

char(size) Holds a fixed length string (can contain letters, numbers,


and special characters). The fixed size is specified in
parenthesis.
varchar(size) Holds a variable length string (can contain letters
numbers, a nd special characters). The maximum size is
specified in parenthesis.
7
date(yyyymmdd) Holds a date
Create Index
 Indices are created in an existing table to locate rows more quickly
and efficiently.
 It is possible to create an index on one or more columns of a table,
and each index is given a name.
 The users cannot see the indexes; they are just used to speed up
queries.
A Unique Index
 Creates a unique index on a table.
 A unique index means that two rows cannot have the same index
value.
 CREATE UNIQUE INDEX index_name ON table_name
(column_name);
 The "column_name" specifies the column you want indexed.
8
…CON’T
A Simple Index
 Creates a simple index on a table.
 When the UNIQUE keyword is omitted, duplicate values
are allowed.
CREATE INDEX index_name
ON table_name (column_name);
 The "column_name" specifies the column you want indexed.
 Example 1
 This example creates a simple index, named "PersonIndex",
on the LastName field of the Person table:
CREATE INDEX PersonIndex
ON Person (LastName);

9
…CON’T
 If you want to index the values in a column in
descending order, you can add the reserved word
DESC after the column name:
CREATE INDEX PersonIndex
ON Person (LastName DESC);
 If you want to index more than one column you can
list the column names within the parentheses,
separated by commas:
CREATE INDEX PersonIndex
ON Person (LastName, FirstName);

10
Drop Index
 You can delete an existing index in a table with
the DROP statement.
 DROP INDEX table_name.index_name;
Delete a Table or Database
 To delete a table (the table structure, attributes,
and indexes will also be deleted):
 DROP TABLE table_name;
 To delete a database:
 DROP DATABASE database_name;

11
ALTER TABLE
 The ALTER TABLE statement is used to add or drop columns
in an existing table.
ALTER TABLE table_name
ADD column_name datatype;

ALTER TABLE table_name


DROP COLUMN column_name;
 Note: Some database systems don't allow the dropping of a column in
a database table (DROP COLUMN column_name).

12
…CON’T
 Example 1
 To add a column named "City" in the "Person"
table:
ALTER TABLE Person ADD City varchar(30);

Person:

LastName FirstName Address


Pettersen Kari Storgt 20

Result:

LastName FirstName Address City


Pettersen Kari Storgt 20

13
…CON’T
 Example 2
 To drop the "Address" column in the "Person"
table:
ALTER TABLE Person DROP COLUMN Address;

Person:

LastName FirstName Address City


Pettersen Kari Storgt 20

Result:

LastName FirstName City


Pettersen Kari
14
Function Syntax
 The syntax for built-in SQL functions is:
SELECT function(column) FROM table;

 Types of Functions
 There are several basic types and categories of functions in
SQL.
 The basic types of functions are:
Aggregate Functions
 Aggregate functions
 Aggregate functions operate against a collection of values, but
return a single value.
 Note: If used among many other expressions in the item list of
a SELECT statement, the SELECT must have a GROUP BY
15
clause!!

…CON’T
 "Persons" table (used in most examples)
Name Age
Hansen, Ola 34

Svendson, Tove 45

Pettersen, Kari 19

16
AGGREGATE FUNCTIONS IN MS ACCESS
Function Description
AVG(column) Returns the average value of a column

Returns the number of rows (without a NULL value) of a


COUNT(column) column
COUNT(*) Returns the number of selected rows
FIRST(column) Returns the value of the first record in a specified field

LAST(column) Returns the value of the last record in a specified field

MAX(column) Returns the highest value of a column

MIN(column) Returns the lowest value of a column

SUM(column) Returns the total sum of a column 17


SAMPLE DATA FOR AGGREGATE FUNCTION

 Table Name “project”

project_no Emp_no job budget


p1

18
GROUP BY and HAVING
 Aggregate functions (like SUM) often need an added GROUP
BY functionality.
 GROUP BY...
 GROUP BY... was added to SQL because aggregate functions
(like SUM) return the aggregate of all column values every
time they are called, and without the GROUP BY function it
was impossible to find the sum for each individual group of
column values.
 The syntax for the GROUP BY function is:
SELECT column,SUM(column) FROM table GROUP BY
column;

19
…CON’T
 Example 1
 GROUP BY Example This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100

 And This SQL:


Select Company, SUM(Amount) SUM_Amount From Sales group by
Company
 Returns this result:

Company SUM_Amount
W3Schools 17100
IBM 17100
20
W3Schools 17100
…CON’T
 The above code is invalid because the column
returned is not part of an aggregate.
 A GROUP BY clause will solve this problem:
 SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company;
 Returns this result:
Company SUM(Amount)

W3Schools 12600

IBM 4500.

21
HAVING
 HAVING... was added to SQL because the WHERE
keyword could not be used against aggregate
functions (like SUM), and without HAVING... it
would be impossible to test for result conditions.
 The syntax for the HAVING function is:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value;
 This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
22
…CON’T
 This SQL:
SELECT Sum(Company) as SUM_Amount FROM Sales
GROUP BY Company
HAVING SUM(Amount)>10000;

Returns this result

Company SUM(Amount)
W3Schools 12600

23
…CON’T
 AVG Aggregate Function calculates the average
of the values in column
 The argument of the function AVG must be
numeric.
 All Null values are eliminated before the function
AVG is applied
 Syntax

SELECT AVG(COLOMN_NAME) COL_NAME


FROM TABLE_NAME
 Example

Select AVG(budget) avg_budget from project


Where budget >1000 24
…CON’T
 Count aggregate function:
 Has two different forms:
 COUNT([DISTINCT] COL_NAME)
 COUNT(*)

 The first form calculates the number of values in the


col_name column
 When DISTINCT key word is used, all duplicate
values are eliminated before COUNT is applied
 This form of COUNT (DISTINCT) does not count
NULL values for the column.
 Example

Select project_no, COUNT (DISTINCT job)


job_count from project 25

GROUP BY project_no
…CON’T
 To get the number of each job in all projects:

 SELECT job, COUNT(*) job_count


 FROM project
 GROUP BY job

26
STATISTICAL AGGREGATE FUNCTIONS
 The following AF are belongs to the group of
statistical AF
 VAR-computes the variance of all the values
listed in a column or expression.
 VARP computes the variance for the population
of all the values listed in a column or expression.
 STDEV- Computes the standard deviation of all
the values listed in a column or expression
 Is computed as the square root of the corresponding
variance
STDEVP- Computes the standard deviation for the
population of all the values in the column expression
27
THE CREATE VIEW STATEMENT
 In SQL, a VIEW is a virtual table based on the
result-set of a SELECT statement.
 A view contains rows and columns, just like a real
table.
 The fields in a view are fields from one or more real
tables in the database.
 You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the
data were coming from a single table.
 Note: The database design and structure will NOT
be affected by the functions, where, or join
statements in a view.
28

…CON’T
 Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;

 Note: The database does not store the view data!


 The database engine recreates the data, using the view's
SELECT statement, every time a user queries a view.

29
Using Views
 A view could be used from inside a query, a stored
procedure, or from inside another view.
 By adding functions, joins, etc., to a view, it allows you to
present exactly the data you want to the user.
 The sample database Northwind has some views
installed by default.
 The view "Current Product List" lists all active products
(products that are not discontinued) from the Products
table.
 The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
30
WHERE Discontinued=No;
SQL QUICK REFERENCE
Statement Syntax

INSERT INTO INSERT INTO table_name VALUES (value1, value2,....) or

INSERT INTO table_name


(column_name1, column_name2,...)
VALUES (value1, value2,....)

LIKE SELECT column_name(s)


FROM table_name
WHERE column_name
LIKE pattern
ORDER BY SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT SELECT column_name(s) FROM table_name
SELECT * SELECT *
FROM table_name 31
SELECT DISTINCT SELECT DISTINCT column_name(s) FROM table_name
SQL DATA MANIPULATION LANGUAGE (DML)
 Objective:
 • To understand DML statements in SQL
such as:
 SELECT - extracts data from a database table
 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database
table

32
…CON’T
 Below is an example of a table called "Persons":

 The table above contains three records and four


columns (LastName, FirstName, Address, and
City).

33
8.1 SQL QUERIES
 With SQL, we can query a database and have a
result set returned.
 A query like this:

 Gives the result:


LastName
Hansen
Svendson
Pettersen

 Note: Most database systems require a semicolon at


the end of the SQL statement. 34
SELECT Statement
 The SELECT statement is used to select data from a table.
 The tabular result is stored in a result table (called the result-
set).

 Example 1
 Select Some Columns
 To select the columns named "LastName" and "FirstName", use
a SELECT statement like this:

35
…CON’T

 Example 2
 Select All Columns
 To select all columns from the "Persons" table, use a * symbol
instead of column names, like this:

36
The SELECT DISTINCT Statement
 The DISTINCT keyword is used to return only distinct
(different) values.
 The SELECT statement returns information from table
columns.
 But what if we only want to select distinct elements?
 With SQL, all we need to do is to add a DISTINCT keyword to
the SELECT statement:

 Example 1
 Using the DISTINCT keyword
 To select ALL values from the column named "Company" we
use a SELECT statement like this: 37
…CON’T

38
…CON’T
 Example 2
 To select only DIFFERENT values from the
column named "Company" we use a SELECT
DISTINCT statement like this:

39
The WHERE Clause
 To conditionally select data from a table, a WHERE
clause can be added to the SELECT statement.

 With the WHERE clause, the following operators


can be used:

 Note: In some versions of SQL the <> operator may 40


be written as !=
…CON’T
 Example 1
 Using the WHERE Clause
 To select only the persons living in the city "Sandnes", we add a
WHERE clause to the SELECT statement:

41
…CON’T
 Example 2
 Using Quotes
 Note that we have used single quotes around the conditional
values in the examples.
 SQL uses single quotes around text values (most database
systems will also accept double quotes).
 Numeric values should not be enclosed in quotes.
 For text values:

42
The LIKE Condition
 The LIKE condition is used to specify a search for a
pattern in a column.

 A "%" sign can be used to define wildcards (missing letters in


the pattern) both before and after the pattern.
 Example 1
 Using LIKE
 The following SQL statement will return persons with first
names that start with an 'O':

43
…CON’T
 The following SQL statement will return persons
with first names that end with an 'a':

 The following SQL statement will return persons


with first names that contain the pattern 'la':

44
The INSERT INTO Statement
 The INSERT INTO statement is used to insert new rows into a
table.

 You can also specify the columns for which you want to insert
data:

 Example 1
 Insert a New Row, This "Persons" table:

 And this SQL statement:

45
…CON’T
 Example 2
 Insert Data in Specified Columns
 This "Persons" table:

 And This SQL statement:

 Will give this result:

46
THE UPDATE STATEMENT
 The UPDATE statement is used to modify the data in a
table.

 Example 1
 Update one Column in a Row
 This "Persons" table:

 We want to add a first name to the person with a last name


of "Rasmussen

47
…CON’T
 Example 2
 Update several Columns in a Row
 This "Persons" table:

 We want to change the address and add the name of the


city:

48
THE DELETE STATEMENT
 The DELETE statement is used to delete rows in a
table.

 Example 1
 Delete a Row
 This "Persons" table:

 "Nina Rasmussen" is going to be deleted:

49
…CON’T
 Example 2
 Delete All Rows

 It is possible to delete all rows in a table without


deleting the table.
 This means that the table structure, attributes,
and indexes will be intact:

50
Sort the Rows
 The ORDER BY clause is used to sort the rows.
Orders:

 Example 1
 To display the companies in alphabetical order:

 Result:

51
…CON’T
 Example 2
 To display the companies in alphabetical order AND the order
numbers in numerical order:

 Example 3
 To display the companies in reverse alphabetical order:

52
…CON’T
 Example 4
 To display the companies in reverse alphabetical order
AND the
 Order numbers in numerical order:

53
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.

 Example 1
 Use AND to display each person with the first name equal to "Tove",
and the last name equal to "Svendson":

54
…CON’T
 Example 2
 Use OR to display each person with the first name equal to "Tove",
or the last name equal to "Svendson":

 Example 3
 You can also combine AND and OR (use parentheses to form
complex expressions):

55
IN OPERATOR
 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
 To display the persons with LastName equal to "Hansen" or
"Pettersen", use the following SQL:

56
BETWEEN ... AND
 The BETWEEN ... AND operator selects a range of data between
two values.
 These values can be numbers, text, or dates.

 Example 1
 To display the persons alphabetically between (and including)
"Hansen" and exclusive "Pettersen", use the following SQL:

57
…CON’T
 Example 2
 To display the persons outside the range used in the
previous example, use the NOT operator:

58
Joins and Keys
 Sometimes we have to select data from two or more tables to make our
result complete.
 We have to perform a join.
 Tables in a database can be related to each other with keys.
 A primary key is a column with a unique value for each row.
 The purpose is to bind data together, across tables, without repeating all
of the data in every table.
 In the "Employees" table below, the "Employee_ID" column is the primary
key, meaning that no two rows can have the same Employee_ID.
 The Employee_ID distinguishes two persons even if they have the same
name.
 When you look at the example tables below, notice that:
 The "Employee_ID" column is the primary key of the "Employees" Table
 The "Prod_ID" column is the primary key of the "Orders" table
 The "Employee_ID" column in the "Orders" table is used to refer to the persons
in the "Employees" table without using their names
59
THE PRIMARY KEY CLAUSE
 The primary key of a table is a column or group of
columns whose values are different in every row.
 Example1 shows the specification of the primary key for
the Employee table

USE DML;
CREATE TABLE Employees (
Employee_ID INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL
)

60
THE FOREIGN KEY CLAUSE
 A foreign key is a column or group of columns in one table that
contains values that match the primary key values in the same
or another table.
 Each foreign key is defined using the FOREIGN KEY clause
combined with the REFERENCES clause.
 Example shows the specification of the foreign key in the Orders
table of the DML database.
 Example 5.10
USE DML;
CREATE TABLE Orders (
Prod_ID VARCHAR(20) NOT NULL primary key,
Product CHAR(10) NOT NULL,
Employee_ID INTEGER NOT NULL Foreign key
REFERENCES Employees) 61
…CON’T
Employees:

62
REFERRING TO TWO TABLES
 We can select data from two tables by referring to two tables, like
this:
 Example 1
 Who has ordered a product, and what did they order?

 Example 2: Who ordered a printer?

63
Using Joins
 OR we can select data from two tables with the JOIN keyword, like this:
 The INNER JOIN returns all rows from both tables where there is a
match.
 Syntax

 Example INNER JOIN

 If there are rows in Employees that do not have matches in Orders, those
rows will not be listed.

64
…CON’T
 Example LEFT JOIN
 Syntax

 The LEFT JOIN returns all the rows from the first table (Employees),
even if there are no matches in the second table (Orders).
 If there are rows in Employees that do not have matches in Orders,
those rows also will be listed.

65
…CON’T
 Example RIGHT JOIN
 Syntax

 List all orders, and who has ordered - if any.

 The RIGHT JOIN returns all the rows from the second table (Orders),
even if there are no matches in the first table (Employees).
 If there had been any rows in Orders that did not have matches in
Employees, those rows also would have been listed.

66
…CON’T
 Example 1
 Who ordered a printer?

67
UNION
 The UNION command is used to select related information from two
tables, much like the JOIN command.
 when using the UNION command all selected columns need to be of
the same data type.
 Note: With UNION, only distinct values are selected.

68
Using the UNION Command
 Example
 List all different employee names in Norway and USA:

 Note: This command cannot be used to list all employees in


Norway and USA.
 In the example above we have two employees with equal names,
and only one of them is listed.
69
 The UNION command only selects distinct values.
UNION ALL
 The UNION ALL command is equal to the UNION command,
except that UNION ALL selects all values.

 Using the UNION ALL Command


 Example
 List all employees in Norway and USA:

70
- END -

You might also like