Database Construction and Usage

Slides:



Advertisements
Similar presentations
IS698: Database Management Min Song IS NJIT. The Relational Data Model.
Advertisements

Database Design -- Basic SQL
1 Lecture 11: Basic SQL, Integrity constraints
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Introduction to Structured Query Language (SQL)
SQL components In Oracle. SQL in Oracle SQL is made up of 4 components: –DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE. Creates / Alters.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
Database Systems Lecture 5 Natasha Alechina
Oracle Data Definition Language (DDL)
SQL Overview Defining a Schema CPSC 315 – Programming Studio Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch Via Yoonsuck Choe.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
1 The Relational Model Instructor: Mohamed Eltabakh
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
1 Database Systems Defining Database Schema Views.
CSE314 Database Systems Lecture 3 The Relational Data Model and Relational Database Constraints Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
CPSC-310 Database Systems
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
Managing Tables, Data Integrity, Constraints by Adrienne Watt
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
CS 480: Database Systems Lecture 13 February 13,2013.
Foreign Keys Local and Global Constraints Triggers
Applied CyberInfrastructure Concepts Fall 2017
Quiz Questions Q.1 An entity set that does not have sufficient attributes to form a primary key is a (A) strong entity set. (B) weak entity set. (C) simple.
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Database Construction (and Usage)
Designing Tables for a Database System
CPSC-608 Database Systems
Relational Algebra Chapter 4, Part A
Relational Algebra 461 The slides for this text are organized into chapters. This lecture covers relational algebra, from Chapter 4. The relational calculus.
CPSC-310 Database Systems
Instructor: Mohamed Eltabakh
Relational Databases The Relational Model.
Relational Databases The Relational Model.
CS4222 Principles of Database System
LECTURE 3: Relational Algebra
SQL OVERVIEW DEFINING A SCHEMA
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL data definition using Oracle
SQL: The Query Language Part 1
CMPT 354: Database System I
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Contents Preface I Introduction Lesson Objectives I-2
Chapter 2: Creating And Modifying Database Tables
CSC 453 Database Systems Lecture
Instructor: Mohamed Eltabakh
Structured Query Language – The Basics
SQL: Structured Query Language
SQL – Constraints & Triggers
CPSC-608 Database Systems
CS3220 Web and Internet Programming SQL and MySQL
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Presentation transcript:

Database Construction and Usage Lecture 5 Database Construction and Usage SQL DDL and DML Relational Algebra

Announcement Attributes on ER relationships are allowed But boolean “flag” attributes are discouraged Sign up to the Google Group for updates! https://groups.google.com/forum/#!forum/tda357-ht2016 Fill in the doodles No-one signed up == no TA attending More rooms are added if needed

Example Room A Room B Alice Bob Charlie 3 Alice, Bob and Charlie signed up for room A No-one signed up for room B In this case, there will be NO teaching assistant in room B!!

Course Objectives Design Construction Usage Interfacing

Connecting to PostgreSQL Chalmers postgresql server (check Fire for your credentials): psql -h ate.ita.chalmers.se -U <username> <dbname> Local postgresql server: psql <dbname> Semicolon and postgres prompt: steven=> select 1+1 steven-> ; Lines should end with ‘;’, otherwise statements are continued on the next line. Note the prompt change!

Case convention SQL is completely case insensitive. Upper-case or Lower-case makes no difference. We will use case in the following way: UPPERCASE marks keywords of the SQL language. lowercase marks the name of an attribute. Capitalized marks the name of a table.

SQL Data Definition Language

Working example Person Course GivenCourse Person(ssn, name) Teaches Course code period studentcount Of GivenCourse >= 0 1,2,3,4 Person(ssn, name) Course(code, name) GivenCourse(code, period, studentcount, teacher) code -> Course.code teacher -> Person.ssn

Creating and dropping tables Relations become tables, attributes become columns. CREATE TABLE Tablename ( <list of table elements> ); Get all info about a created table: \d+ Tablename; PostgreSQL specific! Remove a created table: DROP TABLE Tablename;

Table declaration elements The basic elements are pairs consisting of a column name and a type. Most common SQL types: INT or INTEGER (synonyms) REAL or FLOAT (synonyms) CHAR(n) = fixed-size string of size n. VARCHAR(n) = variable-size string of up to size n. TEXT = string of unrestricted length

NULL is allowed by default! Example Example: CREATE TABLE Courses ( code CHAR(6), name TEXT NOT NULL ); NULL is allowed by default! Created the table courses: code name

Declaring keys An attribute or a list of attributes can be declared PRIMARY KEY or UNIQUE PRIMARY KEY: (At most) One per table, never NULL. Efficient lookups in all DBMS. UNIQUE: Any number per table, can be NULL. Could give efficient lookups (may vary in different DBMS). Both declarations state that all other attributes of the table are functionally determined by the given attribute(s). 2011-02-02 (NB): Put parentheses around ”at most”

