Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views31 pages

SQL5 Efa8040

Uploaded by

Dong Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views31 pages

SQL5 Efa8040

Uploaded by

Dong Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

EFA8040

Data Management and


SQL
SQL, part 5
Markku Kellomäki,
[email protected]
DDL-commands
Data definition language (DDL-commands)
• DDL-commands are used to alter structure of database
• Typical DDL-commands:
• CREATE object type – for example CREATE TABLE, CREATE VIEW
• ALTER object type – for example ALTER TABLE changes structure of a table,
ALTER VIEW changes structure of a view
• DROP object type – for example DROP TABLE removes table, DROP VIEW
drops view
• Notice that delete isn’t same as drop. DELETE FROM table removes data rows, but DROP TABLE
removes whole table
DDL-commands
• Few types of objects in relational databases
• TABLE – all user inputted data is in tables
• VIEW – virtual table based on the result-set of an SQL statement
• INDEX - Indexes are used to retrieve data from the database more
quickly than otherwise
• SEQUENCE – is used to create primary keys
• TRIGGER – activates saved action that is added to specific events
• CONSTRAINT – limitation of table
• DATABASE, SCHEMA, USER, ROLE, FUNCTION, PROCEDURE
CREATE TABLE
• In order to add to a table, the user has to have CREATE TABLE-rights
• Table has to have a name and at least one column. Column has to
have data type and possibly length
• Most common data types:
• CHAR(n) – string, with always size n reserved
• VARCHAR(n) – string, with maximum of n size
• NCHAR, NVARCHAR – like previous with unicode
• INTEGER
• NUMERIC, DECIMAL precise number
• FLOAT, DOUBLE – not so precise numbers
• DATE, TIME, TIMESTAMP
CREATE TABLE
• You can use following constraint in tables:
• PRIMARY KEY - uniquely identifies each record in a table
• FOREIGN KEY - a key used to link two tables together
• DEFAULT - is used to provide a default value for a column
• UNIQUE - ensures that all values in a column are different
• CHECK- is used to limit the value range that can be placed in a column
• NOT NULL - enforces a column to NOT accept NULL values
CREATE TABLE by copying table
• You can create a table by copying table. In copy
• Column names and data types are copied
• Data is copied
• Constraints are not copied
• Example: Create a table capitalists by copying all the rows from person table where city is
Helsinki
CREATE TABLE capitalists
SELECT *
FROM person
WHERE city='HELSINKI';

SELECT * FROM capitalists;


CREATE TABLE by copying table
• EXAMPLE: Hire all the people from Turku, save to new table, set start
date today and increase salary by 1000

CREATE TABLE newperson


SELECT fname AS firstname, lname AS lastname, salary
+ 1000 AS salary, CURDATE() AS hireddate
FROM person WHERE city = 'TURKU';

SELECT * FROM newperson;


CREATE TABLE
• Example: Create customer-table, make a auto incrementable primary
key and test that table:
CREATE TABLE customer(
customerid INTEGER UNSIGNED AUTO_INCREMENT primary KEY,
firstname nvarchar(40) NOT NULL,
lastname nvarchar(40) NOT NULL, birthdate DATE,
creditlimit NUMERIC(7,2) DEFAULT 1000.00);
INSERT INTO customer(firstname, lastname, birthdate,
creditlimit)
VALUES('Pekka', 'Pouta', '1980-02-03', 4000.00);
INSERT INTO customer(firstname, lastname, birthdate)
VALUES ('Anni', 'Aavikko', '1991-12-24');

SELECT * FROM customer;


SEQUENCE
Sequence is a set of integers 1, 2, 3, … that are generated and
supported by some database systems to produce unique values on
demand.
• A sequence is a user defined schema bound object that generates a
sequence of numeric values.
• Sequences are frequently used in many databases because many
applications require each row in a table to contain a unique value and
sequences provides an easy way to generate them.
• The sequence of numeric values is generated in an ascending or
descending order at defined intervals and can be configured to restart
when it exceeds max_value.
CREATE TABLE, CONSTRAINTS
• Example: create postal table
CREATE TABLE postal (postalcode CHAR(5) PRIMARY
KEY, city VARCHAR(40));
• You can create constraint for create table in the end of CREATE TABLE.
If constraint affects more than one column, constraint can be used.
Constraint is an object and it has to have name.
CREATE TABLE postal (
postalcode CHAR(5), city
VARCHAR(40),
CONSTRAINT PRIMARY KEY(postalcode));
ALTER TABLE, columns, constraints
• Example: create a new column postalnumber to customer table and
constraint it to postal table
ALTER TABLE customer
ADD COLUMN postalnumber CHAR(5);

SELECT * FROM customer;

ALTER TABLE customer


ADD CONSTRAINT cfk1 FOREIGN KEY(postalnumber)
REFERENCES postal(postalcode)
ON UPDATE CASCADE;
ALTER TABLE, constraints
• Example: create a constraint on customer table, that allows credit
limit to be full tens, e.g., 1010.00 is OK but 1011.00 is not OK

ALTER TABLE customer


ADD CONSTRAINT customer_chk CHECK(creditlimit % 10 =
0);
• For example this insert will violate customer_chk:
INSERT INTO customer(firstname, lastname,
birthdate, creditlimit)
VALUES ('Matti', 'Pouta', '1989-02-03',
4201.00);
ALTER TABLE, constraints
• Example: Add postal numbers on postal table and try to add foreign
key value to customer table
INSERT INTO postal VALUES ('00001', 'HELSINKI'),
('70700', 'KUOPIO');
UPDATE customer SET postalnumber='00001'
WHERE firstname ='Anni';
SELECT * FROM customer;

UPDATE customer SET postalnumber='88888'


