NUR HAZIMAH BINTI KHALID SHARIZAN BINTI ABDUL JAMIL TS. AINIE HAYATI BINTI NORUZMAN FFUUNNDDAAMMEENNTTAALLSS DDAATTAABBAASSEE WORKBOOK
IV
C H A P T E R 4 CHAPTER 4 S T R U C T U R E D Q U E R Y L A N G U A G E
QUICK NOTES Create Database CREATE DATABASE database_name; Add a Column to a Table ALTER TABLE table_name ADD col_name data_type; Delete a Column from a Table ALTER TABLE table_name DROP col_name; ALTER TABLE table_name MODIFY COLUMN col_name data_type; Change Data Type of a Column ALTER TABLE table_name RENAME new_table_name; Rename Table Name Use Database USE database_name; 1 Data Definition Language (DDL) Create Table with Primary Key & Foreign Key Defined CREATE TABLE table_name ( col_name1 data_type1 const1, col_name2 data_type2 const2, . . col_nameN data_typeN constN, PRIMARY KEY (PK_col), FOREIGN KEY (FK_col) REFERENCES table_name(FK_col) ); ALTER TABLE table_name ADD PRIMARY KEY (PK_col); Define Primary Key of a Table ALTER TABLE table_name CHANGE old_col new_col data_type constraints; Rename Column Name of a Table DROP TABLE table_name; Remove Table Data Manipulation Language (DML) Insert Data into Table INSERT INTO table_name ( col_name1, col_name2, . . col_nameN ) VALUES (value_col_name1,value_col_nam e2,..,value_col_nameN); Select All Data from Table SELECT * FROM table_name; Select Certain Data from Table SELECT col_name1,..,col_nameN FROM table_name; Update Data in the Table UPDATE table_name SET col_name1=value_col_name1, col_name2=value_col_name2, . . col_nameN=value_col_nameN WHERE condition; Delete Certain Record from Table DELETE FROM table_name WHERE condition; Delete All Record from Table DELETE FROM table_name; DISTINCT SELECT DISTINCT col_name FROM table_name [WHERE condition]; WHERE, AND / OR SELECT col_name FROM table_name WHERE condition1 [AND | OR ] condition2; ORDER BY SELECT col_name FROM table_name [WHERE condition] ORDER BY expression [ASC | DESC]; LIKE & WILDCARDS SELECT col_name FROM table_name WHERE condition LIKE 'WILDCARDS % | _'; BETWEEN SELECT col_name FROM table_name WHERE col_name BETWEEN value_col_name1 AND value_col_name2; GROUP BY & HAVING SELECT col_name FROM table_name [WHERE condition] GROUP BY expression HAVING condition; SQL (Structured Query Language) is a non-procedural language used to managing database. It is used to create and manage database and table structures. It is used to retrieve, insert, update and delete data. It is used to manage access control and implement transaction control. Introduction to SQL SQL Data Types Character/ String – Stores text, letters, numbers, and symbols Numeric – Stores numbers Date/ Time – Stores date and time values SQL Statement Types Data Definition Language CREATE, USE, ALTER, DROP, TRUNCATE, RENAME Data Manipulation Language SELECT, INSERT, UPDATE, DELETE Transaction Control Language COMMIT, ROLLBACK, SAVEPOINT Data Control Language GRANT, REVOKE Constraint Types Column level constraints apply to a column Table level constraints apply to entire table. SQL Aggregate Functions MIN() – Returns the smallest value. MAX() – Returns the largest value. AVG() – Returns the average value. COUNT() – Returns the number of records. SUM() – Returns the total sum of values. SQL Advanced Commands Join SELECT col_name1,..,col_nameN, [INNER JOIN | LEFT JOIN | RIGHT JOIN | FULL JOIN] FROM table_name ON condition; IN SELECT col_name FROM table_name WHERE col_name IN (value_col_name1, value_col_name2,.., value_col_nameN); INTERSECT SELECT col_name FROM table_name [WHERE condition] INTERSECT SELECT col_name FROM table_name [WHERE condition];
BranchNo Street City Postcode B005 Jalan Warisan Puteri Sepang 43900 B007 Jalan Camar Johor Bahru 81200 B009 Jalan Seri Tanjung Sungai Air Tawar 45100 B011 Jalan Stadium Alor Setar 05150 StaffNo Name Position Gender BranchNo S002 Marisa Azhar Site Manager Female B005 S007 Fariq Kamaruddin Programmer Male B007 S010 Natasha Zarith Architect Female B009 S011 Haziq Adham Site Manager Male B007 P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 1 Given the Branch and Staff tables, write SQL commands for question 1(a) and 1(b). Table 1.1 : Branch Table 1.2 : Staff List BranchNo, City and Postcode for BranchNo B007 from Branch table. List all staff details that hold Site Manager position from Staff table. (a) (b) 2 SOLUTION (a) (b)
DEPARTMENT PK DeptCode Integer Name Varchar(50) Budget Float P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 2 Given the Department and Employee ERD, write SQL commands for question 2(a), 2(b) and 2(c). Create department and employee tables with PK and FK defined. Insert 2 records for each table. Rename column name in Employee table from 'Name' to 'FirstName'. (a) (b) (c) 3 SOLUTION EMPLOYEE PK SSN Integer Name Varchar(50) LastName Varchar(50) FK DeptCode Integer (a) (b) (c)
DeptCode DeptName FacultyName F001 Dept. Accountancy FA F010 Dept. Mathemathics FSKM F011 Dept. Computer Science FSKM F012 Dept. Networking FSKM LectNo LectName Title DOB DeptCode L001 Syakilla Zakaria Dr. 17-02-1979 F011 L002 Marzuki Ahmad Prof. Madya. Dr. 16-05-1980 F010 L003 Nani Amalina Zin Ts. Dr. 21-09-1985 F011 L004 Zaki Syed Husain Prof. 25-06-1990 F012 P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 3 Given the Department and Lecturer tables, write SQL commands for question 3(a) and 3(b). Table 6.1 : Department Table 6.2 : Lecturer List the LectName and Age from Lecturer table. List LectName, Title and DeptName by joining Lecturer and Department table. (a) (b) 4 SOLUTION (a) (b)
P R A C TI C A L E X E R C I S E QUESTION 4 (b) Explain the function of aggregate : COUNT(), MAX() and SUM(). 5 [Past Year December 2015] (a) List any TWO (2) tasks that can be implemented using SQL. SOLUTION (a) SOLUTION (b) QUESTION 5 (b) Differentiate between DROP and DELETE commands. (a) Explain the function USE command in Data Definition Language (DDL). SOLUTION (a) SOLUTION (b) [Past Year June 2015] C H A P T E R 4
DeptNo DeptName 10 Accounting 20 Operations 30 Research 40 Sales EmpNo EmpName JobTitle DateJoined Salary DeptNo 1042 Allen Tan SalesExec 15-Aug-83 1600 30 1232 Maznah SalesExec 26-Mar-84 1250 30 1265 Mohamad Manager 31-Oct-83 2975 20 1098 Fatimah SalesExec 05-Dec-83 1250 30 1034 David Manager 11-Jun-84 2850 30 1206 Mariah Manager 14-May-84 2450 10 1154 Sathi Analyst 05-Mar-84 3000 20 1192 James Director 09-Jul-84 5000 10 1086 Swee Lee SalesExec 04-Jun-84 1500 30 1245 Leong Clerk 04-Jun-84 1100 20 1010 Sharifah Clerk 23-Jul-84 950 30 1005 Muthu Analyst 05-Dec-83 3000 20 P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 6 Given the Employee and Department tables, show the output for question 6(a) and 6(b). Table 6.1 : Department Table 6.2 : Employee 6 [Past Year December 2015]
P R A C TI C A L E X E R C I S E C H A P T E R 4 7 SELECT EmpName, Employee.DeptNo, JobTitle, Salary FROM Employee, Department WHERE Employee.DeptNo = Department.DeptNo ORDER BY Employee.DeptNo; (b) SELECT EmpName, DeptNo, JobTitle, Salary FROM Employee WHERE Salary > 2000; (a) SOLUTION (a) SOLUTION (b) C H A P T E R 4
P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 7 (b) List FOUR (4) function commands in SQL aggregate functions. 8 [Past Year Session I 2023-2024] Give the definition of Data Definition Language (DDL) and state TWO (2) SQL commands under the DDL category. (a) SOLUTION (a) SOLUTION (b) QUESTION 8 (b) Name FIVE (5) SQL ADVANCED commands. (a) State THREE (3) SQL commands under the DML (Data Manipulation Language). SOLUTION (a) SOLUTION (b) [Past Year Session II 2022-2023]
docNo docName docState docSalary 743 Azmira Hamdan Terengganu 15,000.00 284 Aisyah Yusoff Pahang 9,542.20 352 Manav Veer Pahang 10,321.00 421 Peter Shawn Selangor 13,541.00 625 Nurul Jannah Pahang 11,150.21 544 Alex Wong Kedah 10,079.00 P R A C TI C A L E X E R C I S E QUESTION 9 Given the Doctor tables, show the output for question 9(a) and SQL statement for question 9(b). Table 9.1 : Doctor 9 [Past Year Session I 2023-2024] SELECT * FROM DOCTOR WHERE docState = ‘Pahang’ AND docSalary > 10,000.00; (a) SOLUTION (a) (b) Write SQL statement to insert TWO (2) new rows into table DOCTOR. SOLUTION (b) C H A P T E R 4
Player_Id Name Country Age Salary P01 Wissam Ben Yedder France 32 400,00 P02 Thomas Muller Germany 33 500,00 P03 Nguyen Quang Hai Vietnam 25 390,00 P04 Kaoru Mitoma Japan 25 450,00 P05 Karim Benzema France 35 500,00 P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 10 Given the Player tables, show the SQL query statement for question 10(a) and 10(b). Table 10.1 : Player 10 [Past Year Session II 2022-2023] (a) List all identification number and age of the players from France. SOLUTION (a) List all name and salary of the players with salary sorted in ascending order. (b) SOLUTION (b)
Book_Id Book_Name Price Quality_of_Book B01 Angel Eye 100 10 B02 Rapunzel 80 20 B03 Ali and Football 150 10 B04 World 200 5 P R A C TI C A L E X E R C I S E QUESTION 11 Given the Book tables, construct a SQL query for situation in question 11(a) and 11(b). Table 11.1 : Book 11 [Past Year Session II 2022-2023] (a) Calculate quantity of all books. SOLUTION (a) Display book’s name that starts with ‘A’ and book’s where the price is sorted descending order. (b) SOLUTION (b) C H A P T E R 4
P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 12 12 [Past Year Session I 2022-2023] (a) State FOUR (4) uses of SQL in a database. SOLUTION (a) Staff_ID Staff_Name Staff_State Staff_Salary 111 Azmira Hamdan Terengganu 5200 222 Aisyah Yusoff Pahang 3700 333 Manav Veer Pahang 4700 444 Peter Shawn Selangor 5100 555 Alex Wong Kedah 3600 QUESTION 13 Given the Staff tables, build a SQL query for situation in question 13(a). Table 13.1 : Staff (a) Display the name and state of staff whose salary exceeds RM4500. SOLUTION (a)
Id_Student (PK) Name Age Sex State 21DIP12F2001 Ali Azhar 20 M Johor 21DIP11F2045 Raju A/L Kumar 19 M Terengganu 21DIP13F2067 Yasmin Yusof 18 F Sabah 21DIP11F2054 Zahlia Idris 18 F Kelantan Id_Lec (PK) Lec_Name Subject State Salary 3120 Norhaliza Idris FP613 Penang 4000 5123 Azizah Safie DFC2033 Kedah 3000 P R A C TI C A L E X E R C I S E QUESTION 14 Given the Student and Lecturer tables, write the SQL command for question 14(a), 14(b) and 14 (c). Table 14.1 : Student Table 14.2 : Lecturer 13 [Past Year December 2014] (a) Create both tables Student and Lecturer. SOLUTION (a) C H A P T E R 4
P R A C TI C A L E X E R C I S E C H A P T E R 4 (c) Display all the records in Lecturer’s table whose salary is more than RM 2000. 14 Display STUDENT tuples whose Age number is 19 years old and came from Kelantan. (b) SOLUTION (b) SOLUTION (c) QUESTION 15 Write the SQL command to create a table named PRODUCT with the following columns: Prod_ID (Integer, Primary Key) Prod_Name (Varchar (50)) Prod_Description (Varchar (50)) Price (Integer) SOLUTION (a) (a)
P R A C TI C A L E X E R C I S E QUESTION 16 15 Explain the difference between WHERE and HAVING clauses in SQL. Provide an example for each. (a) SOLUTION (a) QUESTION 17 (a) Explain the difference between DELETE and TRUNCATE in SQL. SOLUTION (a) QUESTION 18 Write an SQL query to display all products from the Product table where the Prod_Name: SOLUTION (a) a) Starts with 'A' b) Ends with 'A' c) Has at least one 'A' in the middle (b) (c) C H A P T E R 4
STUDENT PK Stud_ID Integer Name Varchar(50) Age Integer Gender Char (1) Email Varchar(20) P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 19 Given the following ERD, write SQL commands for question 19(a), 19(b) and 19(c). 16 COURSE PK Course_ID Integer Name Varchar(50) Credits Integer ENROLLMENT PK Enroll_ID Integer Enroll_Date Varchar(50) FK Stud_ID Integer Course_ID Integer (a) Create student, course and enrollment tables with PK and FK defined. SOLUTION (a)
P R A C TI C A L E X E R C I S E 17 (b) Insert 2 records for each table. (c) Retrieve the number of students enrolled in each course. SOLUTION (b) SOLUTION (b) SOLUTION (a) C H A P T E R 4
P R A C TI C A L E X E R C I S E C H A P T E R 4 QUESTION 20 18 (a) Explain FOUR (4) types of SQL statements. SOLUTION (a) Describe SQL Advance Commands below: DISTINCT WHERE ORDER BY (b) SOLUTION (b) (c) Differentiate between table and column constraints in database. SOLUTION (c)
P R A C TI C A L E X E R C I S E A N SWE R QUESTION 1 19 (a) SELECT BranchNo, City, Postcode FROM Branch WHERE BranchNo = 'B007'; (b) SELECT * FROM Staff WHERE Position = 'Site Manager'; QUESTION 2 (a) CREATE TABLE Department ( DeptCode INT NOT NULL, Name VARCHAR(50) DEFAULT NULL, Budget FLOAT DEFAULT NULL, PRIMARY KEY (DeptCode) ); CREATE TABLE Employee ( SSN INT NOT NULL, Name VARCHAR(50) DEFAULT NULL, LastName VARCHAR(50) DEFAULT NULL, DeptCode INT DEFAULT NULL, PRIMARY KEY (SSN), FOREIGN KEY (DeptCode) REFERENCES Department (DeptCode) ); (b) INSERT INTO Employee (SSN, Name, LastName, DeptCode) VALUES ( '850120-01-5221', 'Ara Thalia', 'Zulhilmi', 20), ( '900904-14-5443', 'Faris Iskandar', 'Iskandar', 10); INSERT INTO Department (DeptCode, Name, Budget) VALUES ( 10, 'Human Resource Dept.', 3009.99), ( 20, 'Accounting Dept.', 2055.50); (c) ALTER TABLE Employee RENAME COLUMN Name to FirstName; QUESTION 3 (a) SELECT LectName, DATEDIFF(YY, DOB, GETDATE()) as 'Age' FROM Lecturer; (b) SELECT Lc.LectName, Lc.Title, Dp.DeptName FROM Lecturer Lc INNER JOIN Department Dp ON Lc.DeptCode = Dp.DeptCode; *Any relevant answers are accepted C H A P T E R 4
P R A C TI C A L E X E R C I S E A N SWE R C H A P T E R 4 QUESTION 4 20 (a) Create and manage database Create and modify database tables Insert, update and delete data Retrieve data using queries Manage access control Implement transaction control (b) COUNT() function is used to return the number of rows that matches a specified criterion. MAX() function is used to returns the largest value of the selected column. MIN() function is used to return smallest value of the selected column. *Any relevant answers are accepted QUESTION 5 (a) The USE command in DDL is used to select a particular database and perform SQL operation in the chosen database (b) Feature DROP Command DELETE Command Definition It removes an entire database, table and object from database It deletes specific rows from table based on a condition Syntax DROP TABLE table_name; DELETE FROM table_name WHERE condition; Effect on Data It removes all data along with the table structure It removes only selected data, however the table structure remains Impact on Schema It removes indexes, constraints and dependencies It does not affect indexes, constraints, or structure QUESTION 6 EmpNo EmpName JobTitle DateJoined Salary DeptNo 1265 Mohamad Manager 31-Oct-83 2975 20 1034 David Manager 11-Jun-84 2850 30 1206 Mariah Manager 14-May-84 2450 10 1154 Sathi Analyst 05-Mar-84 3000 20 1192 James Director 09-Jul-84 5000 10 1005 Muthu Analyst 05-Dec-83 3000 20 (a) RESULT TABLE
P R A C TI C A L E X E R C I S E A N SWE R QUESTION 6 21 (b) QUESTION 7 EmpName DeptNo JobTitle Salary James 10 Director 5000 Mariah 10 Manager 2450 Muthu 20 Analyst 3000 Sathi 20 Analyst 3000 Leong 20 Clerk 1100 Mohamad 20 Manager 2975 Sharifah 30 Clerk 950 David 30 Manager 2850 Allen Tan 30 SalesExec 1600 Swee Lee 30 SalesExec 1500 Fatimah 30 SalesExec 1250 Maznah 30 SalesExec 1250 RESULT TABLE (a) Data Definition Language (DDL) is used to create database objects and define access rights to the database. It deals with database schema and description, how the data should reside in the database. DDL Commands are: 1. Create 2. Use 3. Alter 4. Drop (b) MIN() MAX() AVG() COUNT() SUM() C H A P T E R 4
P R A C TI C A L E X E R C I S E A N SWE R C H A P T E R 4 QUESTION 8 22 QUESTION 9 (a) SELECT INSERT UPDATE DELETE (b) DISTINCT WHERE AND/OR ORDER BY LIKE & WILCARDS IN/BETWEEN INTERSECT GROUP BY/HAVING QUESTION 10 (a) docNo docName docState docSalary 352 Manav Veer Pahang 10,321.00 625 Nurul Jannah Pahang 11,150.21 (b) INSERT INTO DOCTOR (docNo, docName, docState, docSalary) VALUES (801, 'Amelia Lee', 'Penang', 12500.00), (912, 'Rizal Rahman', 'Johor', 14000.00); (a) SELECT Player_Id, Age FROM Player WHERE Country = ‘France’; (b) SELECT Name, Salary FROM Player ORDER BY Salary ASC; QUESTION 11 (a) SELECT SUM (Quality_of_Book) AS Total_Quantity FROM Book; (b) SELECT Book_Name, Price FROM Book WHERE Book_Name LIKE ‘A%’ ORDER BY Price DESC;
P R A C TI C A L E X E R C I S E A N SWE R QUESTION 12 23 QUESTION 13 (a) (a) Data Retrieval: SQL is used to fetch specific data from a database using SELECT queries. 1. Data Insertion: SQL allows adding new records into a table using the INSERT statement. 2. Data Updating: SQL helps modify existing records in a database using the UPDATE statement. 3. Data Deletion: SQL can remove records from a table using the DELETE statement. 4. SELECT Staff_Name, Staff_State FROM Staff WHERE Staff_Salary > 4500; QUESTION 14 (a) CREATE TABLE Student ( Id_Student VARCHAR (20) PRIMARY KEY, Name VARCHAR (50), Age INT, Sex CHAR (1), State VARCHAR (50) ); CREATE TABLE Lecturer ( ID_Lec INT PRIMARY KEY, Lec_Name VARCHAR (50), Subject VARCHAR (20), State VARCHAR (50), Salary INT ); (b) SELECT * FROM Student WHERE Age = 19 AND State = ‘Kelantan’; (c) SELECT * FROM Lecturer WHERE Salary > 2000; C H A P T E R 4
P R A C TI C A L E X E R C I S E A N SWE R C H A P T E R 4 QUESTION 15 24 QUESTION 16 (a) (a) CREATE TABLE Product ( Prod_ID INT PRIMARY KEY, Prod_Name VARCHAR (50), Prod_Description VARCHAR (50), Price INT ); Feature WHERE Command HAVING Command Definition To filter results from SELECT, INSERT, UPDATE or DELETE commands. To restrict the groups of returned rows to only those who’s the condition is TRUE. It is used in combination with the GROUP BY clause. Syntax SELECT */ column_name FROM table_name1 WHERE conditions; SELECT column_name FROM table_name WHERE conditions GROUP BY expression HAVING condition; Example SELECT * FROM Product WHERE Price > 100; SELECT Prod_Name, AVG (Price) FROM Product GROUP BY Prod_Name HAVING AVG (Prce) > 200; QUESTION 17 (a) Feature DELETE Command TRUNCATE Command Definition Removes specific rows from a table using a condition and logs each deletion. Removes all rows from a table without logging. Example DELETE FROM EMPLOYEE WHERE Department = ‘HR’; TRUNCATE TABLE Employee;
P R A C TI C A L E X E R C I S E A N SWE R QUESTION 18 25 (a) SELECT * FROM Product WHERE Prod_Name LIKE ‘A%’; (b) SELECT * FROM Product WHERE Prod_Name LIKE ‘%A%’; (c) SELECT * FROM Product WHERE Prod_Name LIKE ‘%A’; QUESTION 19 (a) CREATE TABLE Course ( Course_ID INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL, Credits INTEGER CHECK (Credits > 0) ); CREATE TABLE Student ( Stud_ID INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INTEGER CHECK (Age > 0), Gender CHAR(1) CHECK (Gender IN ('M', 'F')), Email VARCHAR(20) UNIQUE NOT NULL ); CREATE TABLE Enrollment ( Enroll_ID INTEGER PRIMARY KEY, Enroll_Date VARCHAR(50) NOT NULL, Stud_ID INTEGER, Course_ID INTEGER, FOREIGN KEY (Stud_ID) REFERENCES Student(Stud_ID) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID) ON DELETE CASCADE ON UPDATE CASCADE ); C H A P T E R 4
P R A C TI C A L E X E R C I S E A N SWE R C H A P T E R 4 26 (c) SELECT C.Course_ID, C.Name AS Course_Name, COUNT(E.Stud_ID) AS Student_Count FROM Course C LEFT JOIN Enrollment E ON C.Course_ID = E.Course_ID GROUP BY C.Course_ID, C.Name; (b) INSERT INTO Student (Stud_ID, Name, Age, Gender, Email) VALUES (1, 'Alice Johnson', 21, 'F', '[email protected]'), (2, 'Bob Smith', 22, 'M', '[email protected]'); INSERT INTO Course (Course_ID, Name, Credits) VALUES (101, 'Database Management', 3), (102, 'Software Engineering', 4); INSERT INTO Enrollment (Enroll_ID, Enroll_Date, Stud_ID, Course_ID) VALUES (1, '2024-02-15', 1, 101), (2, '2024-02-16', 2, 102); QUESTION 19 QUESTION 20 (a) Data Definition Language (DCL) : It is used to create database objects and define access rights to the database. Data Manipulation Language (DML) : It is used to store, modify or update, retrieve and delete data in the database. Data Control Language (DCL) : It deals with providing right, permission and other controls of database system. Transaction Control Language (TCL) : It deals with a transaction within a database. (b) DISTINCT : To remove duplicates from the result set. WHERE : To filter results from SELECT, INSERT, UPDATE and DELETE commands. ORDER BY : To sort the records in result set. By default, it is sorted in ascending. (c) Feature Table Constraints Column Constraints Scope Applies to multiple columns in a table Applies to a single column Definition Location Defined separately at the table level Defined within the column definition. Examples PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK NOT NULL, NULL, UNIQUE, DEFAULT