Example CREATE TABLE Courses( code CHAR(6), name TEXT NOT NULL, PRIMARY KEY (code) );

Foreign keys Referential constraints are handled with references, called foreign keys. FOREIGN KEY attribute REFERENCES table(attribute). FOREIGN KEY course REFERENCES Courses(code) 2007-11-11 (GK): “so called” changed to “called”.

Foreign keys General: FOREIGN KEY course REFERENCES Courses(code) If course is Primary Key in Courses: FOREIGN KEY course REFERENCES Courses Give a name to the foreign key: CONSTRAINT ExistsCourse FOREIGN KEY course REFERENCES Courses

Example CREATE TABLE GivenCourses ( course CHAR(6), period INT, numStudents INT, teacher INT REFERENCES People(ssn) NOT NULL, PRIMARY KEY (course, period), FOREIGN KEY (course) REFERENCES Courses(code) ); 2009-02-01, NB: code => course for consistency

Example CREATE TABLE GivenCourses ( course CHAR(6) REFERENCES Courses, period INT, numStudents INT, teacher INT REFERENCES People(ssn) NOT NULL, PRIMARY KEY (course, period) ); 2009-02-01, NB: code => course for consistency

Value constraints Use CHECK to insert simple value constraints. CHECK (some test on attributes) CHECK (period IN (1,2,3,4))

Example CREATE TABLE GivenCourses ( course CHAR(6) REFERENCES Courses, period INT CHECK (period IN (1,2,3,4)), numStudents INT, teacher INT REFERENCES People(ssn) NOT NULL, PRIMARY KEY (course, period) ); 2009-02-01, NB: code => course for consistency

Example CREATE TABLE GivenCourses ( course CHAR(6) REFERENCES Courses, period INT, numStudents INT, teacher INT REFERENCES People(ssn) NOT NULL, PRIMARY KEY (course, period), CONSTRAINT ValidPeriod CHECK (period in (1,2,3,4)) ); 2009-02-01, NB: code => course for consistency

SQL Data Manipulation Language: Modifications

Inserting data INSERT INTO tablename VALUES (values for attributes); INSERT INTO Courses VALUES (’TDA357’, ’Databases’); code name TDA357 Databases

Example Legal: Not Legal: INSERT INTO GivenCourses VALUES (’TDA357’,2,199,1); Not Legal: INSERT INTO GivenCourses VALUES (’TDA357’,7,199,1); ERROR: new row for relation "givencourses" violates check constraint "givencourses_period_check"DETAIL: Failing row contains (TDA357, 7, 199, 1).

Deletions DELETE FROM tablename WHERE test over rows; DELETE FROM Courses WHERE code = ’TDA357’;

Updates UPDATE tablename SET attribute = ... WHERE test over rows UPDATE GivenCourses SET teacher = ’Graham Kemp’ WHERE course = ’TDA357’ AND period = 2;

Queries: SQL and Relational Algebra

Querying To query the database means asking it for information. ”List all courses that have lectures in room VR” Unlike a modification, a query leaves the database unchanged.

SQL SQL = Structured Query Language Very-high-level language. The querying parts are really the core of SQL. The DDL and DML parts are secondary. Very-high-level language. Specify what information you want, not how to get that information (like you would in e.g. Java). Based on Relational Algebra

”Algebra” An algebra is a mathematical system consisting of: Operands: variables or values to operate on. Operators: symbols denoting functions that operate on variables and values.

Relational Algebra An algebra whose operands are relations (or variables representing relations). Operators representing the most common operations on relations. Selecting rows Projecting columns Composing (joining) relations

Selection Selection = Given a relation (table), choose what tuples (rows) to include in the result. Select the rows from relation T that satisfy condition C. σ = sigma = greek letter s = selection σC(T) SELECT * FROM T WHERE C; 2008-11-10 (GK): “select” changed to “selection” on last line. 31

What? GivenCourses = SELECT * FROM GivenCourses Example: GivenCourses = SELECT * FROM GivenCourses WHERE course = ’TDA357’; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables. What? course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp 32

GivenCourses = SELECT * FROM GivenCourses WHERE course = ’TDA357’; Example: GivenCourses = SELECT * FROM GivenCourses WHERE course = ’TDA357’; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables. course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp 33

Projection Given a relation (table), choose what attributes (columns) to include in the result. Select the rows from table T that satisfy condition C, and project columns X of the result. π = pi = greek letter p = projection πX(σC(T)) SELECT X FROM T WHERE C; 2008-11-10 (GK): “project” changed to “projection” on last line. 34

What? GivenCourses = SELECT course, teacher FROM GivenCourses Example: GivenCourses = SELECT course, teacher FROM GivenCourses WHERE course = ’TDA357’; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables. What? course teacher TDA357 Niklas Broberg Graham Kemp

GivenCourses = SELECT course, teacher FROM GivenCourses Example: GivenCourses = SELECT course, teacher FROM GivenCourses WHERE course = ’TDA357’; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables. course teacher TDA357 Niklas Broberg Graham Kemp

