CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

Size: px
Start display at page:

Download "CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)"

Transcription

1 CSCU9Q5 Introduction to MySQL Data Definition & Manipulation (Over ~two Lectures) 1

2 Contents Introduction to MySQL Create a table Specify keys and relations Empty and Drop tables 2

3 Introduction SQL is a declarative language for manipulating a relational database Use it to issue commands to the database for tasks such as: Creating and managing tables Inserting data into tables Searching for and retrieving data from tables Deleting data and tables MySQL is a particular version of SQL 3

4 Online Resource Is Oracle s MySQL documentation site note the 5.0 is the version we will use in practicals here. You will need: You will mostly need: Chapter 13: SQL Statement Syntax Chapter 11: Data Types The search facility is awful A better place to learn SQL is: 4

5 Database Engines MySQL supports a number of database engines, each designed for databases with different needs We will use the InnoDB engine as it supports inter-table constraints (Foreign keys) For more on Storage Engines, see: 5

6 Making MySQL Statements We tend to use UPPER CASE for reserved words Strings are enclosed in forward single quotes or double quotes Names of database elements such as tables and fields are enclosed in backwards `quotes` Statements are separated by semi-colons ; E.G SELECT `name` from `mytable` WHERE `name`= John You can drop the use of quotes if it is safe to do so, for example for names with no spaces or special characters. SELECT name from mytable WHERE name= John 6

7 SQL: CREATE TABLE The simplest form of CREATE TABLE looks like this: CREATE TABLE IF NOT EXISTS tablename (colname datatype,... ) CREATE TABLE Staff (Sno INT, Sname CHAR(20), Dept CHAR(20), Grade CHAR(7)) See for full details of CREATE TABLE 7

8 Data Types MySQL is strict about the use of data types. They include: VARCHAR variable length text strings INT integers DECIMAL numbers with decimal places DATE full date TEXT BOOL And others that you can read about here 8

