CMP-3440 Database Systems

Similar documents
CMP-3440 Database Systems

Definition of terms Objectives Interpret history and role of SQL Define a database using SQL data definition iti language Write single table queries u

Chapter 6. SQL Data Manipulation

In SQL window, type SHOW TABLE STATUS; and discuss INNODB vs. MyISAM (foreign key support; transactions; row-level locking)

DB Creation with SQL DDL

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

1) Introduction to SQL

COMP102: Introduction to Databases, 4

STRUCTURED QUERY LANGUAGE (SQL)

Lecture 07. Spring 2018 Borough of Manhattan Community College

! Define terms. ! Interpret history and role of SQL. ! Write single table queries using SQL. ! Establish referential integrity using SQL

Transforming ER to Relational Schema

(ADVANCED) DATABASE SYSTEMS (DATABASE MANAGEMENTS) PROF. DR. HASAN HÜSEYİN BALIK (6 TH WEEK)

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

3ISY402 DATABASE SYSTEMS

Lab # 4. Data Definition Language (DDL)

Chapter-14 SQL COMMANDS

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

Creating and Managing Tables Schedule: Timing Topic

Unit 1 - Chapter 4,5

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Chapter 9: Working with MySQL

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

SQL Structured Query Language Introduction


GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

CS317 File and Database Systems

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Downloaded from

Lecture 06. Fall 2018 Borough of Manhattan Community College

@vmahawar. Agenda Topics Quiz Useful Links

Lab # 3 Hands-On. DML Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

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

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

SQL Commands & Mongo DB New Syllabus

CSC Web Programming. Introduction to SQL

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Exact Numeric Data Types

STRUCTURED QUERY LANGUAGE (SQL)

King Fahd University of Petroleum and Minerals

1 SQL Structured Query Language

Relational Database Language

Lecture 5 Data Definition Language (DDL)

MySQL Introduction. By Prof. B.A.Khivsara

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

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

Structured Query Language (SQL)

Structured Query Language. ALTERing and SELECTing

Oracle Database 10g: Introduction to SQL

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

CMP-3440 Database Systems

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

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

Sample Question Paper

Course Outline and Objectives: Database Programming with SQL

Lecture 6 Structured Query Language (SQL)

1 SQL Structured Query Language

Lecture4: Guidelines for good relational design Mapping ERD to Relation. Ref. Chapter3

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

Appendix A. Using DML to Modify Data. Contents: Lesson 1: Adding Data to Tables A-3. Lesson 2: Modifying and Removing Data A-8

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

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

Databases - 4. Other relational operations and DDL. How to write RA expressions for dummies

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Data Base Concepts. Course Guide 2

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database: SQL Fundamentals I. Q&As: 292

CSIE30600 Database Systems Basic SQL 2. Outline

Exam code: Exam name: Database Fundamentals. Version 16.0

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Deepak Bhinde PGT Comp. Sc.

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

LECTURE 6: GUIDELINES FOR GOOD RELATIONAL DESIGN MAPPING ERD TO RELATIONS

Introduction to Computer Science and Business

1z Oracle Database SQL Expert

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy.

SQL STRUCTURED QUERY LANGUAGE

Introduction to Views

Data Definition Language (DDL)

CS2 Current Technologies Lecture 2: SQL Programming Basics

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

Downloaded from

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

How to use SQL to create a database

2.2.2.Relational Database concept

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

NCSS: Databases and SQL

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

Standard Query Language. SQL: Data Definition Transparencies

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

CSCC43H: Introduction to Databases. Lecture 4

Fname A variable character field up to 15 characters in length. Must have a value Lname A variable character field up to 15

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

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

Transcription:

CMP-3440 Database Systems Relational DB Languages SQL Lecture 06 zain 1

Purpose and Importance Database Language: To create the database and relation structures. To perform various operations. To handle simple and complicated queries. Perform these tasks with: Minimal user effort and Command structure/syntax must be easy to learn Must be portable. 2

