SlideShare a Scribd company logo
Different kind of DBMS
• Hierarchical DBMS, 60s
• Relation DBMS, RDBMS, 70s
• Object DBMS, 80s
• Object-relational DBMS, 90s
• Most databases today are RDBMS or Object-
relational DBMS
Relational Database Systems
• Started in the 70s at IBM by Cod
• Several implementations by companies like Oracle,
Sybase, Upright and Microsoft
• Highly optimized systems
• Proven and mature technology
• Several international standards
• Most systems today uses a RDBMS
Purpose
• Make storing of data and accessing of data easy
• RDBMS
• Roles: Admin, Developer, Architect
• Databases: Oracle, SQL Server, DB2, MySQL,
Postgres, SQLite
CODD’S RULE
• Each cell should have only one data: each data should be accessible
• Data shouldn’t be duplicated: Edit/delete is difficult because you
don’t know how many/where all the data are. Duplicate occupies
space
TYPES OF DATABASES ON PURPOSE
• OLTP: Online Transaction Processing – manage your day to day
business. Bulk of the operations here is CUD (Create, Update,
Delete), Less of Read
• OLAP: Online Analytical Processing – Almost all the operation
here is READ
DATABASE SERVER
DB1
DB2 DB2
Connecting to a DB:
1. Hostname [IPAddress]
2. Database name
3. Username
4. Password
User Management:
1. Admin
2. Multiple users with different
roles and permission
Developer Role
DB1
C: Create data: INSERT
R: Read Data: SELECT
U: Update the data: UPDATE
D: Delete existing data: DELETE
Architect Role
DB1
How many tables?
What kind of data they will have?
How many columns you need?
What should be the data type of each column?
Do we require to add any constraints?
EMPID ENAME EMAILID PHONENO
Integer Varchar(40) VARCHAR(30) CHAR(11)
..
Rohit Sharma
Table Name: EMPLOYEES
Datatypes:
1. Integer
2. Real
3. Date
4. Text /Char
Datatypes in MYSQL: https://www.w3schools.com/mysql/mysql_datatypes.asp
Relationships in Database
• 1: 1 – One attribute belongs only one other attribute, Email ID & Phone
Number
– Put all these attributes in same table
• 1: Many / Many to 1 – One attribute can have multiple other attribute,
Employee to Department
– Create 2 tables and Join them using Foreign Key relationship
• Many to Many – multiple values, Students and Subjects
– Create 3 tables, 1 each for 2 attributes and 3rd table for the relationship
EMPID ENAME EMAILID PHONENO DID
Integer Varchar(40) VARCHAR(30) CHAR(11)
101 Sachin 1
102 Rohit 3
Table Name: EMPLOYEES
DID DNAME DCODE
1 Sales C105
2 Product Dev
Table Name: DEPARTMENTS
Department 20 cols
# = 10
Dept tab = 200
• Students: DS, ML, PYTHON
• Subjects: DS- 45, ML – 25, Python - 40
ROLLNO STUDENT
2 ROHIT
SUBID SUBNAME FACULTY
1 DS
TID ROLLNO SUBID
1 1 1
2 2 1
3 1 2
E-R Diagram
SUBJECTS
Has
Assignment – Get 5 ER Diagrams
• Airline Pilot Scheduling
• Retail Banking Operation
• ATM Operations
• Library Management Systems
• Hospital Management Systems
• Hotel Management Systems
Pick one of those and
convert into database
object
SELECT THE DATABASE
• MYSQL:
https://dev.mysql.com/downloads/mysql/
• POSTGRES:
https://www.postgresql.org/download/windows/
SERVER
ADMIN TOOL
COMMAND LINE ACCESS
17
Creating the Database
• Following two tasks must be completed:
– Create database structure
– Create tables that will hold end-user data
• More about Databases
19
The Database Schema
• Authentication
– Process through which DBMS verifies that only
registered users are able to access database
– Log on to RDBMS using user ID and password
created by database administrator
• Schema
– Group of database objects—such as tables and
indexes—that are related to each other
20
Data Types
• Data type selection is usually dictated by nature of
data and by intended use
• Pay close attention to expected use of attributes for
sorting and data retrieval purposes
21
Data Types (continued)
22
Creating Table Structures
• Use one line per column (attribute) definition
• Use spaces to line up attribute characteristics and
constraints
• Table and attribute names are capitalized
• NOT NULL specification
• UNIQUE specification
23
Creating Table Structures (continued)
• Primary key attributes contain both a NOT NULL and
a UNIQUE specification
• RDBMS will automatically enforce referential
integrity for foreign keys
• Command sequence ends with semicolon
24
SQL Constraints
• NOT NULL constraint
– Ensures that column does not accept nulls
• UNIQUE constraint
– Ensures that all values in column are unique
• DEFAULT constraint
– Assigns value to attribute when a new row is added to table
• CHECK constraint
– Validates data when attribute value is entered
25
SQL Indexes
• When primary key is declared, DBMS automatically creates unique
index
• Often need additional indexes
• Using CREATE INDEX command, SQL indexes can be created on
basis of any selected attribute
• Composite index
– Index based on two or more attributes
– Often used to prevent data duplication
26
Data Manipulation Commands
• Adding table rows
• Saving table changes
• Listing table rows
• Updating table rows
• Restoring table contents
• Deleting table rows
• Inserting table rows with a select subquery
27
Adding Table Rows
• INSERT
– Used to enter data into table
– Syntax:
• INSERT INTO columnname
VALUES (value1, value2, … , valuen);
28
Adding Table Rows (continued)
• When entering values, notice that:
– Row contents are entered between parentheses
– Character and date values are entered between apostrophes
– Numerical entries are not enclosed in apostrophes
– Attribute entries are separated by commas
– A value is required for each column
• Use NULL for unknown values
29
Saving Table Changes
• Changes made to table contents are not
physically saved on disk until, one of the
following occurs:
– Database is closed
– Program is closed
– COMMIT command is used
• Syntax:
– COMMIT [WORK];
• Will permanently save any changes made to any
table in the database
30
Listing Table Rows
• SELECT
– Used to list contents of table
– Syntax:
• SELECT columnlist
FROM tablename;
• Columnlist represents one or more
attributes, separated by commas
• Asterisk can be used as wildcard character
to list all attributes
31
Updating Table Rows
• UPDATE
– Modify data in a table
– Syntax:
• UPDATE tablename
SET columnname = expression [, columname = expression]
[WHERE conditionlist];
• If more than one attribute is to be updated in row,
separate corrections with commas
32
Restoring Table Contents
• ROLLBACK
– Used to restore database to its previous
condition
– Only applicable if COMMIT command has not
been used to permanently store changes in
database
• Syntax:
– ROLLBACK;
• COMMIT and ROLLBACK only work with data
manipulation commands that are used to
add, modify, or delete table rows
33
Deleting Table Rows
• DELETE
– Deletes a table row
– Syntax:
• DELETE FROM tablename
[WHERE conditionlist ];
• WHERE condition is optional
• If WHERE condition is not specified, all rows from
specified table will be deleted
34
Inserting Table Rows with a
Select Subquery
• INSERT
– Inserts multiple rows from another table
(source)
– Uses SELECT subquery
• Query that is embedded (or nested) inside
another query
• Executed first
– Syntax:
• INSERT INTO tablename SELECT columnlist
FROM tablename;
35
Selecting Rows with
Conditional Restrictions
• Select partial table contents by placing restrictions on
rows to be included in output
– Add conditional restrictions to SELECT statement,
using WHERE clause
• Syntax:
– SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;
36
Selecting Rows with
Conditional Restrictions (continued)
37
Selecting Rows with
Conditional Restrictions (continued)
38
Arithmetic Operators:
The Rule of Precedence
• Perform operations within parentheses
• Perform power operations
• Perform multiplications and divisions
• Perform additions and subtractions
39
Arithmetic Operators:
The Rule of Precedence (continued)
40
Special Operators
• BETWEEN
– Used to check whether attribute value is within a
range
• IS NULL
– Used to check whether attribute value is null
• LIKE
– Used to check whether attribute value matches given
string pattern
41
Special Operators (continued)
• IN
– Used to check whether attribute value matches
any value within a value list
• EXISTS
– Used to check if subquery returns any rows
42
Advanced Data Definition Commands
• All changes in table structure are made by using
ALTER command
– Followed by keyword that produces specific
change
– Following three options are available:
• ADD
• MODIFY
• DROP
43
Changing a Column’s Data Type
• ALTER can be used to change data type
• Some RDBMSs (such as Oracle) do not permit
changes to data types unless column to be changed
is empty
44
Changing a Column’s Data Characteristics
• Use ALTER to change data characteristics
• If column to be changed already contains data,
changes in column’s characteristics are permitted if
those changes do not alter the data type
45
Adding a Column
• Use ALTER to add column
– Do not include the NOT NULL clause for new
column
46
Dropping a Column
• Use ALTER to drop column
– Some RDBMSs impose restrictions on the deletion
of an attribute
47
Advanced Data Updates
48
Copying Parts of Tables
• SQL permits copying contents of selected table
columns so that the data need not be reentered
manually into newly created table(s)
• First create the PART table structure
• Next add rows to new PART table using PRODUCT
table rows
49
Adding Primary and Foreign Key Designations
• When table is copied, integrity rules do not copy, so
primary and foreign keys need to be manually defined on
new table
• User ALTER TABLE command
– Syntax:
• ALTER TABLE tablename ADD
PRIMARY KEY(fieldname);
• For foreign key, use FOREIGN KEY in place of PRIMARY KEY
50
Deleting a Table from the Database
• DROP
– Deletes table from database
– Syntax:
• DROP TABLE tablename;
51
Advanced Select Queries
• SQL provides useful functions that can:
– Count
– Find minimum and maximum values
– Calculate averages
• SQL allows user to limit queries to only those entries
having no duplicates or entries whose duplicates may
be grouped
52
Aggregate Functions
53
Aggregate Functions (continued)
54
Aggregate Functions (continued)
55
Aggregate Functions (continued)
56
Aggregate Functions (continued)
57
Grouping Data
58
Grouping Data (continued)
59
Grouping Data (continued)
60
Virtual Tables: Creating a View
• View is virtual table based on SELECT query
– Can contain columns, computed columns, aliases,
and aggregate functions from one or more tables
• Base tables are tables on which view is based
• Create view by using CREATE VIEW command
61
Virtual Tables: Creating a View
(continued)
62
Joining Database Tables
• Ability to combine (join) tables on common
attributes is most important distinction between
relational database and other databases
• Join is performed when data are retrieved from more
than one table at a time
• Join is generally composed of an equality comparison
between foreign key and primary key of related
tables
63
Joining Tables with an Alias
• Alias can be used to identify source table
• Any legal table name can be used as alias
• Add alias after table name in FROM clause
– FROM tablename alias
64
Summary
• SQL commands can be divided into two overall
categories:
– Data definition language commands
– Data manipulation language commands
• The ANSI standard data types are supported by all
RDBMS vendors in different ways
• Basic data definition commands allow you to create
tables, indexes, and views
65
Summary (continued)
• DML commands allow you to add, modify, and delete rows from tables
• The basic DML commands are SELECT, INSERT, UPDATE, DELETE,
COMMIT, and ROLLBACK
• INSERT command is used to add new rows to tables
• SELECT statement is main data retrieval command in SQL
66
Summary (continued)
• Many SQL constraints can be used with columns
• The column list represents one or more column
names separated by commas
• WHERE clause can be used with SELECT, UPDATE, and
DELETE statements to restrict rows affected by the
DDL command
67
Summary (continued)
• Aggregate functions
– Special functions that perform arithmetic
computations over a set of rows
• ORDER BY clause
– Used to sort output of SELECT statement
– Can sort by one or more columns and use either
an ascending or descending order
• Join output of multiple tables with SELECT statement
68
Summary (continued)
• Natural join uses join condition to match only rows
with equal values in specified columns
• Right outer join and left outer join used to select
rows that have no matching values in other related
table
69
Introduction to SQL
• SQL functions fit into two broad categories:
– Data definition language
• SQL includes commands to:
– Create database objects, such as tables, indexes, and views
– Define access rights to those database objects
– Data manipulation language
• Includes commands to insert, update, delete, and
retrieve data within database tables
The Relational Model
• All data is stored in tables with rows and columns
pnr* name surname sex
1 Fredrik Ålund Male
2 Eva Larsson Female
The Relational Model
• Relations between tables and data
pnr* car
1 Volvo
pnr* name
1 Fredrik
2 Eva
The Relational Model
• Each column contains atomic data
• Views is an alternative view of a table
• Normalization is used to make the data model as flexible
as possible
– No column should depend on any other column in the
row
– No redundant data
– Several levels of normalization and the third normal
form is the most used
Standardized Query Language, SQL
• SQL is a ISO standard supported by basically all
vendors, more or less
• SQL 92, SQL 99 and the new SQL 200x
• SQL is used to create the data model
• SQL is used to query the database
• SQL is used to perform updates
• Powerful language created to manipulate data
74
Objectives
• Explore basic commands and functions of SQL
• How to use SQL for data administration (to create
tables, indexes, and views)
• How to use SQL for data manipulation (to add,
modify, delete, and retrieve data)
• How to use SQL to query a database to extract useful
information
SQL Basics
• Tables can be created with the create command
– C REATE TABLE PERSON(pnr int, namn char(10), surname char(10), sex char(6))
– CREATE TABLE PERSON_CARS(pnr int, car char(7))
• Primary keys are defined in the create statement
– C REATE TABLE PERSON(pnr int, namn char(10), surname char(10), sex char(6),
primary key(pnr))
Online Free Editor for SQL
• https://livesql.oracle.com
• https://www.w3schools.com/sql/trysql.asp?filename
=trysql_op_in
SQL Basics
• Foreign keys can also be defined in the create statement
– CREATE TABLE PERSON_CARS(pnr int, car char(7),
foreign key(pnr) references PERSON(pnr) on delete
cascade)
On Delete Options:
Restrict : Nothing gonna be delete if there is a child row
Cascade : the child row will be delete / update too
Set Null : the child column will be set to null if you delete the parent
No action : The child row will not be concern of the delete / update
SQL Basics
• A column can have restrictions and default values
– CREATE TABLE PERSON(pnr int, name char(10)
default ‘Unknown’, surname char(10), sex char(6)
not null, primary key(pnr))
SQL Basics
• A table can be altered after has been created
– ALTER TABLE PERSON_CARS ADD CONSTRAINT
person_car_pk PRIMARY KEY(pnr, car)
– ALTER TABLE PERSON ADD COLUMN AGE INT
SQL Basics
• Data is retrieved with the SELECT statement
– SELECT * FROM PERSON
– SELECT PNR, NAME FROM PERSON
– SELECT * FROM PERSON WHERE AGE > 25 AND
SEX=‘Male’
• Tables are joined in the SELECT statement
– SELECT PERSON.NAME, PERSON_CARS.CAR FROM
PERSON, PERSON_CARS WHERE PERSON.PNR =
PERSON_CARS.PNR
SQL Basics
• Data is inserted with the INSERT statement
– INSERT INTO PERSON(pnr, name, surname,sex,
age) VALUES(3, ‘Eva’, ‘Larsson’, ‘Female’, ’27’)
– INSERT INTO PERSON_CARS(pnr, car)
VALUES(3,’Toyota’)
SQL Basics
• Data can be update with the UPDATE statements
– UPDATE PERSON SET AGE=22 WHERE PNR=1
• Update Fredriks age to 22
– UPDATE PERSON_CAR SET CAR=‘Volvo’
• Updates all cars to Volvo
SQL Basics
• Data is deleted with the DELETE statement
– DELETE FROM PERSON WHERE ID=3
• Deletes the row with Eva Larsson
SQL Basics
• Views are created with a combination of a CREATE and a
SELECT
– CREATE VIEW VOLVO_OWNERS(pnr, name, surname,
sex, age) as SELECT p.pnr, name, surname, sex, age
FROM PERSON p, PERSON_CARS pc WHERE
pc.pnr=p.pnr AND pc.cars=‘Volvo’
• Only show Volvo users
• SELECT * FROM VOLVO_OWNERS
Advanced SQL
• Stored Procedures
– A precompiled query in the database. Entire systems
can be built with Stored Procedures.
• Triggers
– Certain events can trigger actions, for example a
stored procedure might be started when a row is
deleted
• Both Stored Procedures and Triggers are part of SQL 99
Transactions
• Transactions is the way that the RDBMS keeps the
data consistent
– A transaction is supposed to have the ACID
property
• Atomic
• Consistent
• Isolated
• Durable
Transactions
• The classic example is the cash machine
– If the cash machine gives out the money, but the
reduce balance doesn’t finnish, we have too much
mony
– If the balance is reduced but we don’t get any
money we have too little
Transactions in SQL
• A transaction is started with START
• A transaction is commited with COMMIT
– If ok, everything is secured and well
• A transaction is rolled back (undone) with ROLLBACK
– All operations are undone
89
Introduction to SQL (continued)
90
Introduction to SQL (continued)
91
Introduction to SQL (continued)
• Assignment on SQL Programming
93
The Database Model