9 Table Constraints The specification of a column can include some extras: default value (used if an insertion doesn't supply a value) and a column constraint (see below) And we can add table constraint(s) before the closing bracket. Both types of constraint are used to protect integrity (next slide) 9

10 SQL: CREATE TABLE: Data Integrity Column constraints: enforcing entity and referential integrity [NOT NULL NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] [PRIMARY] KEY] [COMMENT 'string'] PRIMARY KEY (only one per table) FOREIGN KEY REFERENCES table (column) e.g. CREATE TABLE Staff (Sno INT PRIMARY KEY, Sname VARCHAR(20) NOT NULL, 10

11 SQL: CREATE TABLE: Data Integrity: Foreign Keys The last of these declares a foreign key. CREATE TABLE Staff ( Dept VARCHAR(20) FOREIGN KEY REFERENCES Depts (Dname), Grade VARCHAR(7) FOREIGN KEY REFERENCES Paytable ) The referenced column must be the key of its table We shall not be allowed to insert a row into Staff unless Dept and Grade contains a valid value (one found in the other table) or null we can miss out the bracketed column-name if it is the same in both tables 11

12 SQL: CREATE TABLE: Data integrity (continued): cascaded deletion We can add ON DELETE CASCADE to the REFERENCES part This means that if a row in the other table is deleted, all matching rows in this table should be deleted too For example, the Dependant table in the ER tutorial (for the dependants of employees) might declare the column Enum REFERENCES Employee ON DELETE CASCADE So if we delete employee 123 from the Employee table, then then all his/her dependants are deleted from the Dependant table, thus protecting referential integrity We should only do this for weak entities it would be a disaster if we deleted (say) student records as a result of deleting an Adviser of Studies 12

13 SQL: CREATE TABLE: Data integrity (continued): Deadly Embrace Notice that we cannot declare the Staff table until we have declared Depts and Paytable insert any data into Staff until we have matching data in Depts and Paytable This can form a deadly embrace suppose the Depts table references the Staff table (for Head of Dept, for example) then we cannot declare the Depts table until we have declared Staff ; and we cannot declare the Staff table until we have declared Depts the solution to this problem comes later 13

14 SQL: CREATE TABLE: Data integrity (continued) Table Constraints After the last field, we can add table-constraints these look like column-constraints, but they can reference more than one column CREATE TABLE HTR (Hour char(6), Teacher char(3), Room char(4), PRIMARY KEY (Hour, Teacher)) ; obviously, this is how to declare composite primary keys we can declare (possibly composite) foreign keys in the same sort of way, e.g. the Staff table could be rewritten to put the constraints at the end (next slide): 14

15 SQL: CREATE TABLE: Data Integrity (continued) Table Constraints (Continued) CREATE TABLE Staff (Sno INT PRIMARY KEY, Sname VARCHAR(20) NOT NULL, Dept VARCHAR(20) REFERENCES Depts (Dname), Grade VARCHAR(7) REFERENCES Paytable) ; could be written as CREATE TABLE Staff (Sno INT, Sname VARCHAR(20) NOT NULL, Dept VARCHAR(20), Grade VARCHAR(7), PRIMARY KEY(Sno), CONSTRAINT FOREIGN KEY (Dept) REFERENCES Depts (Dname), CONSTRAINT FOREIGN KEY (Grade) REFERENCES Paytable) 15

16 SQL: ALTERING AN EXISTING TABLE We can change tables, using ALTER TABLE, even after they contain data Amongst other possibilities, we can add or modify columns ALTER TABLE Staff ADD (StreetAddress VARCHAR(20), TownAddress VARCHAR(20)) ; ALTER TABLE Staff MODIFY (TownAddress DEFAULT 'Stirling') ; (we can enter staff before departments, then switch on the constraint) 16

17 SQL: ALTERING TABLE, continued Avoiding Deadly Embrace We can use ALTER TABLE to add a constraint This gets us out of the deadly embrace mentioned earlier CREATE TABLE Dept (Dname VARCHAR(20) PRIMARY KEY, Head INT) ; CREATE TABLE Staff (Sno INT PRIMARY KEY, Sname VARCHAR(20) NOT NULL Dept VARCHAR(20) CONSTRAINT DeptExist REFERENCES Dept (Dname) ALTER TABLE Dept ADD FOREIGN KEY (Head) REFERENCES Staff(Sno) 17

18 Dropping and Deleting We can completely remove a table: both its data (if any) and its definition DROP TABLE tablename ; DROP TABLE tablename CASCADE CONSTRAINTS ; the second form removes Foreign Key constraints in associated tables (which otherwise could not be updated) Removing the data alone (not the definition): DELETE FROM tablename ; DELETE FROM tablename WHERE condition ; we shall deal with conditions later 18

19 Getting data into tables There are two ways of using SQL to get data into tables Firstly, with the values in the SQL statement INSERT INTO Staff VALUES (123,'Lee','CompSci','II.7') ; if we are not loading all the columns, use this form: INSERT INTO Staff (Sno, Sname) VALUES (456, 'Waldenstein') ; Secondly, by extracting the data from existing tables INSERT INTO Loan SELECT DISTINCT Sno, Bno, Date_out FROM Staff_Borrower ; We can also use a bulk-loader utility (PHPMyAdmin has one) 19

20 Getting Even More Data In INSERT INTO `books` (`Name`,`Number`) VALUES ('book1', '1'), ('book2', '2'), ('book3', 3'); See for more details of the INSERT syntax 20

21 Changing Data in a Table Use UPDATE table SET field=value, field=value WHERE condition See for full syntax Next, we will look at manipulating table data Querying a database 21

22 CSC9UQ5 Introduction to MySQL DATA MANIPULATION 22

23 Getting Data From a Database with MySQL The SQL SELECT statement is used to retrieve data from one or more tables in a database It allows you to choose which row and which columns you would like to retrieve and allows joins across several tables. 23

24 Example Tables for This Lecture Books Borrowers Name Number Name Number Dept Book1 1 Anne 1 Maths Book2 2 Bill 2 Maths Book3 3 Claire 3 French Book4 4 Duncan 4 French Book5 5 Edward 5 French Loans BookNumber PersonNumber

25 SELECT From One Table SELECT * FROM Borrowers Shows whole table SELECT Name FROM Borrowers Lists Borrowers names only SELECT Number, Dept FROM Borrowers WHERE Name= Anne Get Anne s number and department 25

26 SELECT and Calculations There are many functions that you can include in a SELECT statement Some simple ones are: SELECT MAX(Number) FROM Borrowers Shows largest borrower number (Min is also available) SELECT Number+1 FROM Borrowers Adds 1 to each borrower number and reports it or even SELECT sin(45) Calculates the sine of 45 no need to reference a table at all 26

27 Joining Tables SELECT borrowers.name, books.name FROM borrowers, books Pairs every borrower with every book Not an awful lot of use Needs to be expanded to be useful 27

28 Looking up a Foreign Key Let s say we want to know who has borrowed Book1 The Loans table has this information, but not in a form that is immediately accessible: BookNumber PersonNumber SELECT Number FROM Books WHERE Name= Book1 Tells us that book1 has the ID number 1 SELECT PersonNumber FROM Loans WHERE BookNumber=1 Tells us that person 2 has the book SELECT Name FROM Borrowers WHERE Number=2 Tells us that person number 2 is Bill, so Bill has Book1 28

29 Put it all Together SELECT Borrowers.Name FROM Borrowers, Books, Loans WHERE Books.name="Book1" AND Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber Returns Bill. Note the use of AND. You can also use OR and NOT. Other useful logic: >, <, <=, >=, =,!= (or <>) When comparing NULL, use IS NULL or IS NOT NULL You can search for partial strings using LIKE: SELECT Name FROM Borrowers WHERE Name LIKE "%e" The % character is a wild card, so above looks for anything ending in e SELECT Name FROM Borrowers WHERE Name LIKE _e" The _ is a single character wild card, so above looks for names with two characters ending in e 29

30 Comparison Examples SELECT * FROM table WHERE x BETWEEN 1 and 3 SELECT * FROM table WHERE x IN ( A, B, C ) SELECT * FROM table WHERE x NOT IN ( A, B, C ) Use brackets to enforce operator order: WHERE (a=1) AND (b=2 OR b=3)!= WHERE (a=1 AND b=2) OR (b=3) Note: Commands and Names (such as table or field names) are not case sensitive: Select = SELECT Table = table String literals may be case sensitive, depending on the collation. _ci at the end of the collation name means case insensitive Force a case sensitive search with SELECT * FROM table WHERE BINARY name="john" 30

31 How to Construct a SELECT Decide what columns you want in your results table: SELECT col1, col2 Then list all the tables involved in the selection (some won t actually provide a field in the select list, but are involved anyway SELECT col1, col2 FROM table1, table2, table3 Then follow the path from what you want to look up to the answer, building x=y statements joined by AND (or OR). SELECT col1, col2 FROM table1, table2, table3 WHERE table1.col1= target AND table2.col1=table1.col1 This is known as performing a Natural Join 31

32 More General Joins If we want to list all the people who have a book, and the books they have: SELECT Borrowers.Name, Books.name FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber Note that SELECT * FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber Is an Equijoin, and lists all the columns from all tables that meet the selection criteria, including them once for each table they appear in. This is not very useful, but shows that everything matches up. 32

33 Inner and Outer Joins We have just seen an inner join. Only rows that meet the criteria completely are returned. Now we look at outer joins where more data is returned about one or more of the fields. Lets say we want to list all of the people in the borrowers database, regardless of whether or not they have a book out. If they do have a book, we want to list that too, otherwise we will just return NULL for people with no current book For this, we need the JOIN command: 33

34 Join Syntax SELECT Borrowers.name, Books.name FROM Borrowers LEFT OUTER JOIN (Books, Loans) ON (Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber) Note the syntax SELECT cols FROM table LEFT OUTER JOIN (table,table) ON (conditions) You can use similar syntax for an inner join: SELECT Borrowers.name, Books.name FROM Borrowers INNER JOIN (Books, Loans) ON (Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber) Is the same as in previous example general join 34

35 A Contrived Example Who has the book with the lowest ID number? SELECT Borrowers.Name FROM Borrowers, Books, Loans WHERE Books.number = (SELECT MIN(number) FROM Books) AND Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber The Answer, as we would expect, is Bill Note the use of brackets to enclose the sub-select and use of the function MIN() 35

36 Groups We may want to summarise the data in the database, and there are some statistical functions available. We have already seen MAX and MIN and there are others: AVG COUNT For example, how many people are there from each department? SELECT Dept, COUNT(Dept) FROM Borrowers GROUP BY Dept 36

37 How Many Books Does Each Department Have? We could show the list and count them ourselves: SELECT Borrowers.Dept FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber But SQL can do it for us: SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber GROUP BY Dept You can select from the resultant table using HAVING SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber GROUP BY Dept HAVING COUNT(Dept) > 2 37

38 Another Example SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans WHERE Books.Number=loans.booknumber AND Borrowers.number=loans.personnumber GROUP BY Dept HAVING COUNT(Dept) = (SELECT MAX(COUNT(Dept))) Selects the department with the most books out and reports how many they have 38

39 Union Allows you to make more than one selection at the same time and put the results together A bit like using OR, but more flexible: SELECT Name FROM Borrowers WHERE Name="Anne" OR Name="Claire Is the same as SELECT Name FROM Borrowers WHERE Name="Anne UNION SELECT Name FROM Borrowers WHERE Name="Claire Which might seem pointless 39

40 Union But it is useful when selecting across more than one table SELECT Name FROM Borrowers UNION SELECT Name FROM Staff Selects the names of all borrowers and all staff Note that there is an Anne in both tables. UNION will only list Anne once. To see duplicate rows, use Staff Name Number Role Anne 1 Manager Fred 2 Engineer George 3 Engineer Harry 4 Engineer UNION ALL 40

41 Selection Manipulation Here are a few things you can do to the selected list: Sort the results by one or more field ORDER BY field, field, [DESC] Force a query to contain unique entries only: SELECT DISTINCT Select a given number of entries starting at a given offset SELECT * FROM table LIMIT(offset,count) 41

42 More on Sub Queries We can use a sub query, as we have already seen, but what happens when the sub query produces more than 1 row? SELECT * FROM staff WHERE Name = ANY (SELECT Name FROM Borrowers) Selects staff whose name appears in both Staff and Borrowers tables SELECT * FROM borrowers WHERE Number > ALL (SELECT Number FROM staff) Selects those borrowers who have a higher number than ALL of the staff 42

43 Aliases You can give an alias to a table or column to make it easier to refer to later in a query or to make it easier to read in the output: SELECT AVG(Number) FROM books shows AVG(Number) 3 SELECT AVG(Number) Average FROM books shows Average 3 43

44 Aliases SELECT Role, COUNT(Role) FROM staff GROUP BY role HAVING COUNT(role) > 1 Can be re-written as SELECT Role, COUNT(Role) count FROM staff GROUP BY role HAVING count > 1 Where count is an alias for COUNT(Role) You can also do this sort of thing: SELECT * FROM Books a, Borrowers b WHERE a.number = b.number We have made aliases for the tables to make reference to them easier 44

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL DDL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Overview Structured Query Language or SQL is the standard query language

More information

1) Introduction to SQL

1) Introduction to SQL 1) Introduction to SQL a) Database language enables users to: i) Create the database and relation structure; ii) Perform insertion, modification and deletion of data from the relationship; and iii) Perform