The confusing SELECT What? GivenCourses = SELECT course, teacher Example: GivenCourses = SELECT course, teacher FROM GivenCourses; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi What? course teacher TDA357 Niklas Broberg Graham Kemp TIN090 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables.

The confusing SELECT GivenCourses = SELECT course, teacher Example: GivenCourses = SELECT course, teacher FROM GivenCourses; Result = course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi course teacher TDA357 Niklas Broberg Graham Kemp TIN090 Devdatt Dubhashi 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables. Quiz: SELECT is a projection??

Mystery revealed! SELECT course, teacher FROM GivenCourses; In general, the SELECT clause could be seen as corresponding to projection, and the WHERE clause to selection (don’t confuse the naming though). πcode,teacher(σ(GivenCourses)) = πcode,teacher(GivenCourses) 2009-02-01, NB: code => course for consistency

Quiz! What does the following expression compute? GivenCourses Courses course per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi code name TDA357 Databases TIN090 Algorithms 2009-02-01, NB: Updated data in tables. SELECT * FROM Courses, GivenCourses WHERE teacher = ’Niklas Broberg’;

FROM Courses, GivenCourses code name course per teacher TDA357 Databases 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi Algorithms 2009-02-01, NB: Updated data in tables.

WHERE teacher = ’Niklas Broberg’ code name course per teacher TDA357 Databases 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi Algorithms 2009-02-01, NB: Updated data in tables.

Answer: The result is all rows from Courses combined in all possible ways with all rows from GivenCourses, and then keep only those where the teacher attribute is Niklas Broberg. SELECT * FROM Courses, GivenCourses WHERE teacher = ’Niklas Broberg’; code name course per teacher TDA357 Databases 3 Niklas Broberg TIN090 Algorithms 2007-11-07 (GK): Aligned SQL. 2009-02-01, NB: Updated data in tables.

Cartesian Products σteacher = ’Niklas Broberg’(Courses x GivenCourses) The cartesian product of relations R1 and R2 is all possible combinations of rows from R1 and R2. Written R1 x R2 Also called cross-product, or just product 2007-11-07 (GK): Aligned SQL. SELECT * FROM Courses, GivenCourses WHERE teacher = ’Niklas Broberg’; σteacher = ’Niklas Broberg’(Courses x GivenCourses)

Quiz! List all courses, with names, that Niklas Broberg is responsible for. Courses(code,name) GivenCourses(course,per,teacher) course -> Courses.code SELECT * FROM Courses, GivenCourses WHERE teacher = ’Niklas Broberg’ AND code = course; 2009-02-01, NB: Updated data in tables. code name course per teacher TDA357 Databases 3 Niklas Broberg

code = course code name course per teacher Not equal TDA357 Databases Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi Algorithms 2009-02-01, NB: Updated data in tables. Not equal

Joining relations Very often we want to join two relations on the value of some attributes. Typically we join according to some reference, as in: Special operator ⋈C for joining relations. SELECT * FROM Courses, GivenCourses WHERE code = course; 2007-11-07 (GK): Aligned SQL. R1 ⋈C R2 = σC(R1 x R2) SELECT * FROM R1 JOIN R2 ON C;

Example SELECT * FROM Courses JOIN GivenCourses ON code = course; per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi code name TDA357 Databases TIN090 Algorithms SELECT * FROM Courses JOIN GivenCourses ON code = course; 2009-02-01, NB: Updated data in tables. code name course per teacher TDA357 Databases 3 Niklas Broberg 2 Graham Kemp TIN090 Algorithms 1 Devdatt Dubhashi

Natural join ”Magic” version of join. Join two relations on the condition that all attributes in the two that share the same name should be equal. Remove all duplicate columns Written R1 ⋈ R2 (like join with no condition)

Example SELECT * FROM Courses NATURAL JOIN GivenCourses; code per teacher TDA357 3 Niklas Broberg 2 Graham Kemp TIN090 1 Devdatt Dubhashi code name TDA357 Databases TIN090 Algorithms SELECT * FROM Courses NATURAL JOIN GivenCourses; 2007-11-07 (GK): Aligned SQL. code name per teacher TDA357 Databases 3 Niklas Broberg 2 Graham Kemp TIN090 Algorithms 1 Devdatt Dubhashi

Sets or Bags? Relational algebra formally applies to sets of tuples. SQL, the most important query language for relational databases is actually a bag language. SQL will eliminate duplicates, but usually only if you ask it to do so explicitly. Some operations, like projection, are much more efficient on bags than sets.

Sets or Bags? Algebra A B 1 2 5 6 3 Relational SQL πA(R) A 1 5 A 1 5 R(A,B) A B 1 2 5 6 3 Relational Algebra SQL SELECT A FROM R πA(R) A 1 5 A 1 5 Bag Set (no repeating values)

More Relational Algebra, SQL, Views Next time, Lecture 6 More Relational Algebra, SQL, Views