structured query language (sql) a2 teacher up skilling lecture 2
TRANSCRIPT
SQL
• SQL: widely used non-procedural language
• Example: Find the name of the customer with customer-id 192-83-
7465
select customer.customer_name
from customer
where customer.customer_id = ‘192-83-7465’
• We will use SQL to:
• Create structure of a database
• Modify structure of a database
• Populate database
• Modify the database
• Query the database
Create Database
To create a database in SQL, you issue the following command to the
DBMS system:
CREATE DATABASE database_name;
For example, to create a database for North Coast Adventures, we would
execute the following statement:
CREATE DATABASE NorthCoastAdventures
Create Table
• Given a set of relations in a database schema, we first need to define
each relation in the database system we have
For example, we want to define the instructor relation,
instructor (ID, name, dept_name, salary), in the university
database
Example:
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references
department(dept_name));
Create Table Construct
• An SQL relation is defined in a database using the create table
command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk));
• r is the name of the relation, e.g., instructor
• Each Ai is an attribute name in the schema of relation r, e.g., ID
• Di is the data type of values in the domain of attribute A – these are
domain types that are either built-in or user defined, e.g., char(5)
• Integrity constraints represent all the additional information about the
relation/its attributes, e.g., primary key (ID)
• create table if not exists instead of create table can also be used
to avoid duplications
Integrity Constraints
• not null – constraint on the value of an attribute
• primary key (A1, ..., An )
• foreign key (Am, ..., An ) references r(Am, ..., An ) - meaning
that the attributes in the currently defined relation are actually used
as the primary key in another relation.
• Example: Declare ID as the primary key for instructor
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references
department(dept_name));
SQL Domain Types
In SQL, there is a number of inbuilt domain types:
• char(n). Fixed length character string, with user-specified length n.
• varchar(n). Variable length character strings, with user-specified
maximum length n.
• int. Integer (a finite subset of the integers that is machine-
dependent).
• numeric(p,d). Fixed point number, with user-specified precision of p
digits (plus a sign), with d of the p digits to the right of decimal point.
• real, double precision. Floating point and double-precision floating
point numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at
least n digits.
SQL Domain Types (cont.)
• date: Dates, containing a (4 digit) year, month and day
Example: date ‘2005-7-27’
• time: Time of day, in hours, minutes and seconds.
Example: time ‘09:00:30’ time ‘09:00:30.75’
• timestamp: date plus time of day
Example: timestamp ‘2005-7-27 09:00:30.75’
Populating a Database
• After a relation is defined, such as instructor (ID, name, dept_name,
salary), We can then populate the created table with data
Example:
insert into instructor values (‘10211’, ’Smith’, ’Biology’,
66000);
insert into instructor values (‘10211’, null, ’Biology’, 66000);
• The value for each attribute in an insert command must be in the
domain of values for that attribute. For example, the value for salary
has to be a numerical value of the format numeric(8,2).
• Each of the insert command can be typed it in a query interface.
Insert Into Construct
• A row can be inserted into a defined table using the insert into
command:
insert into r values (V1, V2, ..., Vn)
• r is the name of the relation
• Each Vi is a value for the corresponding attribute
• Note that the order of the values for the attributes must be the same
as the order of the attributes in the defined relation.
Example:
insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000);
will add a row into the instructor table.
Querying the Database
• A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P;
• Ai in the select clause represents an attribute
• ri in the from clause represents a relation – listing all relations
involved in the query
• P in the where clause is a predicate – describing what conditions the
query results need to satisfy.
• Which attributes/columns do I want to have in the result table (a list of
attributes)? Which relations in the database do these attributes come
from (a list of relations)? What conditions should be applied so that we
only get the values for the attributes in the result table (a logic
expression)?
The select Clause
• The select clause list the attributes you want in the result of a query
• Only the values of the attributes on the list will appear in the result
table
• Example: find the names of all instructors:
select name
from instructor;
• SQL allows duplicates in relations as well as in query results – the
values of the listed attributes in each row in the original table, which
satisfies the conditions specified in the query will appear as a row in
the result table.
The select Clause (cont.)
• To force the elimination of duplicates, insert the keyword distinct after
select.
• Find the names of all departments with instructor, and remove
duplicates
select distinct dept_name from instructor;
• The keyword all specifies that duplicates not be removed.
all is the default option so you don’t need to have it.
select all dept_name from instructor;
The select Clause (cont.)
• An asterisk in the select clause denotes “all attributes”
select *
from instructor;
• The select clause can contain arithmetic expressions involving the
operation, +, –, , and /, and operating on constants or attributes of
tuples.
• The query:
select ID, name, salary/12
from instructor;
would return a relation that is the same as the instructor relation, except
that the value of the attribute salary is divided by 12.
The from Clause
• The from clause lists the relations involved in the query
• More than one relation may be involved because in order to get
the result table, data has to come from several relations.
• The simplest case is to query over one relation only, i.e., having
one relation in the from clause.
select
from instructor, teaches;
The where Clause
• The where clause specifies conditions that a tuple must satisfy in
order for some of its values to appear in the result table.
• To find all instructors in Comp. Sci. department with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000;
• Comparison expressions can be combined using the logical
connectives and, or, and not, so the conditions are expressed as a
logic expression.
• Comparison operators (=, <>, <=, >=, >, <) can be applied to
results of arithmetic expressions, e.g., salary = 80000, salary <>
80000 etc.
Cartesian Product
• Often is it the case that the columns/attributes we want to have in the
result table come from more than one table.
• Cartesian products are represented as a list of relations, separated by
comas, in the from clause
• Cartesian product not very useful directly, but useful combined with
where clause conditions.
• Find the Cartesian product instructor X teaches
select from instructor, teaches;
• Links each tuple in the instructor table with every tuple in the teaches
table to generate every possible instructor – teaches pair, with all
attributes from both relations.
Joins with Basic Query structure
• Joins are needed when we need to combine data from two tables.
• Joins can be achieved in several different ways – this is just one way
Examples
• For all instructors who have taught courses, find their names
and the course ID of the courses they taught.
select name, course_id
from instructor, teaches
where instructor.ID = teaches.ID;
instructor (ID, name, dept_name, salary)
teaches (ID, course_id, sec_id, semester, year)
Joins with Basic Query structure (cont.)• In order to join tuples from two tables in a meaningful way,
appropriate conditions need to be applied
• Find the course ID, semester, year and title of each course offered by
the Comp. Sci. department
select section.course_id, semester, year, title
from section, course
where section.course_id = course.course_id and
dept_name = ‘Comp. Sci.‘;
section (course_id, sec_id, semester, year, building, room_number,
time_slot_id)
course (course_id, title, dept_name, credits)
Make Changes to Database
• The drop table command deletes all information about the dropped
relation from the database.
For instance, drop table instructor;
• The alter table command is used to add attributes to an existing
relation:
• alter table r add A D;
• where A is the name of the attribute to be added to relation r
and D is the domain of A.
• The alter table command can also be used to drop attributes of a
relation:
alter table r drop A;
where A is the name of an attribute of relation r.
For instance, alter table instructor drop first_name;
Make Changes to Database (cont.)• For instance, if you forgot to specify the primary key when you
created the instructor table, you can add it:
alter table instructor PRIMARY KEY (ID);
• If you forgot to index the primary key, you can add it:
alter table instructor index (ID);
• You can add a foreign key, drop a primary key, index, foreign key,
in a similar way.
Make Changes to Database (cont.)• The delete command can be used to delete tuples from a table.
For instance, Delete all instructors from the instructor table.
delete from instructor ;
• In order to delete only those tuples you want, you need to specify
conditions in the where clause.
• For instance, Delete all instructors from the instructor table with the
name ‘Harrison’
delete from instructor where name= ‘Harrison;
Sample Relational Database and SQL Queries
Sample Query #1select customer.customer_namefrom customerwhere customer.customer_id = ‘192-83-7465;’
Sample Query #2
select account.balancefrom depositor, accountwhere depositor.customer_id = ‘192-83-7465’ and depositor.account_number = account.account_number;
3 Relations (Tables):• Customer• Account• Depositor
Reading
Extra Resources
http://www.w3schools.com/sql/
http://www.sqlcourse.com/