More information

Database design process

Database design process Database technology Lecture 2: Relational databases and SQL Jose M. Peña jose.m.pena@liu.se Database design process 1 Relational model concepts... Attributes... EMPLOYEE FNAME M LNAME SSN BDATE ADDRESS

More information

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus Lecture #17: MySQL Gets Done

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus  Lecture #17: MySQL Gets Done CSCI-UA:0060-02 Database Design & Web Implementation Professor Evan Sandhaus sandhaus@cs.nyu.edu evan@nytimes.com Lecture #17: MySQL Gets Done Database Design and Web Implementation Database Design and

More information

Overview Relational data model

Overview Relational data model Thanks to José and Vaida for most of the slides. Relational databases and MySQL Juha Takkinen juhta@ida.liu.se Outline 1. Introduction: Relational data model and SQL 2. Creating tables in Mysql 3. Simple

More information

CIS 330: Applied Database Systems. ER to Relational Relational Algebra

CIS 330: Applied Database Systems. ER to Relational Relational Algebra CIS 330: Applied Database Systems ER to Relational Relational Algebra 1 Logical DB Design: ER to Relational Entity sets to tables: ssn name Employees lot CREATE TABLE Employees (ssn CHAR(11), name CHAR(20),

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Tenth Edition Chapter 7 Introduction to Structured Query Language (SQL) Objectives In this chapter, students will learn: The basic commands and

More information

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables INDEX Exercise No Title 1 Basic SQL Statements 2 Restricting and Sorting Data 3 Single Row Functions 4 Displaying data from multiple tables 5 Creating and Managing Tables 6 Including Constraints 7 Manipulating

More information

Integrity constraints, relationships. CS634 Lecture 2

Integrity constraints, relationships. CS634 Lecture 2 Integrity constraints, relationships CS634 Lecture 2 Foreign Keys Defined in Sec. 3.2.2 without mentioning nulls. Nulls covered in Sec. 5.6 First example: nice not-null foreign key column: create table

More information

CSC Web Programming. Introduction to SQL

CSC Web Programming. Introduction to SQL CSC 242 - Web Programming Introduction to SQL SQL Statements Data Definition Language CREATE ALTER DROP Data Manipulation Language INSERT UPDATE DELETE Data Query Language SELECT SQL statements end with

More information

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL) Chapter 6 Introduction to Structured Query Language (SQL) Introduction Structured Query Language (SQL) is a data sublanguage that has constructs for defining and processing a database It can be Used stand-alone