Purpose and Importance SQL is transform-oriented language with two major components: DDL (Data Definition Language) CREATE, ALTER, DROP, TRUNCATE, RENAME etc. DML (Data Manipulation Language) SELECT, INSERT, UPDATE, DELETE, MERGE, LOCK etc. DCL (Data Control Language) GRANT, REVOKE TCL (Transaction Control Language) COMMIT, ROLLBACK, SET TRANSACTION etc. SQL is relatively easy to learn: Non-procedural; you specify what information you require, rather than how to get it. It is essentially free-format 3

Objectives of SQL Consists of standard English words: CREATE TABLE Staff(staffNo VARCHAR(5), lastname VARCHAR(15), salary DECIMAL(7,2)); INSERT INTO Staff VALUES ( SG16, ASLAM, 8500); SELECT staffno, lastname, salary FROM Staff WHERE salary > 4000; 4

Objectives of SQL Can be used by range of users including DBAs, management, application developers and other types of end users. An ISO standard now exists for SQL, making it both the formal and de facto standard language for relational database. 5

Writing SQL Commands SQL statement consists of reserved words and user-defined words. Reserved Words: Fixed part of SQL and must be spelt exactly as required and cannot be split across lines. User-defined Words: Made up by user and represent names of various database objects such as relations, columns, views. 6

SQL Sample Data Types String CHARACTER(CHAR) fixed length CHARACTER VARYING definable variable length (VARCHAR or VARCHAR2) BINARY LARGE OBJECT (BLOB) binary strings in hexadecimal Number NUMERIC exactly defined numbers INTEGER (INT) Temporal TIMESTAMP data/time with local time zone Boolean BOOLEAN true/false 7

Writing SQL Commands Case insensitive except literal. Extended notation: Upper-case letters Reserved Words. Lower-case letters user-defined words. Literals are constantly used in SQL statements: Non-numeric literals enclosed in single quotes e.g. Sargodha Numeric literals not be enclosed in quotes e.g. 650.00 8

DDL - Defining a Database CREATE commands are used to create database objects CREATE SCHEMA database_name; CREATE TABLE table_name; CREATE VIEW view_name; Create commands can be reversed using DROP DROP SCHEMA database_name DROP TABLE table_name DROP VIEW view_name ALTER commands can be used to change the existing definition 9

DDL Creating Table CREATE TABLE Customer_T (CustomerID NUMBER(11,0) CustomerName VARCHAR2(25) CustomerAddress VARCHAR2(30), CustomerCity VARCHAR2(20), CustomerState CHAR(2), CustomerPostalCode VARCHAR2(9), NOT NULL, NOT NULL, CONSTRAINT Customer_PK PRIMARY KEY (CustomerID)); 10

DDL Creating Table CREATE TABLE Order_T (OrderID NUMBER(11,0) OrderDate DATE CustomerID NUMBER(11,0), NOT NULL, DEFAULT SYSDATE, CONSTRAINT Order_PK PRIMARY KEY (OrderID), CONSTRAINT Order_FK FOREIGN KEY (CustomerID) REFERENCES Customer_T(CustomerID)); 11

DDL Table Integrity Restricted Update: A customer ID can only be deleted if it is not found in ORDER table. CREATE TABLE CustomerT (CustomerID INTEGER DEFAULT 999 NOT NULL, CustomerName VARCHAR(40) NOT NULL, CONSTRAINT Customer_PK PRIMARY KEY (CustomerID), ON UPDATE RESTRICT); Cascaded Update: Changing a customer ID in the CUSTOMER table will result in that value changing in the ORDER table to match.... ON UPDATE CASCADE); 12

DDL Table Integrity Set Null Update: When a customer ID is changed, any customer ID in the ORDER table that matches the old customer ID is set to NULL.... ON UPDATE SET NULL); Set Default Update: When a customer ID is changed, any customer ID in the ORDER tables that matches the old customer ID is set to a predefined default value.... ON UPDATE SET DEFAULT); 13

