CSU_07314_Lecture_1_Intro_SQL[1]
CSU_07314_Lecture_1_Intro_SQL[1]
ITU07314
DATABASE MANAGEMENT
SYSTEMS
DBMS
2 Logistics
Instructor: Siphy, A. S.
email: [email protected]/
[email protected]
29/10/20
Intro to SQL,
24
3 Course Overview
Description of the Course
Assignments & projects
Readings
Grading
Schedules - as per teaching t/t.
29/10/20
Intro to SQL,
24
5 Course Description…
We will focus more on the following
Topics;
Relational schema and data processing
Relational Algebra
SQL overview,
Run Data definition Language (DDL)
Run Data Manipulation language (DML)
Manage schema objects
Manage objects with data dictionary views
Data warehousing and data mining 29/10/20
Intro to SQL,
24
6 Course Description…
Retrieve row and column data from
tables
Advanced SQL commands
Subquery,
Triggers, Sequence, Index, constraints over
multiple relations, Synonym, and so on
Apply DDL and DML to develop and
implement a relational database( in class
projects & assignments)
Transaction processing concepts
Concurrency control techniques 29/10/20
Intro to SQL,
24
7 Assessment
Class Projects
Using a database modeling approach, designing
relational database in a Oracle/ MySQL platform.
Designing, populating, and running queries
against your own personal database in
Oracle/MySQL.
Types of database projects
Individual
Lab projects –weekly basis
Group
Min projects – Case studies and scenarios about
database design -to be done in Oracle/MySQL
Database. Min-project will be issued weekly
29/10/20
Intro to SQL,
24
8 Grading
Continuous assessments
Comprehensive Test
Several Lab tests,
projects, and
assignments,
Shall be no special CW - 40%
test/make-up Final Exam -60%
test/projects/assign.
29/10/20
Intro to SQL,
24
Class Etiquette
Mandatory Attendance: Regular class
attendance and active participation are
essential for success in this course and are
expected from all students. Attendance and
participation will be recorded.
Consequences for Absences: Multiple
absences may lead to a 10% reduction in
the final coursework
No Cell Phones: Please switch off or
silence your cell phones to minimize
disruptions.
Shall be no special test/make-up
test/projects/assign
10 Readings
Thomas M. Connolly and Carolyn E. Begg (2009),
Database System: A Practical Approach to Design,
Implementation, and Management, 5rd Edition,
Addison-Wesley, Harlow England.
Mark Gillenson (2011), Fundamentals of Database
Management Systems, 2nd Edition, Wiley
Carlos Coronel, Steven Morris and Peter Rob (2012),
Database Systems: Design, Implementation and
Management, 10th Edition, Cengage Learning.
29/10/20
Intro to SQL,
24
Overview
11
Introduction to SQL
The SQL language overview
SQL, the relational model, and E/R diagrams
SQL categories (DDL, DML)
Data types
Column constraints
DDL commands
29/10/20
24
Intro to SQL,
12 SQL Introduction
29/10/20
Intro to SQL,
24
14
SQL
DATA DEFINITION LANGUAGE (DDL)
CREATE
ALTER(ADD/DELETE/MODIFY) Columns/constraints
DROP
RENAME
TRUNCATE
COMMENT
Following lectures...
DATA MANIPULATION LANGUAGE (DML) –next lecture
INSERT
DELETE
UPDATE
SELECT 29/10/20
Intro to SQL,
24
MERGE
15 SQL ..
DATA CONTROL LANGUAGE (DCL)
commands
GRANT
REVOKE
TRANSANCTION CONTROL
LANGAUGE (TCL) commands
COMMIT
ROLLBACK
SAVEPOINT
29/10/20
Intro to SQL,
24
16 Some Facts on SQL
SQL data is case-sensitive, SQL commands are not.
29/10/20
Intro to SQL,
24
17 SQL Environment
Catalog
A set of schemas that constitute the description of a
database
Schema
The structure that contains descriptions of objects created
by a user (base tables, views, constraints)
Data Definition Language (DDL)
Commands that define a database, including creating,
altering, and dropping tables and establishing constraints
Data Manipulation Language (DML)
Commands that maintain and query a database
Data Control Language (DCL)
Commands that control a database, including
administering
Intro to SQL,
privileges and committing data 29/10/20
24
18 SQL Environment..
29/10/20
Intro to SQL,
24
19 SQL Environment..
29/10/20
Intro to SQL,
24
20 RDBMS –examples
29/10/20
Intro to SQL,
24
21
SQL: DDL Commands
CREATE TABLE: used to create a table.
CREATE VIEW – defines a logical table from one or more views
CREATE SCHEMA – defines a portion of the database owned by a
particular user
29/10/20
Intro to SQL,
24
22 DDL…..
Allows the specification of not only a set of relations but
also information about each relation, including:
The schema for each relation.
The domain of values associated with
each attribute.
Integrity constraints
The set of indices to be maintained for
each relations.
Security and authorization information for
each relation.
The physical storage structure of each
relation on disk.
Intro to SQL,
29/10/20
24
23 Non-Procedural
Programming
SQL is a declarative (non-procedural)
language
Procedural - say exactly what the
computer has to do
Non-procedural – describe the required
result (not the way to compute it)
29/10/20
Intro to SQL,
24
24 SQL, the Relational Model, and
E/R Diagram
SQL is based on the E/R designs can be
relational model implemented in SQL
It has many of the Entities, attributes,
same ideas and relationships can
all be expressed in
Databases that
terms of SQL
support SQL are
often described as Many-to-many
relational databases relationships are a
problem, so should
It is not always true
be removed
to the model
29/10/20
24
Intro to SQL,
25 Relations, Entities, Tables
29/10/20
24
Intro to SQL,
Identify entities and attributes
26
Emp
EmpNo Job
Salary Comm
Dept
Location
Name
DeptNo
29/10/20
Intro to SQL,
24
Identify relationships
27
Managed by
Manage
29/10/20
Intro to SQL,
24
Create a relational schema…
28
FK
Emp (EmpNo, Name, Job, Sal, Comm, HireDate, Mgr, DeptNo)
PK FK
29/10/20
Intro to SQL,
24
29 Tables in SQL Columns
Table name
Product
29/10/20
24
Intro to SQL,
32 Create Table Construct
An SQL relation is defined 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
each Ai is an attribute name in the schema of relation r
Di is the data type of values in the domain of attribute Ai
Example:
CREATE TABLE Student (
SID char(16),
sname varchar(30),
course varchar(4),
Birthdate date
PRIMARY KEY(SID));
29/10/20
Intro to SQL,
24
33 SQL Data types
String types
CHAR(n) – fixed-length character data, ‘n’ characters long Maximum
length = 2000 bytes
VARCHAR2(n) – variable length character data, maximum 4000 bytes
LONG – variable-length character data, up to 4GB. Maximum 1 per
table
Numeric types
NUMBER(p,q) – general purpose numeric data type
NUMBER(p) – signed integer, p digits wide
FLOAT(p) – floating point in scientific notation with p binary digits
precision
INTEGER - signed integer -4 bytes
Date/time type
DATE – fixed-length date/time in dd-mm-yy form
29/10/20
Intro to SQL,
24
34
Date/Time Types in SQL (Cont.)
Date. Dates, containing a (4 digit) year, month and date
E.g. date ‘2014-7-27’
Time. Time of day, in hours, minutes and seconds.
E.g. time ’09:00:30’ time ’09:00:30.75’
Timestamp: date plus time of day
E.g. timestamp ‘2014-7-27 09:00:30.75’
Interval: period of time
E.g. Interval ‘1’ day
Subtracting a date/time/timestamp value from another gives an interval
value
Interval values can be added to date/time/timestamp values
Can extract values of individual fields from date/time/timestamp
E.g. extract (year from r.starttime)
Can cast string types to date/time/timestamp
E.g. cast <string-valued-expression> as date
29/10/20
Intro to SQL,
24
35 Column constraints
NULL or NOT NULL.
If the column must contain a non- null value, the
constraint ‘NOT NULL’ should be put into it.
CHECK
This allows the column value to be checked against a
range or selection of values.
UNIQUE
This allows the column value to be checked against all
other values in that column in the table.
PRIMARY KEY
Makes the columns a SINGLE COLUMN primary key.
This CANNOT be used if there are more than one columns in
the key.{primary key means “NOT NULL”, “UNIQUE”}
REFERENCES – FOREIGN KEY
DEFAULT constraint
AssignsIntroa value to an attribute when a new row is added
to SQL,
29/10/20
24
to a table
36 Primary Keys
29/10/20
24
Intro to SQL,
37 Unique Constraints
29/10/20
Intro to SQL,
24
Relational Data Model
40
29/10/20
Intro to SQL,
24
41 Create PRODUCT table
Non-nullable specification
Primary keys
can never have
NULL values
Identifying primary
key
29/10/20
Intro to SQL,
24
42
Non-nullable specifications
Primary key
29/10/20
Intro to SQL,
24
43 Controlling the values in attributes
Default value
Domain constraint
29/10/20
Intro to SQL,
24
Identifying foreign keys and establishing relationships
44
Primary key of
parent table
Foreign key of
dependent table
29/10/20
Intro to SQL,
24
45 Manipulating the buffer
To terminate an SQL entry, use ;
SQL*Plus commands do not need a semi-colon(;)
Append text or a text adds text to the end of a line.
Change /old/new or C /old/new changes old to new in a line.
Change /text or C /text deletes text from a line.
Clear buffer or cl buff deletes all lines.
Del deletes a line
Get file loads the contents of a file named file into the buffer.
Input or i add one or more lines
Input text adds a line consisting of text.
List or l lists all lines in buffer
List n or l n or n lists one line and makes it the current line.
List * or l * lists the current line
List last or l last lists the last line
List m n or l m n lists lines m through n
Save file or sav file saves the contents of the buffer to a file
named file.
Intro to SQL,
29/10/20
24
46
Data Integrity Controls
Referential integrity – constraint
that ensures that foreign key
values of a table must match
primary key values of a related
table in 1:M relationships
Restricting:
Deletes of primary records
Updates of primary records
Inserts of dependent records
29/10/20
Intro to SQL,
24
47
29/10/20
Intro to SQL,
24
48 SQL and the Data
Dictionary
The data dictionary Some DBMSs let you query
or catalogue stores the catalogue
In Oracle you can access
Information about the metadata in several
database tables ways
Information about There are ‘system tables’
with metadata in them
the columns of tables
You can also DESCRIBE
Other information - tables
users, locks, indexes,
and more
This is ‘metadata’
29/10/20
24
Intro to SQL,
49 Oracle Data Dictionary
To find out what tables and
sequences you have defined use
SELECT table_name
FROM user_tables
The user_tables table is maintained
by Oracle
It has lots of columns, so don’t use
SELECT * FROM user_tables
29/10/20
24
Intro to SQL,
50 Oracle Data Dictionary
To find the details of a table use
DESCRIBE <table name>
Example:
SQL> DESCRIBE Student;
Name Null? Type
------------ -------- ----------
SID NOT NULL NUMBER(16)
SNAME NOT NULL VARCHAR2(30)
COURSE VARCHAR2(4)
BIRTHDATE DATE
29/10/20
24
Intro to SQL,
51 Changing Tables
Sometimes you ALTER TABLE can
want to change the Add a new column
structure of an Remove/drop an
existing table existing column
One way is to DROP Add a new
it then rebuild it constraint
This is dangerous, Remove an
so there is the existing constraint
ALTER TABLE
command instead
29/10/20
24
Intro to SQL,
52 Deleting Tables
NEXT_DAY(date, dayofweek)
Gives the date of the next ‘dayofweek’ after the date
given.
LAST_DAY(date)
Gives the last day of the month in the date specified.
29/10/20
Intro to SQL,
24
59 Formatting the date
TO_CHAR(d,format) returns the date in the format
specified:
MON returns the month in 3-character format
D returns the day number in the week
DD returns the day number in the month
DDD returns the day number in the year
DY gives the weekday in 3-character format
DAY gives the weekday name
Y returns the last digit of the year
Yy returns the last 2 digits of the year
Yyyy returns the 4-digit year
Hh12 returns the hours of the day(1 -12)
Hh24 returns the hours of the day (1 – 24)
Mi returns the minutes of the hour
Ss returns the seconds of the minute
AM returns AM or PM
29/10/20
Intro to SQL,
24
60 And a Few More Relation
Definitions
CREATE TABLE course (
course_id varchar(8),
title varchar(50),
PRIMARY KEY (course_id));
29/10/20
Intro to SQL,
24
62 Values in SQL
SQL is (usually) not case-sensitive, but we’ll write SQL
keywords in upper case for emphasis
STRINGS/TEXTS/DATE & TIME in SQL are surrounded by
single quotes:
'I AM A STRING‘, ’15-JAN-2024’, Etc
The empty string:'‘
NUMERIC-Integer/Decimal/Float in SQL e.g. 123,
123.50,
NULL in SQL -Use NULL if no value is specified
and the column allows it
BOOLEAN -Use values like TRUE or FALSE, or 1
for true and 0 for false, depending on SQL
syntax.
29/10/20
Intro to SQL,
24
Populate relational tables
63 To create a tuple in SQL the following ‘Insert’ command is required:
29/10/20
Intro to SQL,
24
64 Retrieval Queries in SQL
(SELECT Statements)
SQL SELECT Overview
Ai represents an attribute
Ri represents a relation
P is a predicate <condition based on row/s>
The result of an SQL query is a relation.
29/10/20
Intro to SQL,
24
66 The select Clause
The SELECT clause lists the attributes desired in
the result of a query
corresponds to the projection operation of the relational
algebra(after next lecture)
Example: find the names of all students:
SELECT sname
FROM student;
NOTE: SQL names are case insensitive (i.e., you
may use upper- or lower-case letters.)
E.g., SName ≡ SNAME ≡ sname
Some people use upper case wherever we use bold
font.
29/10/20
Intro to SQL,
24
67 The select Clause
(Cont.)
SQL allows duplicates in relations as well as in query
results.
To force the elimination of duplicates, insert the
keyword distinct after select.
Find the names of all students, and remove duplicates
SELECT DISTINCT sname
FROM student;
The keyword all specifies that duplicates should not be
removed.
29/10/20
Intro to SQL,
24
70 The where Clause
The WHERE clause specifies conditions that the result must
satisfy;
Corresponds to the selection predicate of the relational algebra.
To find all students enrolled in BCS
SELECT *
FROM Student
WHERE course= ‘BCS’;
Comparison results can be combined using the logical
connectives AND, OR, and NOT
To find all students enrolled in BCS and were born from
01/01/1990
SELECT *
FROM student
WHERE course = ‘BCS’ AND birthdate>
‘01/01/1990’;
https://www.w3schools.com/sql/default.asp
29/10/20
Intro to SQL,
24