More information

Unit Assessment Guide

Unit Assessment Guide Unit Assessment Guide Unit Details Unit code Unit name Unit purpose/application ICTWEB425 Apply structured query language to extract and manipulate data This unit describes the skills and knowledge required

More information

CS2300: File Structures and Introduction to Database Systems

CS2300: File Structures and Introduction to Database Systems CS2300: File Structures and Introduction to Database Systems Lecture 14: SQL Doug McGeehan From Theory to Practice The Entity-Relationship Model: a convenient way of representing the world. The Relational

More information

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel 1 In this chapter, you will learn: The basic commands

More information

T-SQL Training: T-SQL for SQL Server for Developers

T-SQL Training: T-SQL for SQL Server for Developers Duration: 3 days T-SQL Training Overview T-SQL for SQL Server for Developers training teaches developers all the Transact-SQL skills they need to develop queries and views, and manipulate data in a SQL

More information

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL functions fit into two broad categories: Data definition language Data manipulation language Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my

More information

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 5 Structured Query Language Hello and greetings. In the ongoing

More information

Follow these steps to get started: o Launch MS Access from your start menu. The MS Access startup panel is displayed:

Follow these steps to get started: o Launch MS Access from your start menu. The MS Access startup panel is displayed: Forms-based Database Queries The topic presents a summary of Chapter 3 in the textbook, which covers using Microsoft Access to manage and query an Access database. The screenshots in this topic are from

More information

Data Types in MySQL CSCU9Q5. MySQL. Data Types. Consequences of Data Types. Common Data Types. Storage size Character String Date and Time.

Data Types in MySQL CSCU9Q5. MySQL. Data Types. Consequences of Data Types. Common Data Types. Storage size Character String Date and Time. - Database P&A Data Types in MySQL MySQL Data Types Data types define the way data in a field can be manipulated For example, you can multiply two numbers but not two strings We have seen data types mentioned

More information

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1 SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1 Class 03: SQL Fundamentals 2 SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier

