Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

akhuwat-db-lab-10-DML

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Akhuwat College

Spring 2023

CS-244: Database Systems-Lab


Lab-10 Manual

Manipulating Data Using DML

Introduction to Lab
In this lab, you will learn how to insert rows into a table, update existing rows in a table, and delete
existing rows from a table.

The main topics of this lab include:

1. Data Manipulation Language (DML)


Lab-10 Manual 2023

2. The INSERT Statement Syntax


3. Inserting New Rows
4. Inserting Rows with Null Values
5. Inserting Special Values
6. Creating a Script
7. Changing Data in a Table (The UPDATE Statement)
8. Updating Rows in a Table
9. Updating Rows: Integrity Constraint Error
10. Removing a Row from a Table (The DELETE Statement)
11. Deleting Rows from a Table
12. Deleting Rows Based on Another Table
13. Deleting Rows: Integrity Constraint Error
14. The TRUNCATE Statement

Objectives of this Lab


At the end of this lab, students should be able to:

1. Describe each DML statement


2. Insert rows into a table
3. Update rows in a table
4. Delete rows from a table
5. Merge rows in a table

1. Data Manipulation Language (DML)


Data manipulation language (DML) is a core part of SQL. When you want to add, update, or
delete data in the database, you execute a DML statement.

2. The INSERT Statement Syntax


Add new rows to a table by using the INSERT statement.

In the syntax:
table is the name of the table
column is the name of the column in the table to populate
value is the corresponding value for the column

Page | 1
Lab-10 Manual 2023

Note: This statement with the VALUES clause adds only one row at a time to a table.

3. Inserting New Rows

INSERT INTO departments(department_id,


department_name, manager_id, location_id) VALUES
(70, 'Public Relations', 100, 1700);

Because you can insert a new row that contains values for each column, the column list is not
required in the INSERT clause. However, if you do not use the column list, the values must be listed
according to the default order of the columns in the table, and a value must be provided for each
column.
Note: For clarity, use the column list in the INSERT clause.
Enclose character and date values within single quotation marks; it is not recommended to enclose
numeric values within single quotation marks.

4. Inserting Rows with Null Values


Methods for Inserting Null Values
Method Description

Implicit Omit the column from the column list.

Explicit Specify the NULL keyword in the VALUES list, specify the
empty string ('') in the VALUES list for character strings
and dates.

The MySQL Server automatically enforces all data types, data ranges, and data integrity constraints.
Any column that is not listed explicitly obtains a null value in the new row.

Examples:
Implicit method: Omit the column from the column list.
INSERT INTO departments (department_id, department_name)
VALUES (30, 'Purchasing');

Explicit method: Specify the NULL keyword in the VALUES clause.


INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);

Common errors: that can occur during user input:


 Mandatory value missing for a NOT NULL column

Page | 2
Lab-10 Manual 2023

 Duplicate value violates uniqueness constraint


 Foreign key constraint violated
 CHECK constraint violated
 Data type mismatch
 Value too wide to fit in column
5. Inserting Special Values
You can use functions to enter special values in your table.
INSERT INTO employees (employee_id,
first_name, last_name, email,
phone_number, hire_date, job_id,
salary, commission_pct, manager_id,
department_id) VALUES (113, 'Louis',
'Popp', 'LPOPP', '515.124.4567',
SYSDATE(), 'AC_ACCOUNT', 6900, NULL,
205, 100);

The above example records information for employee Popp in the EMPLOYEES table. It supplies the
current date and time in the HIRE_DATE column. It uses the SYSDATE function for current date and
time.
Confirming Additions to the Table
SELECT employee_id, last_name, job_id, hire_date,
commission_pct FROM employees WHERE employee_id =
113;
6. Creating a Script
MySQL has a powerful scripting language. We can write fairly complex scripts to perform various
tasks with significant ease. We can declare variables of different types and write
procedures/functions that use those variables. We briefly discuss this scripting language and
provide links to dig deeper for those interested in pursuing the topic in more depth.
MySQL scripts may be run in batch mode or through the SOURCE command. The script file
extension is usually .sql but this is not a strict requirement. The following command runs a script
in batch mode.
mysql -u username -p < path-to\scriptName.sql
Save the following lines in a text file named myscript.sql for batch mode execution.
SHOW DATABASES;
USE mysql;
SELECT user, host FROM user;
Enter the following command at the prompt and press Enter.
$ mysql -u root -p < myscript.sql
You will see out similar to the following.

Page | 3
Lab-10 Manual 2023

+--------------------+
| Database |
+--------------------+
| companydb |
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
7 rows in set (0.00 sec)

Database changed
+------------------+-----------+
| user | host |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)
To run the same script file through the SOURCE command, enter the following at MySQL prompt and hit
Enter.
mysql> SOURCE myscript.sql
In both cases you must provide full path of the script file on the command line.
Using Variables
In MySQL, you can define a user variables through SET or SELECT statement:
1. SET @varname = value or (SET @varname := value)

2. SELECT @varname := value ...

3. SELECT columnName INTO @varname ...

For example we can define and assign values to two variables a and b as follows.

Page | 4
Lab-10 Manual 2023