DDL Changing Table Definition Syntax: ALTER TABLE table_name alter_table_action; Some of the alter_table_actions available are: ADD [COLUMN] column_definition ALTER [COLUMN] column_name SET DEFAULT default-value ALTER [COLUMN] column_name DROP DEFAULT DROP [COLUMN] column_name [RESTRICT] [CASCADE] ADD table_constraint ALTER TABLE CUSTOMER_T ADD COLUMN CustomerType VARCHAR2 (2) DEFAULT Commercial ; 14

DDL View Query: What are the data elements necessary to create an invoice for a customer? Save this query as a view named Invoice_V. CREATE VIEW Invoice_V AS SELECT Customer_T.CustomerID, CustomerAddress, Order_T.OrderID, Product_T.ProductID,ProductStandardPrice, OrderedQuantity, and other columns as required FROM Customer_T, Order_T, OrderLine_T, Product_T WHERE Customer_T.CustomerID = Order_T.CustomerID AND Order_T.OrderID = OrderLine_T.OrderD AND Product_T.ProductID = OrderLine_T.ProductID; 15

DDL View Query: List all furniture products that have ever had a standard price over $300. CREATE VIEW ExpensiveStuff_V AS SELECT ProductID, ProductDescription, ProductStandardPrice FROM Product_T WHERE ProductStandardPrice > 300 WITH CHECK OPTION; Error, when attempting to update the unit price of the writer s desk to $295 16

DML Inserting Data Command: To insert a row of data into a table where a value will be inserted for every attribute. INSERT INTO Customer_T VALUES (001, Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, FL, 32601); Command: To insert a row of data into a table where some attributes will be left null. INSERT INTO Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice) VALUES (1, End Table, Cherry, 175, 8); 17

DML Inserting Data Command: Populating a table by using a subset of another table with the same structure. INSERT INTO CaCustomer_T SELECT * FROM Customer_T WHERE CustomerState = CA ; 18

DML Inserting Data Command: Populating a table having unique primary identifier CREATE TABLE Customer_T (CustomerID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 10000 NO CYCLE), CustomerName VARCHAR2(25) NOT NULL, CustomerAddress VARCHAR2(30), CustomerCity VARCHAR2(20), CustomerState CHAR(2), CustomerPostalCode VARCHAR2(9), CONSTRAINT Customer_PK PRIMARY KEY (CustomerID); 19

DML Inserting Data Command: Populating a table having unique primary identifier The primary key value, 001, does not need to be entered INSERT INTO Customer_T VALUES (001, Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, FL, 32601); to this: INSERT INTO Customer_T VALUES ( Contemporary Casuals, 1355 S. Himes Blvd., Gainesville, FL, 32601); 20

DML Deleting Data Command: Deleting rows that meet a certain criterion from the Customer table. DELETE FROM Customer_T WHERE CustomerState = HI ; Command: Deleting all rows from the Customer table. DELETE FROM Customer_T; 21

DML Updating Data Command: To modify standard price of product 7 in the Product table to 775. UPDATE Product_T SET ProductStandardPrice = 775 WHERE ProductID = 7; 22

Data Retrieval - SELECT Statement SELECT list columns from tables/views FROM identifies the tables/views WHERE include conditions for row selection 23

SELECT Statement SELECT [DISTINCT ALL] {* [columnexpression [AS newname]] [, ] } FROM TableName [alias] [, ] [WHERE condition] [GROUP BY columnlist] [HAVING condition] [ORDER BY columnlist] ; 24

Example All Columns, All Rows List full details of all staff SELECT staffno, fname, lname, address, position, gender, DOB, salary, branchno FROM Staff; Can use * as an abbreviation for all columns : SELECT * FROM Staff; staffno fname lname Address Position Gender DOB Salary branchno SL21 Amir Bilal 56 abc Manager M 1-Oct-84 30000 B005 SG17 Aslam Basit 65 def Assistant M 7-Nov-86 35000 B003 SA09 Asim Bashir 89 ghijk Admin M 9-Dec-88 36000 B003 25