More Related Content

PPT
Introduction to Structured Query Language (SQL).ppt
PPT
Introduction to Structured Query Language (SQL) (1).ppt
PPT
Lec 1 = introduction to structured query language (sql)
PPT
15925 structured query
PDF
Intruduction to SQL.Structured Query Language(SQL}
PPT
Introduction to structured query language (sql)
PPT
Introduction to Structured Query Language (SQL).ppt
PPT
Sql server T-sql basics ppt-3
Introduction to Structured Query Language (SQL).ppt
Introduction to Structured Query Language (SQL) (1).ppt
Lec 1 = introduction to structured query language (sql)
15925 structured query
Intruduction to SQL.Structured Query Language(SQL}
Introduction to structured query language (sql)
Introduction to Structured Query Language (SQL).ppt
Sql server T-sql basics ppt-3

Similar to Session 1 - Databases-JUNE 2023.pdf (20)

PPTX
Introduction to structured query language (sql) (1)
PPT
chap 7.ppt(sql).ppt
PPT
SQL Inteoduction to SQL manipulating of data
PPT
Chap 7
PDF
SQL for data scientist And data analysist Advanced
PPTX
SQL Training Centre in Ambala ! Batra Computer Centre
PPT
Chapt7.ppt
PPTX
Database Management Systems and SQL SERVER.pptx
PPTX
Relational Database Management System
PPT
Sql1
PDF
DATA MANAGEMENT computer science class 12 unit - 3 notes.pdf
PDF
MySQL for beginners
PPTX
Database Overview
PPT
Review of SQL
PPTX
PPTX
MS SQL - Database Programming Concepts by RSolutions
PPTX
SQL(database)
PPTX
2018 02 20_biological_databases_part2_v_upload
PDF
PDF
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
Introduction to structured query language (sql) (1)
chap 7.ppt(sql).ppt
SQL Inteoduction to SQL manipulating of data
Chap 7
SQL for data scientist And data analysist Advanced
SQL Training Centre in Ambala ! Batra Computer Centre
Chapt7.ppt
Database Management Systems and SQL SERVER.pptx
Relational Database Management System
Sql1
DATA MANAGEMENT computer science class 12 unit - 3 notes.pdf
MySQL for beginners
Database Overview
Review of SQL
MS SQL - Database Programming Concepts by RSolutions
SQL(database)
2018 02 20_biological_databases_part2_v_upload
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
Ad