mysql> SET @a := 2, @b := 3;
We can now use these variables in queries. For now let us do some arithmetic with them.
mysql> SELECT @a, @b, @c := @a + @b;
The output is shown below.
+------+------+---------------+
| @a | @b | @c := @a + @b |
+------+------+---------------+
| 2 | 3 | 5 |
+------+------+---------------+
1 row in set, 1 warning (0.00 sec)
Let us declare a variable and then use it in a query.
mysql> SET @mydate = STR_TO_DATE('31 aug 1981','%d %M %Y');
mysql> SELECT * FROM emp WHERE hiredate < @mydate;
+-------+-------+----------+------+------------+---------+--------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+-------+----------+------+------------+---------+--------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
+-------+-------+----------+------+------------+---------+--------+--------+
6 rows in set (0.00 sec)
You can see the effect of the WHERE clause in which the variable mydate was used. Not all rows
were returned. Let us declare two date variables and then list employees whose hire dates fall
between them.
mysql> SET @start_date := STR_TO_DATE('01 jan 1981', '%d %M %Y'),
@end_date := STR_TO_DATE('31 may 1981', '%d %M %Y');
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM emp WHERE hiredate BETWEEN @start_date AND
@end_date;
+-------+-------+----------+------+------------+---------+--------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+-------+----------+------+------------+---------+--------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |

Page | 5
Lab-10 Manual 2023

| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |


| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
+-------+-------+----------+------+------------+---------+--------+--------+
4 rows in set (0.00 sec)
As you can see, fairly complex queries and procedures/functions may be written using variables.
This language has compound statements, flow control statements, stored procedures, local
variables and user-defined functions to name a few.

7. Changing Data in a Table (The UPDATE Statement)


You can modify existing rows by using the UPDATE statement.

In the syntax:

table is the name of the table


column is the name of the column in the table to populate
value is the corresponding value or subquery for the column
condition identifies the rows to be updated and is composed of
column names expressions, constants, subqueries, and
comparison operators

Confirm the update operation by querying the table to display the updated rows.

Note: In general, use the primary key to identify a single row. Using other columns can
unexpectedly cause several rows to be updated. For example, identifying a single row in the
EMPLOYEES table by name is dangerous, because more than one employee may have the same
name.

8. Updating Rows in a Table


The UPDATE statement modifies specific rows if the WHERE clause is specified.
Note: If you omit the WHERE clause, all the rows in the table are modified.

Example:
UPDATE employees
SET department_id = 70

Page | 6
Lab-10 Manual 2023

WHERE employee_id = 113;

Note: All rows in the table are modified if you omit the WHERE clause:

UPDATE copy_emp
SET department_id = 110;

9. Updating Rows: Integrity Constraint Error


If you attempt to update a record with a value that is tied to an integrity constraint, an error is
returned.
In this example, department number 55 does not exist in the parent table, DEPARTMENTS, and so
you receive the parent key violation error.
UPDATE copy_emp SET department_id = 55 WHERE department_id = 90;

Note: Integrity constraints ensure that the data adheres to a predefined set of rules. A subsequent
lab covers integrity constraints in greater depth.

10. Removing a Row from a Table (The DELETE Statement)


You can remove existing rows by using the DELETE statement.

In the syntax:
table is the table name
condition identifies the rows to be deleted and is composed of
column names, expressions, constants, subqueries, and
comparison operators

Note: If no rows are deleted, a message “0 rows deleted.” is returned:

11. Deleting Rows from a Table


You can delete specific rows by specifying the WHERE clause in the DELETE statement.

DELETE FROM departments WHERE department_name = 'Finance';

The above example deletes the Finance department from the DEPARTMENTS table. You can confirm
the delete operation by displaying the deleted rows using the SELECT statement.
SELECT * FROM departments WHERE department_name = 'Finance';

Page | 7
Lab-10 Manual 2023

If you omit the WHERE clause, all rows in the table are deleted. The second example below deletes
all the rows from the COPY_EMP table, because no WHERE clause has been specified.
DELETE FROM copy_emp;

Example:
Remove rows identified in the WHERE clause.
DELETE FROM employees WHERE employee_id = 114;
DELETE FROM departments WHERE department_id IN (30, 40);

12. Deleting Rows Based on Another Table


You can use subqueries to delete rows from a table based on values from another table.
The example below deletes all the employees who are in a department where the department name
contains the string ‘Public’. The subquery searches the DEPARTMENTS table to find the department
number based on the department name containing the string ‘Public’. The subquery then feeds the
department number to the main query, which deletes rows of data from the COPY_EMP table based
on this department number.
DELETE FROM copy_emp WHERE department_id = (SELECT department_id FROM
departments WHERE department_name LIKE '%Public%');

13. Deleting Rows: Integrity Constraint Error


If you attempt to delete a record with a value that is tied to an integrity constraint, an error is
returned.
DELETE FROM departments WHERE department_id = 90;

The above example tries to delete department number 40 from the DEPARTMENTS table, but it
results in an error because department number is used as a foreign key in the COPY_EMP table. If
the parent record that you attempt to delete has child records, then you receive the child record
found violation error.

14. The TRUNCATE Statement


A more efficient method of emptying a table is with the TRUNCATE statement.
TRUNCATE TABLE table_name;

Example:
TRUNCATE TABLE copy_emp;

Note: No rollback is possible after executing the TRUNCATE statement!


Removing rows with the TRUNCATE statement is faster than removing them with the DELETE
statement for the following reasons:

Page | 8
Lab-10 Manual 2023

 The TRUNCATE statement is a data definition language (DDL) statement and generates no
rollback information. Rollback information is covered later in this lab.
 If the table is the parent of a referential integrity constraint, you cannot truncate the table.
You need to disable the constraint before issuing the TRUNCATE statement. Disabling
constraints is covered in a subsequent lab.

The End

Page | 9

You might also like