Example Specific Columns, All Rows List of salaries for all staff, showing only staff number, first & last name, and salary SELECT staffno, fname, lname, salary FROM Staff; staffno fname lname Salary SL21 Amir Bilal 30000 SG17 Aslam Basit 35000 SA09 Asim Bashir 36000 26

Example Use of Distinct List all branch numbers where staff works SELECT branchno FROM Staff; branchno B005 B003 B003 Use DISTINCT to eliminate duplicates SELECT DISTINCT branchno FROM Staff; branchno B005 B003 27

Example Calculated Fields Produce a list of annual salaries of all staff, showing staff number, first & last names, and salary details SELECT staffno, fname, lname, salary * 12 FROM Staff; staffno fname lname col4 SL21 Amir Bilal 30000 SG17 Aslam Basit 35000 SA09 Asim Bashir 36000 To name column, use AS clause: SELECT staffno, fname, lname, salary * 12 AS AnnualSalary FROM Staff; 28

Example Comparison Search Condition List all staff with a salary greater than 32000 SELECT staffno, fname, lname, position, salary FROM Staff WHERE salary > 32000; staffno fname lname Position Salary SG17 Aslam Basit Assistant 35000 SA09 Asim Bashir Admin 36000 29

Example Compound Comparison Search Condition List all addresses of all branch offices in Sargodha or Lahore SELECT * FROM Branch WHERE city = Sargodha OR city = Lahore ; branchno Street City B005 22 College Road Lahore B003 150 Main Road Sargodha 30

Example Range Search Condition List all names of staff with a salary between 30000 and 35000 SELECT staffno, fname, lname, salary FROM Staff WHERE salary BETWEEN 30000 AND 35000; Also a negated version NOT BETWEEN. Could also write: SELECT staffno, fname, lname, salary FROM Staff WHERE salary >=30000 AND salary <=35000, staffno fname lname Salary SL21 Amir Bilal 30000 SG17 Aslam Basit 35000 31

Example Set Membership List all managers and assistants SELECT staffno, fname, lname, position FROM Staff WHERE position IN ( Manager, Assistant ); Also a negated version (NOT IN) Could also write: SELECT staffno, fname, lname, position FROM Staff WHERE position = Manager OR position = Assistant ; staffno fname lname Position SL21 Amir Bilal Manager SG17 Aslam Basit Assistant 32

Example Pattern Matching Find all owners with the string Lahore in their address. SELECT clientno, fname, lname, address FROM PrivateOwner WHERE address LIKE %Lahore% ; clientno fname lname Address CO87 Abid Bhatti 6 High Road, Lahore CO42 Atif Butt 45 Lahore Broast, Sargodha CO83 Arshad Bilal 92 Iqbal Park, Lahore 33

Example Pattern Matching SQL has two pattern matching symbols: % sequence of zero or more characters. _ any single character LIKE %Lahore% means a sequence of characters of any length containing Lahore. 34

Example NULL Search Condition List details of all clients where a phone number is not available SELECT clientno, name FROM Clients WHERE phone IS NULL; clientno Name 0001 Faraz Khan 0008 Farooq Khan Negative version (IS NOT NULL) can be used for non-null values. 35

Example Column Ordering List salaries for all staff, arranged in descending order of salary. SELECT staffno, fname, lname, salary FROM Staff ORDER BY salary DESC; Ascending order can be listed by eliminating DESC. Ordering can be made for multiple columns as well staffno fname lname salary SA09 Asim Bashir 36000 SG17 Aslam Basit 35000 SL21 Amir Bilal 30000 36

Using Aliases in SQL empno ename Job MGR hiredate Salary Phone deptno E1509 Asad FullTime E1309 3-1-09 32000 111222 D009 E1309 Amir FullTime 1-1-07 35000 333444 D004 E1317 Ali FullTime E1309 11-8-11 28000 656565 D009 List the name of the manager for the employee Asad SELECT ename from EMPLOYEES WHERE empno = (SELECT MGR from EMPLOYEE WHERE ename = Asad ); SELECT m.ename FROM EMPLOYEES e, EMPLOYEES m WHERE m.empno = e.mgr AND e.ename = Asad ; 37