Recently uploaded (20)

PDF
servsafecomprehensive-ppt-full-140617222538-phpapp01.pdf
PPTX
DPT-MAY24.pptx for review and ucploading
PDF
MCQ Practice CBT OL Official Language 1.pptx.pdf
PPT
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
PPTX
STS CHAP 4 human development as reflected
PPT
ALLIED MATHEMATICS -I UNIT III MATRICES.ppt
PPT
notes_Lecture2 23l3j2 dfjl dfdlkj d 2.ppt
PPTX
microtomy kkk. presenting to cryst in gl
PPTX
1751884730-Visual Basic -Unitj CS B.pptx
PPTX
The Stock at arrangement the stock and product.pptx
PPTX
The-Scope-of-Food-Quality-and-Safety.pptx managemement
PPTX
Slideham presentation for the students a
PPTX
Principles of Inheritance and variation class 12.pptx
PPTX
Sports and Dance -lesson 3 powerpoint presentation
PPTX
Theory of Change. AFH-FRDP OCEAN ToCpptx
DOCX
mcsp232projectguidelinesjan2023 (1).docx
PPT
NO000387 (1).pptsbsnsnsnsnsnsnsmsnnsnsnsjsnnsnsnsnnsnnansnwjwnshshshs
PPTX
Job-opportunities lecture about it skills
PDF
313302 DBMS UNIT 1 PPT for diploma Computer Eng Unit 2
PDF
Why Today’s Brands Need ORM & SEO Specialists More Than Ever.pdf
servsafecomprehensive-ppt-full-140617222538-phpapp01.pdf
DPT-MAY24.pptx for review and ucploading
MCQ Practice CBT OL Official Language 1.pptx.pdf
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
STS CHAP 4 human development as reflected
ALLIED MATHEMATICS -I UNIT III MATRICES.ppt
notes_Lecture2 23l3j2 dfjl dfdlkj d 2.ppt
microtomy kkk. presenting to cryst in gl
1751884730-Visual Basic -Unitj CS B.pptx
The Stock at arrangement the stock and product.pptx
The-Scope-of-Food-Quality-and-Safety.pptx managemement
Slideham presentation for the students a
Principles of Inheritance and variation class 12.pptx
Sports and Dance -lesson 3 powerpoint presentation
Theory of Change. AFH-FRDP OCEAN ToCpptx
mcsp232projectguidelinesjan2023 (1).docx
NO000387 (1).pptsbsnsnsnsnsnsnsmsnnsnsnsjsnnsnsnsnnsnnansnwjwnshshshs
Job-opportunities lecture about it skills
313302 DBMS UNIT 1 PPT for diploma Computer Eng Unit 2
Why Today’s Brands Need ORM & SEO Specialists More Than Ever.pdf
Ad

