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