WHERE firstname='Pekka'; -- Does not work - why?
SELECT * FROM customer;
DROP TABLE
• DROP TABLE removes table and its data
• You can’t remove table that has constraints from another table
• Example: remove table newperson:
DROP TABLE newperson;
• Example: remove table postal:
DROP TABLE postal; -- ERROR
VIEW
• A view is a virtual table based on the result-set of an SQL statement.
• When user fetches data from view, database executes view-query
• View doesn’t save data
• If view is based on single table and query is simple enough, database can
allow saving via view to the table
• Views are used to
• Create easy ”interface” for complex queries
• Hide information by showing only specific data. Access is granted only by view
instead of table
• Produce reports
VIEW
• Example: create a view which lists all persons from all projects
CREATE VIEW hourlist AS
SELECT pr.pid, pr.pname, p.lname, p.fname, pp.hours,
pp.hours_planned
FROM person p JOIN proj_pers pp
ON p.socsecno = pp.socsecno
JOIN project pr
ON pp.pid = pr.pid
ORDER BY pr.pname, p.fname;

SELECT * FROM hourlist;


INDEX
• The CREATE INDEX statement is used to create indexes in tables.
• Indexes are used to retrieve data from the database more quickly
than otherwise. The users cannot see the indexes, they are just used
to speed up searches/queries.
• One table can have multiple indexes
• Index can be defined by chosen columns. Index saves column
information and reference to specific rows
INDEX
• Example: create index for person table for combination of last and
first names
CREATE INDEX person_idx4 ON person(lname, fname);
• Check if queries use previous index:
CREATE INDEX person_idx4 ON person(lname, fname);

EXPLAIN SELECT *
FROM person WHERE lname='Meri' AND fname= 'Leo';

EXPLAIN SELECT *
FROM person WHERE salary=2800; -- this one should not
use index
UNIQUE
• UNIQUE constraint ensures that all values in a column are
different.
• Both UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint.
• However, you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
• You can create either UNIQUE CONSTRAINT –object or UNIQUE
INDEX-object
UNIQUE
ALTER TABLE PROJECT ADD CONSTRAINT project_uq1
UNIQUE (pname);
CREATE UNIQUE INDEX person_idx5 ON
person(lname);
INSERT INTO project(pid, pname)
VALUES('P7','BILLING');
INSERT INTO person(socsecno, fname, lname)
VALUES('8888','Ville','Meri'); -- error -
duplicate last name
DML-commands
Data Manipulation Language(DML)
• DML-commands are INSERT, UPDATE AND DELETE commands that
modify table data
• INSERT –adds rows to table
• UPDATE – modifies data in table
• DELETE – removes data from table

• TRUNCATE removes table rows without logging anything, it’s not a


DML-command
TRANSACTIONS
• TRANSACTION = a group of DML commands, that are grouped so that the are
either
• Approved or
• Disapproved all at once
• Incomplete transactions are not permanently saved, only the user can see
changes.
• Only accepting transactions alters tables permanently and makes the changes
visible for others
TRANSACTIONS
• TRANSACTION starts with
• START TRANSACTION command
• BEGIN command
• Where previous transaction ends
• If there’s autocommit on, each DML command forms transaction. Set autocommit=1 (on)/ 0(off)
• Disapproved all at once
• Transaction ends on
• COMMIT –transaction approved
• ROLLBACK – transaction disapproved
• DDL-command, (CREATE, ALTER, DROP) causes COMMIT
• DML-command, causes COMMIT if autocommit is on
• Forced ending of the session => causes rollback
INSERT
• INSERT adds rows to table
• INSERT INTO table VALUES(); --adds data to all columns
• INSERT INTO table(columns) values(); --adds data only to spesific columns
• For data to be added use '' for strings, numerals don’t need it
Examples:
• First let’s remove autocommit:
SET AUTOCOMMIT = 0;
-add new project
START TRANSACTION;
INSERT INTO project(pid, pname, priorit, location)
VALUES('P8', 'TESTING', 3, 'KUOPIO');
INSERT
• If columns are dropped from listing, all the tables in columns has to
have values
INSERT INTO project
VALUES('P12', 'GAME DEV', NULL, 'TAMPERE');
• Some databases allow adding multiple rows with same query
INSERT INTO project
VALUES('P14','Hunger',2,'TURKU'), ('P15',
'Gamefying',4,'HELSINKI');
Let’s see what has been added and then rollback changes
SELECT * FROM project;
ROLLBACK;
UPDATE
• UPDATE updates rows of tables
• Notice that WHERE clause is usually mandatory for UPDATE AND
DELETE clauses, because change affects whole table
• Example: Change projects from Kuopio to Helsinki and set priority 1
UPDATE project
SET location= 'HELSINKI', priorit = 1
WHERE location = 'KUOPIO';
DELETE
• DELETE removes rows from table
• Notice that where clause is usually mandatory for UPDATE AND
DELETE clauses, because change effects whole table
• Example: remove all projects with pid >= P6
DELETE FROM project WHERE pid >= 'P6';
SELECT * FROM project;

• What about projects P10 and P11?


TRUNCATE
• TRUNCATE table; --removes all rows from table
• DELETE from table; --also removes all rows of table
• TRUNCATE is not transactionable command, but delete is
• TRUNCATE is faster because you don’t neet to save undo buffers
• You can’t bring back rows removed with truncate
Subqueries in INSERT, UPDATE and DELETE
• You can use subqueries in DML-commands
• Example: Create table of cities and save every city there
CREATE TABLE cities
SELECT DISTINCT city FROM person;

INSERT INTO cities SELECT DISTINCT(location)


FROM project;

SELECT * FROM cities;

You might also like