Session 1 - Databases-JUNE 2023.pdf

  • 1. Different kind of DBMS • Hierarchical DBMS, 60s • Relation DBMS, RDBMS, 70s • Object DBMS, 80s • Object-relational DBMS, 90s • Most databases today are RDBMS or Object- relational DBMS
  • 2. Relational Database Systems • Started in the 70s at IBM by Cod • Several implementations by companies like Oracle, Sybase, Upright and Microsoft • Highly optimized systems • Proven and mature technology • Several international standards • Most systems today uses a RDBMS
  • 3. Purpose • Make storing of data and accessing of data easy • RDBMS • Roles: Admin, Developer, Architect • Databases: Oracle, SQL Server, DB2, MySQL, Postgres, SQLite
  • 4. CODD’S RULE • Each cell should have only one data: each data should be accessible • Data shouldn’t be duplicated: Edit/delete is difficult because you don’t know how many/where all the data are. Duplicate occupies space
  • 5. TYPES OF DATABASES ON PURPOSE • OLTP: Online Transaction Processing – manage your day to day business. Bulk of the operations here is CUD (Create, Update, Delete), Less of Read • OLAP: Online Analytical Processing – Almost all the operation here is READ
  • 6. DATABASE SERVER DB1 DB2 DB2 Connecting to a DB: 1. Hostname [IPAddress] 2. Database name 3. Username 4. Password User Management: 1. Admin 2. Multiple users with different roles and permission
  • 7. Developer Role DB1 C: Create data: INSERT R: Read Data: SELECT U: Update the data: UPDATE D: Delete existing data: DELETE
  • 8. Architect Role DB1 How many tables? What kind of data they will have? How many columns you need? What should be the data type of each column? Do we require to add any constraints?
  • 9. EMPID ENAME EMAILID PHONENO Integer Varchar(40) VARCHAR(30) CHAR(11) .. Rohit Sharma Table Name: EMPLOYEES Datatypes: 1. Integer 2. Real 3. Date 4. Text /Char Datatypes in MYSQL: https://www.w3schools.com/mysql/mysql_datatypes.asp
  • 10. Relationships in Database • 1: 1 – One attribute belongs only one other attribute, Email ID & Phone Number – Put all these attributes in same table • 1: Many / Many to 1 – One attribute can have multiple other attribute, Employee to Department – Create 2 tables and Join them using Foreign Key relationship • Many to Many – multiple values, Students and Subjects – Create 3 tables, 1 each for 2 attributes and 3rd table for the relationship
  • 11. EMPID ENAME EMAILID PHONENO DID Integer Varchar(40) VARCHAR(30) CHAR(11) 101 Sachin 1 102 Rohit 3 Table Name: EMPLOYEES DID DNAME DCODE 1 Sales C105 2 Product Dev Table Name: DEPARTMENTS Department 20 cols # = 10 Dept tab = 200
  • 12. • Students: DS, ML, PYTHON • Subjects: DS- 45, ML – 25, Python - 40 ROLLNO STUDENT 2 ROHIT SUBID SUBNAME FACULTY 1 DS TID ROLLNO SUBID 1 1 1 2 2 1 3 1 2
  • 14. Assignment – Get 5 ER Diagrams • Airline Pilot Scheduling • Retail Banking Operation • ATM Operations • Library Management Systems • Hospital Management Systems • Hotel Management Systems Pick one of those and convert into database object
  • 15. SELECT THE DATABASE • MYSQL: https://dev.mysql.com/downloads/mysql/ • POSTGRES: https://www.postgresql.org/download/windows/
  • 17. 17 Creating the Database • Following two tasks must be completed: – Create database structure – Create tables that will hold end-user data
  • 18. • More about Databases
  • 19. 19 The Database Schema • Authentication – Process through which DBMS verifies that only registered users are able to access database – Log on to RDBMS using user ID and password created by database administrator • Schema – Group of database objects—such as tables and indexes—that are related to each other
  • 20. 20 Data Types • Data type selection is usually dictated by nature of data and by intended use • Pay close attention to expected use of attributes for sorting and data retrieval purposes
  • 22. 22 Creating Table Structures • Use one line per column (attribute) definition • Use spaces to line up attribute characteristics and constraints • Table and attribute names are capitalized • NOT NULL specification • UNIQUE specification
  • 23. 23 Creating Table Structures (continued) • Primary key attributes contain both a NOT NULL and a UNIQUE specification • RDBMS will automatically enforce referential integrity for foreign keys • Command sequence ends with semicolon
  • 24. 24 SQL Constraints • NOT NULL constraint – Ensures that column does not accept nulls • UNIQUE constraint – Ensures that all values in column are unique • DEFAULT constraint – Assigns value to attribute when a new row is added to table • CHECK constraint – Validates data when attribute value is entered
  • 25. 25 SQL Indexes • When primary key is declared, DBMS automatically creates unique index • Often need additional indexes • Using CREATE INDEX command, SQL indexes can be created on basis of any selected attribute • Composite index – Index based on two or more attributes – Often used to prevent data duplication
  • 26. 26 Data Manipulation Commands • Adding table rows • Saving table changes • Listing table rows • Updating table rows • Restoring table contents • Deleting table rows • Inserting table rows with a select subquery
  • 27. 27 Adding Table Rows • INSERT – Used to enter data into table – Syntax: • INSERT INTO columnname VALUES (value1, value2, … , valuen);
  • 28. 28 Adding Table Rows (continued) • When entering values, notice that: – Row contents are entered between parentheses – Character and date values are entered between apostrophes – Numerical entries are not enclosed in apostrophes – Attribute entries are separated by commas – A value is required for each column • Use NULL for unknown values
  • 29. 29 Saving Table Changes • Changes made to table contents are not physically saved on disk until, one of the following occurs: – Database is closed – Program is closed – COMMIT command is used • Syntax: – COMMIT [WORK]; • Will permanently save any changes made to any table in the database
  • 30. 30 Listing Table Rows • SELECT – Used to list contents of table – Syntax: • SELECT columnlist FROM tablename; • Columnlist represents one or more attributes, separated by commas • Asterisk can be used as wildcard character to list all attributes
  • 31. 31 Updating Table Rows • UPDATE – Modify data in a table – Syntax: • UPDATE tablename SET columnname = expression [, columname = expression] [WHERE conditionlist]; • If more than one attribute is to be updated in row, separate corrections with commas
  • 32. 32 Restoring Table Contents • ROLLBACK – Used to restore database to its previous condition – Only applicable if COMMIT command has not been used to permanently store changes in database • Syntax: – ROLLBACK; • COMMIT and ROLLBACK only work with data manipulation commands that are used to add, modify, or delete table rows
  • 33. 33 Deleting Table Rows • DELETE – Deletes a table row – Syntax: • DELETE FROM tablename [WHERE conditionlist ]; • WHERE condition is optional • If WHERE condition is not specified, all rows from specified table will be deleted
  • 34. 34 Inserting Table Rows with a Select Subquery • INSERT – Inserts multiple rows from another table (source) – Uses SELECT subquery • Query that is embedded (or nested) inside another query • Executed first – Syntax: • INSERT INTO tablename SELECT columnlist FROM tablename;
  • 35. 35 Selecting Rows with Conditional Restrictions • Select partial table contents by placing restrictions on rows to be included in output – Add conditional restrictions to SELECT statement, using WHERE clause • Syntax: – SELECT columnlist FROM tablelist [ WHERE conditionlist ] ;
  • 36. 36 Selecting Rows with Conditional Restrictions (continued)
  • 37. 37 Selecting Rows with Conditional Restrictions (continued)
  • 38. 38 Arithmetic Operators: The Rule of Precedence • Perform operations within parentheses • Perform power operations • Perform multiplications and divisions • Perform additions and subtractions
  • 39. 39 Arithmetic Operators: The Rule of Precedence (continued)
  • 40. 40 Special Operators • BETWEEN – Used to check whether attribute value is within a range • IS NULL – Used to check whether attribute value is null • LIKE – Used to check whether attribute value matches given string pattern
  • 41. 41 Special Operators (continued) • IN – Used to check whether attribute value matches any value within a value list • EXISTS – Used to check if subquery returns any rows
  • 42. 42 Advanced Data Definition Commands • All changes in table structure are made by using ALTER command – Followed by keyword that produces specific change – Following three options are available: • ADD • MODIFY • DROP
  • 43. 43 Changing a Column’s Data Type • ALTER can be used to change data type • Some RDBMSs (such as Oracle) do not permit changes to data types unless column to be changed is empty
  • 44. 44 Changing a Column’s Data Characteristics • Use ALTER to change data characteristics • If column to be changed already contains data, changes in column’s characteristics are permitted if those changes do not alter the data type
  • 45. 45 Adding a Column • Use ALTER to add column – Do not include the NOT NULL clause for new column
  • 46. 46 Dropping a Column • Use ALTER to drop column – Some RDBMSs impose restrictions on the deletion of an attribute
  • 48. 48 Copying Parts of Tables • SQL permits copying contents of selected table columns so that the data need not be reentered manually into newly created table(s) • First create the PART table structure • Next add rows to new PART table using PRODUCT table rows
  • 49. 49 Adding Primary and Foreign Key Designations • When table is copied, integrity rules do not copy, so primary and foreign keys need to be manually defined on new table • User ALTER TABLE command – Syntax: • ALTER TABLE tablename ADD PRIMARY KEY(fieldname); • For foreign key, use FOREIGN KEY in place of PRIMARY KEY
  • 50. 50 Deleting a Table from the Database • DROP – Deletes table from database – Syntax: • DROP TABLE tablename;
  • 51. 51 Advanced Select Queries • SQL provides useful functions that can: – Count – Find minimum and maximum values – Calculate averages • SQL allows user to limit queries to only those entries having no duplicates or entries whose duplicates may be grouped
  • 60. 60 Virtual Tables: Creating a View • View is virtual table based on SELECT query – Can contain columns, computed columns, aliases, and aggregate functions from one or more tables • Base tables are tables on which view is based • Create view by using CREATE VIEW command
  • 61. 61 Virtual Tables: Creating a View (continued)
  • 62. 62 Joining Database Tables • Ability to combine (join) tables on common attributes is most important distinction between relational database and other databases • Join is performed when data are retrieved from more than one table at a time • Join is generally composed of an equality comparison between foreign key and primary key of related tables
  • 63. 63 Joining Tables with an Alias • Alias can be used to identify source table • Any legal table name can be used as alias • Add alias after table name in FROM clause – FROM tablename alias
  • 64. 64 Summary • SQL commands can be divided into two overall categories: – Data definition language commands – Data manipulation language commands • The ANSI standard data types are supported by all RDBMS vendors in different ways • Basic data definition commands allow you to create tables, indexes, and views
  • 65. 65 Summary (continued) • DML commands allow you to add, modify, and delete rows from tables • The basic DML commands are SELECT, INSERT, UPDATE, DELETE, COMMIT, and ROLLBACK • INSERT command is used to add new rows to tables • SELECT statement is main data retrieval command in SQL
  • 66. 66 Summary (continued) • Many SQL constraints can be used with columns • The column list represents one or more column names separated by commas • WHERE clause can be used with SELECT, UPDATE, and DELETE statements to restrict rows affected by the DDL command
  • 67. 67 Summary (continued) • Aggregate functions – Special functions that perform arithmetic computations over a set of rows • ORDER BY clause – Used to sort output of SELECT statement – Can sort by one or more columns and use either an ascending or descending order • Join output of multiple tables with SELECT statement
  • 68. 68 Summary (continued) • Natural join uses join condition to match only rows with equal values in specified columns • Right outer join and left outer join used to select rows that have no matching values in other related table
  • 69. 69 Introduction to SQL • SQL functions fit into two broad categories: – Data definition language • SQL includes commands to: – Create database objects, such as tables, indexes, and views – Define access rights to those database objects – Data manipulation language • Includes commands to insert, update, delete, and retrieve data within database tables
  • 70. The Relational Model • All data is stored in tables with rows and columns pnr* name surname sex 1 Fredrik Ålund Male 2 Eva Larsson Female
  • 71. The Relational Model • Relations between tables and data pnr* car 1 Volvo pnr* name 1 Fredrik 2 Eva
  • 72. The Relational Model • Each column contains atomic data • Views is an alternative view of a table • Normalization is used to make the data model as flexible as possible – No column should depend on any other column in the row – No redundant data – Several levels of normalization and the third normal form is the most used
  • 73. Standardized Query Language, SQL • SQL is a ISO standard supported by basically all vendors, more or less • SQL 92, SQL 99 and the new SQL 200x • SQL is used to create the data model • SQL is used to query the database • SQL is used to perform updates • Powerful language created to manipulate data
  • 74. 74 Objectives • Explore basic commands and functions of SQL • How to use SQL for data administration (to create tables, indexes, and views) • How to use SQL for data manipulation (to add, modify, delete, and retrieve data) • How to use SQL to query a database to extract useful information
  • 75. SQL Basics • Tables can be created with the create command – C REATE TABLE PERSON(pnr int, namn char(10), surname char(10), sex char(6)) – CREATE TABLE PERSON_CARS(pnr int, car char(7)) • Primary keys are defined in the create statement – C REATE TABLE PERSON(pnr int, namn char(10), surname char(10), sex char(6), primary key(pnr))
  • 76. Online Free Editor for SQL • https://livesql.oracle.com • https://www.w3schools.com/sql/trysql.asp?filename =trysql_op_in
  • 77. SQL Basics • Foreign keys can also be defined in the create statement – CREATE TABLE PERSON_CARS(pnr int, car char(7), foreign key(pnr) references PERSON(pnr) on delete cascade) On Delete Options: Restrict : Nothing gonna be delete if there is a child row Cascade : the child row will be delete / update too Set Null : the child column will be set to null if you delete the parent No action : The child row will not be concern of the delete / update
  • 78. SQL Basics • A column can have restrictions and default values – CREATE TABLE PERSON(pnr int, name char(10) default ‘Unknown’, surname char(10), sex char(6) not null, primary key(pnr))
  • 79. SQL Basics • A table can be altered after has been created – ALTER TABLE PERSON_CARS ADD CONSTRAINT person_car_pk PRIMARY KEY(pnr, car) – ALTER TABLE PERSON ADD COLUMN AGE INT
  • 80. SQL Basics • Data is retrieved with the SELECT statement – SELECT * FROM PERSON – SELECT PNR, NAME FROM PERSON – SELECT * FROM PERSON WHERE AGE > 25 AND SEX=‘Male’ • Tables are joined in the SELECT statement – SELECT PERSON.NAME, PERSON_CARS.CAR FROM PERSON, PERSON_CARS WHERE PERSON.PNR = PERSON_CARS.PNR
  • 81. SQL Basics • Data is inserted with the INSERT statement – INSERT INTO PERSON(pnr, name, surname,sex, age) VALUES(3, ‘Eva’, ‘Larsson’, ‘Female’, ’27’) – INSERT INTO PERSON_CARS(pnr, car) VALUES(3,’Toyota’)
  • 82. SQL Basics • Data can be update with the UPDATE statements – UPDATE PERSON SET AGE=22 WHERE PNR=1 • Update Fredriks age to 22 – UPDATE PERSON_CAR SET CAR=‘Volvo’ • Updates all cars to Volvo
  • 83. SQL Basics • Data is deleted with the DELETE statement – DELETE FROM PERSON WHERE ID=3 • Deletes the row with Eva Larsson
  • 84. SQL Basics • Views are created with a combination of a CREATE and a SELECT – CREATE VIEW VOLVO_OWNERS(pnr, name, surname, sex, age) as SELECT p.pnr, name, surname, sex, age FROM PERSON p, PERSON_CARS pc WHERE pc.pnr=p.pnr AND pc.cars=‘Volvo’ • Only show Volvo users • SELECT * FROM VOLVO_OWNERS
  • 85. Advanced SQL • Stored Procedures – A precompiled query in the database. Entire systems can be built with Stored Procedures. • Triggers – Certain events can trigger actions, for example a stored procedure might be started when a row is deleted • Both Stored Procedures and Triggers are part of SQL 99
  • 86. Transactions • Transactions is the way that the RDBMS keeps the data consistent – A transaction is supposed to have the ACID property • Atomic • Consistent • Isolated • Durable
  • 87. Transactions • The classic example is the cash machine – If the cash machine gives out the money, but the reduce balance doesn’t finnish, we have too much mony – If the balance is reduced but we don’t get any money we have too little
  • 88. Transactions in SQL • A transaction is started with START • A transaction is commited with COMMIT – If ok, everything is secured and well • A transaction is rolled back (undone) with ROLLBACK – All operations are undone
  • 89. 89 Introduction to SQL (continued)
  • 90. 90 Introduction to SQL (continued)
  • 91. 91 Introduction to SQL (continued)
  • 92. • Assignment on SQL Programming