More information

MySQL Introduction. By Prof. B.A.Khivsara

MySQL Introduction. By Prof. B.A.Khivsara MySQL Introduction By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and not for commercial use. Outline Design

More information

Database Technology. Topic 3: SQL. Olaf Hartig.

Database Technology. Topic 3: SQL. Olaf Hartig. Olaf Hartig olaf.hartig@liu.se Structured Query Language Declarative language (what data to get, not how) Considered one of the major reasons for the commercial success of relational databases Statements

More information

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University SQL - Subqueries and Chapter 3.4 V4.0 Copyright @ Napier University Schema Subqueries Subquery one SELECT statement inside another Used in the WHERE clause Subqueries can return many rows. Subqueries can

More information

CHAPTER 16. More on SQL- Grouping Records and Table Joins

CHAPTER 16. More on SQL- Grouping Records and Table Joins CHAPTER 16 More on SQL- Grouping Records and Table Joins Brief Summary of the Chapter: grouping records table-joining using Group by clause of select statement of SQL Define a Transaction Describe reason

More information

Relational Algebra and SQL

Relational Algebra and SQL Relational Algebra and SQL Computer Science E-66 Harvard University David G. Sullivan, Ph.D. Example Domain: a University We ll use relations from a university database. four relations that store info.

More information

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1 COSC344 Database Theory and Applications Lecture 5 SQL - Data Definition Language COSC344 Lecture 5 1 Overview Last Lecture Relational algebra This Lecture Relational algebra (continued) SQL - DDL CREATE

More information

Table Joins and Indexes in SQL

Table Joins and Indexes in SQL Table Joins and Indexes in SQL Based on CBSE Curriculum Class -11 By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region Neha Tyagi, PGT CS II Shift Jaipur Introduction Sometimes we need an information

More information

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Table of Contents. PDF created with FinePrint pdffactory Pro trial version Table of Contents Course Description The SQL Course covers relational database principles and Oracle concepts, writing basic SQL statements, restricting and sorting data, and using single-row functions.

More information

SQL Interview Questions

SQL Interview Questions SQL Interview Questions SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems. In this tutorial, we shall go through the basic

More information

Relational Database Language

Relational Database Language DATA BASE MANAGEMENT SYSTEMS Unit IV Relational Database Language: Data definition in SQL, Queries in SQL, Insert, Delete and Update Statements in SQL, Views in SQL, Specifying General Constraints as Assertions,

More information

EE221 Databases Practicals Manual

EE221 Databases Practicals Manual EE221 Databases Practicals Manual Lab 1 An Introduction to SQL Lab 2 Database Creation and Querying using SQL Assignment Data Analysis, Database Design, Implementation and Relation Normalisation School

More information

CHAPTER4 CONSTRAINTS

CHAPTER4 CONSTRAINTS CHAPTER4 CONSTRAINTS LEARNING OBJECTIVES After completing this chapter, you should be able to do the following: Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN KEY,

More information

Chapter 1 SQL and Data

Chapter 1 SQL and Data Chapter 1 SQL and Data What is SQL? Structured Query Language An industry-standard language used to access & manipulate data stored in a relational database E. F. Codd, 1970 s IBM 2 What is Oracle? A relational

More information

THE UNIVERSITY OF AUCKLAND

THE UNIVERSITY OF AUCKLAND VERSION 1 COMPSCI 280 THE UNIVERSITY OF AUCKLAND SECOND SEMESTER, 2015 Campus: City COMPUTER SCIENCE Enterprise Software Development (Time allowed: 40 minutes) NOTE: Enter your name and student ID into

More information

Unit 1 - Chapter 4,5

Unit 1 - Chapter 4,5 Unit 1 - Chapter 4,5 CREATE DATABASE DatabaseName; SHOW DATABASES; USE DatabaseName; DROP DATABASE DatabaseName; CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype,... columnn

More information

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity SQL language: basics Creating a table Modifying table structure Deleting a table The data dictionary Data integrity 2013 Politecnico di Torino 1 Creating a table Creating a table (1/3) The following SQL

More information

Database Laboratory Note (MS SQL Server 2000)

Database Laboratory Note (MS SQL Server 2000) Database Laboratory Note MS SQL Server 2000 Creating a New Database using QA query analyzer In MS-SQL server 2000 a database can be considered as a container to the objects in a database. A database has

More information

Data Manipulation Language (DML)

Data Manipulation Language (DML) In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 3 Data Manipulation Language (DML) El-masry 2013 Objective To be familiar

More information

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data. DATA 301 Introduction to Data Analytics Relational Databases Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca DATA 301: Data Analytics (2) Why Relational Databases? Relational

More information

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] 1. What is DBMS? A Database Management System (DBMS) is a program that controls creation, maintenance and use

More information

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq Language f SQL Larry Rockoff Course Technology PTR A part ofcenqaqe Learninq *, COURSE TECHNOLOGY!» CENGAGE Learning- Australia Brazil Japan Korea Mexico Singapore Spain United Kingdom United States '

More information

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3 1 Chapter 3 Introduction to relational databases and MySQL Slide 2 Objectives Applied 1. Use phpmyadmin to review the data and structure of the tables in a database, to import and run SQL scripts that

More information

Creating and Managing Tables Schedule: Timing Topic

Creating and Managing Tables Schedule: Timing Topic 9 Creating and Managing Tables Schedule: Timing Topic 30 minutes Lecture 20 minutes Practice 50 minutes Total Objectives After completing this lesson, you should be able to do the following: Describe the

More information

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity COSC 416 NoSQL Databases Relational Model (Review) Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Relational Model History The relational model was proposed by E. F. Codd

More information

The Relational Model 2. Week 3

The Relational Model 2. Week 3 The Relational Model 2 Week 3 1 We have seen how to create a database schema, how do we create an actual database on our computers? professor(pid : string, name : string) course(pid : string, number :

More information

This lecture. Basic Syntax

This lecture. Basic Syntax This lecture Databases - Database Definition This lecture covers the process of implementing an ER diagram as an actual relational database. This involves converting the various entity sets and relationship

More information

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4 SQL OVERVIEW CS121: Relational Databases Fall 2017 Lecture 4 SQL 2 SQL = Structured Query Language Original language was SEQUEL IBM s System R project (early 1970 s) Structured English Query Language Caught

More information

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall The Relational Model Chapter 3 Comp 521 Files and Databases Fall 2012 1 Why Study the Relational Model? Most widely used model by industry. IBM, Informix, Microsoft, Oracle, Sybase, etc. It is simple,

More information

UNIT-IV (Relational Database Language, PL/SQL)

UNIT-IV (Relational Database Language, PL/SQL) UNIT-IV (Relational Database Language, PL/SQL) Section-A (2 Marks) Important questions 1. Define (i) Primary Key (ii) Foreign Key (iii) unique key. (i)primary key:a primary key can consist of one or more

More information

LAB 3 Notes. Codd proposed the relational model in 70 Main advantage of Relational Model : Simple representation (relationstables(row,

LAB 3 Notes. Codd proposed the relational model in 70 Main advantage of Relational Model : Simple representation (relationstables(row, LAB 3 Notes The Relational Model Chapter 3 In the previous lab we discussed the Conceptual Database Design Phase and the ER Diagram. Today we will mainly discuss how to convert an ER model into the Relational

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

Unit 27 Web Server Scripting Extended Diploma in ICT

Unit 27 Web Server Scripting Extended Diploma in ICT Unit 27 Web Server Scripting Extended Diploma in ICT Dynamic Web pages Having created a few web pages with dynamic content (Browser information) we now need to create dynamic pages with information from

More information

1. Which of the following will give the same answer irrespective of the NULL values in the specified. a. MIN() b. MAX()

1. Which of the following will give the same answer irrespective of the NULL values in the specified. a. MIN() b. MAX() MULTIPLE CHOICE QUESTIONS EXERCISES 1. Which of the following will give the same answer irrespective of the NULL values in the specified column: a. MIN() b. MAX() c. SUM() d. None of the above 2. An aggregate

More information

Activant Solutions Inc. SQL 2005: Basic Data Manipulation

Activant Solutions Inc. SQL 2005: Basic Data Manipulation Activant Solutions Inc. SQL 2005: Basic Data Manipulation SQL Server 2005 suite Course 4 of 4 This class is designed for Beginner/Intermediate SQL Server 2005 System Administrators Objectives System Stored

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

Oracle Create Table Foreign Key On Delete No

Oracle Create Table Foreign Key On Delete No Oracle Create Table Foreign Key On Delete No Action Can I create a foreign key against only part of a composite primary key? For example, if you delete a row from the ProductSubcategory table, it could

More information

Oracle Syllabus Course code-r10605 SQL

Oracle Syllabus Course code-r10605 SQL Oracle Syllabus Course code-r10605 SQL Writing Basic SQL SELECT Statements Basic SELECT Statement Selecting All Columns Selecting Specific Columns Writing SQL Statements Column Heading Defaults Arithmetic

More information

Chapter 4 SQL. Database Systems p. 121/567

Chapter 4 SQL. Database Systems p. 121/567 Chapter 4 SQL Database Systems p. 121/567 General Remarks SQL stands for Structured Query Language Formerly known as SEQUEL: Structured English Query Language Standardized query language for relational

More information

CONCEPTUAL DESIGN: ER TO RELATIONAL TO SQL

CONCEPTUAL DESIGN: ER TO RELATIONAL TO SQL RELATIONAL MODEL TO Data Model CONCEPTUAL DESIGN: ER TO RELATIONAL TO How to represent Entity sets, Relationship sets, Attributes, Key and participation constraints, Subclasses, Weak entity sets...? 2

More information

The Relational Model. Chapter 3

The Relational Model. Chapter 3 The Relational Model Chapter 3 Why Study the Relational Model? Most widely used model. Systems: IBM DB2, Informix, Microsoft (Access and SQL Server), Oracle, Sybase, MySQL, etc. Legacy systems in older

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course: Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course: 20762C Developing SQL 2016 Databases Module 1: An Introduction to Database Development Introduction to the

More information

Downloaded from

Downloaded from Lesson 16: Table and Integrity Constraints Integrity Constraints are the rules that a database must follow at all times. Various Integrity constraints are as follows:- 1. Not Null: It ensures that we cannot

More information

Introduction to relational databases and MySQL

Introduction to relational databases and MySQL Chapter 3 Introduction to relational databases and MySQL A products table Columns 2017, Mike Murach & Associates, Inc. C3, Slide 1 2017, Mike Murach & Associates, Inc. C3, Slide 4 Objectives Applied 1.

More information

Translating an ER Diagram to a Relational Schema

Translating an ER Diagram to a Relational Schema Translating an ER Diagram to a Relational Schema CS386/586 Introduction to Database Systems, Lois Delcambre 1999-2009 Slide 1 Translate each entity set into a table, with keys. Entity set: represented

More information

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6 SQL Part 2 Kathleen Durant PhD Northeastern University CS3200 Lesson 6 1 Outline for today More of the SELECT command Review of the SET operations Aggregator functions GROUP BY functionality JOIN construct

More information

SQL. Char (30) can store ram, ramji007 or 80- b

SQL. Char (30) can store ram, ramji007 or 80- b SQL In Relational database Model all the information is stored on Tables, these tables are divided into rows and columns. A collection on related tables are called DATABASE. A named table in a database

More information

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109 Index A abbreviations in field names, 22 in table names, 31 Access. See under Microsoft acronyms in field names, 22 in table names, 31 aggregate functions, 74, 375 377, 416 428. See also AVG; COUNT; COUNT(*);

More information

Introductory SQL SQL Joins: Viewing Relationships Pg 1

Introductory SQL SQL Joins: Viewing Relationships Pg 1 Introductory SQL SQL Joins: Viewing Relationships Pg 1 SQL Joins: Viewing Relationships Ray Lockwood Points: The relational model uses foreign keys to establish relationships between tables. SQL uses Joins

More information

Querying Data with Transact SQL

Querying Data with Transact SQL Course 20761A: Querying Data with Transact SQL Course details Course Outline Module 1: Introduction to Microsoft SQL Server 2016 This module introduces SQL Server, the versions of SQL Server, including

More information

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data. Managing Data Data storage tool must provide the following features: Data definition (data structuring) Data entry (to add new data) Data editing (to change existing data) Querying (a means of extracting

More information

Informatics 1: Data & Analysis

Informatics 1: Data & Analysis Informatics 1: Data & Analysis Lecture 4: From ER Diagrams to Relational Models Ian Stark School of Informatics The University of Edinburgh Friday 24 January 2014 Semester 2 Week 2 http://www.inf.ed.ac.uk/teaching/courses/inf1/da

More information

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13 CS121 MIDTERM REVIEW CS121: Relational Databases Fall 2017 Lecture 13 2 Before We Start Midterm Overview 3 6 hours, multiple sittings Open book, open notes, open lecture slides No collaboration Possible

More information

From theory to practice. Designing Tables for a postgresql Database System. psql. Reminder. A few useful commands

From theory to practice. Designing Tables for a postgresql Database System. psql. Reminder. A few useful commands From theory to practice Designing Tables for a postgresql Database System The Entity- Relationship model: a convenient way of representing the world. The Relational model: a model for organizing data using

More information

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Introduction to SQL ECE 650 Systems Programming & Engineering Duke University, Spring 2018 SQL Structured Query Language Major reason for commercial success of relational DBs Became a standard for relational

More information

Database Systems Fundamentals

Database Systems Fundamentals Database Systems Fundamentals Using PHP Language Arman Malekzade Amirkabir University of Technology (Tehran Polytechnic) Notice: The class is held under the supervision of Dr.Shiri github.com/arman-malekzade

More information

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall The Relational Model Chapter 3 Comp 521 Files and Databases Fall 2014 1 Why the Relational Model? Most widely used model by industry. IBM, Informix, Microsoft, Oracle, Sybase, MySQL, Postgres, Sqlite,

More information

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships Instructor: Craig Duckett Lecture 04: Thursday, April 5, 2018 Relationships 1 Assignment 1 is due NEXT LECTURE 5, Tuesday, April 10 th in StudentTracker by MIDNIGHT MID-TERM EXAM is LECTURE 10, Tuesday,

More information

Pagina 1 di 7 13.1.7. SELECT Syntax 13.1.7.1. JOIN Syntax 13.1.7.2. UNION Syntax SELECT [ALL DISTINCT DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]

More information

15CSL58: DATABASE MANAGEMENT LABORATORY

15CSL58: DATABASE MANAGEMENT LABORATORY 15CSL58: DATABASE MANAGEMENT LABORATORY Subject Code: 15CSL58 I.A. Marks: 20 Hours/Week: L(1)+P(2) Exam Hours: 03 Total Hours: 40 Exam Marks: 80 Course objectives: This course will enable students to Foundation

More information

INTRODUCTION TO MYSQL MySQL : It is an Open Source RDBMS Software that uses Structured Query Language. It is available free of cost. Key Features of MySQL : MySQL Data Types: 1. High Speed. 2. Ease of

More information

Database Programming with SQL

Database Programming with SQL Database Programming with SQL 2-1 Objectives This lesson covers the following objectives: Apply the concatenation operator to link columns to other columns, arithmetic expressions, or constant values to

More information

MySQL Workshop. Scott D. Anderson

MySQL Workshop. Scott D. Anderson MySQL Workshop Scott D. Anderson Workshop Plan Part 1: Simple Queries Part 2: Creating a database: creating a table inserting, updating and deleting data handling NULL values datatypes Part 3: Joining

More information

Databases. Jörg Endrullis. VU University Amsterdam

Databases. Jörg Endrullis. VU University Amsterdam Databases Jörg Endrullis VU University Amsterdam The Relational Model Overview 1. Relational Model Concepts: Schema, State 2. Null Values 3. Constraints: General Remarks 4. Key Constraints 5. Foreign Key

More information

GridDB Advanced Edition SQL reference

GridDB Advanced Edition SQL reference GMA022C1 GridDB Advanced Edition SQL reference Toshiba Solutions Corporation 2016 All Rights Reserved. Introduction This manual describes how to write a SQL command in the GridDB Advanced Edition. Please

More information

Lecture 1. Monday, August 25, 2014

Lecture 1. Monday, August 25, 2014 Lecture 1 Monday, August 25, 2014 What is a database? General definition: An organized collection of information. 1 Different Types of Databases Flat file o A one-table database o Usually loaded into a

More information

SQL: Data Definition Language

SQL: Data Definition Language SQL: Data Definition Language CSC 343 Winter 2018 MICHAEL LIUT (MICHAEL.LIUT@UTORONTO.CA) DEPARTMENT OF MATHEMATICAL AND COMPUTATIONAL SCIENCES UNIVERSITY OF TORONTO MISSISSAUGA Database Schemas in SQL

More information

Chapter 9: Working with MySQL

Chapter 9: Working with MySQL Chapter 9: Working with MySQL Informatics Practices Class XI (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.) Kendriya

More information

Creating SQL Tables and using Data Types

Creating SQL Tables and using Data Types Creating SQL Tables and using Data Types Aims: To learn how to create tables in Oracle SQL, and how to use Oracle SQL data types in the creation of these tables. Outline of Session: Given a simple database

More information

Chapter-14 SQL COMMANDS

Chapter-14 SQL COMMANDS Chapter-14 SQL COMMANDS What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. SQL is Structured Query Language, which is a computer language

More information

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object.

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object. 1 WHAT IS A DATABASE? A database is any organized collection of data that fulfills some purpose. As weather researchers, you will often have to access and evaluate large amounts of weather data, and this

More information

SQL. SQL Data Manipulation: Queries

SQL. SQL Data Manipulation: Queries SQL Data Manipulation: Queries ISYS 464 Spring 2003 Topic 09 1 SQL SQL: Structured Query Language Pronounced: "S Q L" or "sequel" Developed by IBM in San Jose for its experimental relational database management

More information

MySQL for Developers with Developer Techniques Accelerated

MySQL for Developers with Developer Techniques Accelerated Oracle University Contact Us: 02 696 8000 MySQL for Developers with Developer Techniques Accelerated Duration: 5 Days What you will learn This MySQL for Developers with Developer Techniques Accelerated

More information

MySQL by Examples for Beginners

MySQL by Examples for Beginners yet another insignificant programming notes... HOME MySQL by Examples for Beginners Read "How to Install MySQL and Get Started" on how to install, customize, and get started with MySQL. 1. Summary of MySQL

More information

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul 1 EGCI 321: Database Systems Dr. Tanasanee Phienthrakul 2 Chapter 10 Data Definition Language (DDL) 3 Basic SQL SQL language Considered one of the major reasons for the commercial success of relational

More information

MySQL Creating a Database Lecture 3

MySQL Creating a Database Lecture 3 MySQL Creating a Database Lecture 3 Robb T Koether Hampden-Sydney College Mon, Jan 23, 2012 Robb T Koether (Hampden-Sydney College) MySQL Creating a DatabaseLecture 3 Mon, Jan 23, 2012 1 / 31 1 Multiple

More information

Chapter 16: Databases

Chapter 16: Databases Chapter 16: Databases Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 16 discusses the following main topics: Introduction to Database

More information

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data 1 Writing Basic SQL SELECT Statements Objectives 1-2 Capabilities of SQL SELECT Statements 1-3 Basic SELECT Statement 1-4 Selecting All Columns 1-5 Selecting Specific Columns 1-6 Writing SQL Statements

More information

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017 SQL: Data Definition Language csc343, Introduction to Databases Diane Horton Fall 2017 Types Table attributes have types When creating a table, you must define the type of each attribute. Analogous to

More information