0% found this document useful (0 votes)
7 views11 pages

Lab2 DML

The document provides an overview of Data Manipulation Language (DML) in SQL, detailing commands such as SELECT, INSERT, UPDATE, and DELETE for managing database records. It includes examples of how to create tables, execute basic queries, and utilize various SQL functions and operators for data retrieval and manipulation. Additionally, it covers advanced topics like aggregate functions, grouping, and sorting results using ORDER BY and HAVING clauses.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Lab2 DML

The document provides an overview of Data Manipulation Language (DML) in SQL, detailing commands such as SELECT, INSERT, UPDATE, and DELETE for managing database records. It includes examples of how to create tables, execute basic queries, and utilize various SQL functions and operators for data retrieval and manipulation. Additionally, it covers advanced topics like aggregate functions, grouping, and sorting results using ORDER BY and HAVING clauses.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

DATA MANIPULATION language LAB 2 SQL

LAB Experiment 2
DATA MANIPULATION LANGUAGE (DML):
DML(Data Manipulation Language) : The SQL commands that deals with the manipulation of
data present in database belong to DML or Data Manipulation Language and this includes most
of the SQL statements. DML is used to retrieve, insert and modify database information. These
commands will be used by all database users during the routine operation of the database.
Examples of DML:
 SELECT – is used to retrieve data from the database.
 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.
Consider the following employee table
CREATE TABLE EMPLOYE
(
ssn int unique identity(1,1),
fname varchar (20) not null,
mname char (20) not null,
lname varchar (20) not null,
bdate date not null,
location varchar(13) not null default 'burie',
sex char not null,
salary decimal(8,4) ,
super_ssn int not null default '1' ,
primary key (ssn),
DNO INT NOT NULL,
);

Let's take a brief look at the basic DML commands:


1. INSERT 2. SELECT 3. UPDATE 4. DELETE
1. INSERT INTO: This is used to add records into a relation. These are three type of
INSERT INTO queries which are as
Inserting a single record
Syntax: INSERT INTO < relation/table name> (field_1,field_2……field_n)VALUES
(data_1,data_2,........data_n);
Example: INSERT INTO student (stuId, lastName ,firstName ,sex)VALUES
(1,’abebe’,’arega’,’M’);

Example: recording employee data for created employee table based on employee table

INSERT INTO EMPLOYEE values('ayisheshim', 'A', 'almaw', '1991-03-13', 'BURIE', 'M',


10445.80,'165', 1);
INSERT INTO EMPLOYEE values('BIKILA', 'B', 'ALEMU', '1991-03-13', 'markos', 'M',
13445.80,'165', 3);
INSERT INTO EMPLOYEE values('amin', 'c', 'tune', '1989-01-13', 'fenote selam', 'M',
15445.80,'165', 3);
INSERT INTO EMPLOYEE values('getahun', 'A', 'tigstu', '1984-07-23', 'bahirdar', 'M',
10445.80, '165', 2);
Inserting all records from another relation
Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n

1
DATA MANIPULATION language LAB 2 SQL

FROM relation_name_2 WHERE field_x=data;

Example1 : INSERT INTO student SELECT Dept_name FROM employee


WHERE FirstName = ‘arega‘;

SELECT:-

SELECT extracts data from a database table. The SELECT statement is the core command to
access data in SQL Server. The main components of a SELECT statement are:
 Column listing - either specific columns or * (SELECT list)
When * is specified, then all columns from the tables included in the FROM
clause are included
 Table listing (FROM clause)
 Filter logic (WHERE clause)
 Summarize values (GROUP BY)
 Filters the GROUP BY values (HAVING)
 Sorting logic (ORDER BY)
SELECT can be combine with other statements to do the following:
 Joining data from multiple tables to build a single result set
 INSERT with a SELECT statement to add records into an existing table
 SELECT...INTO statement to create a new table based on the column list specification
and enter records into the new table
 UNION or UNION ALL command to have multiple set of logic returned in a single
result set
Examples: all examples are based employee table done on lab1 as an assignment.
Basic SELECT Statement:-
SELECT FROM
. If you want to select all the fields available in the employee table, use the following syntax:
SELECT * FROM table_name;
SELECT * FROM EMPLYEE;
The result will be generated as below all recorded employee.
Output1 u can view the result

If you want to select some selected fields available in the employee table, use the following
syntax:

SELECT column1, column2, ...


FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data from the
table. Table name is the name table specified in the database (emplyee)

Example:- select employee name and it’s department number

2
DATA MANIPULATION language LAB 2 SQL

Select fname,Dno from employee;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to
list the different (distinct) values.

As it is observed from output 1 and 2 there are 11 records but output 3 shows only 10 records.
From row 3 and 4 on output 1 and 2 employee name Ayisheshim is recorded 2 times but on
output 3 is only once due to DISTINICT.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2,
FROM table_name;
Example: Select DISTINCT fname,Dno from employee;
SQL SELECT.FROM-WHERE Clause
SELECT-FROM-WHERE:- The WHERE clause is used to filter records based on certain
condition. The WHERE clause is used to extract only those records that fulfill a specified
condition.
Where syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: below is a selection from the "employee" table which are working on department
number 5 only
SELECT * FROM employee
WHERE Dno='5';

Output

Operators in the WHERE Clause


The following operators can be used in the WHERE clause:
The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators. The AND and OR
operators are used to filter records based on more than one condition:

 The AND operator displays a record if all the conditions separated by AND is TRUE.

3
DATA MANIPULATION language LAB 2 SQL

 The OR operator displays a record if any of the conditions separated by OR is TRUE.


 The NOT operator displays a record if the condition(s) is NOT TRUE.
Examples:

 Retrieve the birthdate and address of the employee(s) whose name is ‘Ayisheshim A
almaw’
SELECT BDATE, location FROM EMPLOYEE
WHERE FNAME = 'ayisheshim' AND Minit = 'A' AND Lname = 'Almaw';
 The following SQL statement selects all employee(s) that are located in "burie ".
SELECT * FROM EMPLOYEE
WHERE location IN (' location ');
 The following SQL statement selects all EMPLYEES that are NOT located in "burie ".
SELECT * FROM EMPLOYEE
WHERE location NOT IN (' burie ');
OR Example
The following SQL statement selects all fields from "EMPLOYEE" where Address SELECT *
FROM EMPLOYEE
WHERE location ='burie' OR location ='osis';
The following table represents some of the Operators used in the WHERE Clause

Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column

The SQL BETWEEN Operators

The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates. The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

4
DATA MANIPULATION language LAB 2 SQL

 The following SQL statement selects all employees with a salary BETWEEN 7000.0 and
10445.80:
SELECT * FROM employee
WHERE SALARY BETWEEN 7000.0 AND 10445.80;
BETWEEN Text Values: - The following SQL statement selects all employees with a Minit
BETWEEN 'A' and 'B':
SELECT * FROM employee
WHERE Minit BETWEEN 'A' AND 'C'
The SQL LIKE Operator:- The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column. There are two wildcards used in conjunction with the LIKE
operator:

 ‘%’ The percent sign represents zero, one, or multiple characters


 ‘_ ‘The underscore represents a single character

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE Fname LIKE 'a%' Finds any values that start with "a"

WHERE Fname LIKE '%a' Finds any values that end with "a"

WHERE Fname LIKE '%or%' Finds any values that have "or" in any position

WHERE Fname LIKE '_r%' Finds any values that have "r" in the second position

WHERE Fname LIKE 'a_%_%' Finds any values that start with "a" and are at least 3
characters in length

5
DATA MANIPULATION language LAB 2 SQL

WHERE Fname LIKE 'a%o' Finds any values that start with "a" and ends with "o"

SQL LIKE Examples

 The following SQL statement selects all employees with a Fname starting with "a":
SELECT * FROM employee
WHERE Fname LIKE 'a%';

 The following SQL statement selects employees with a Fname ending with "a":

SELECT * FROM employee


WHERE Fname LIKE '%a';
BETWEEN Dates Example

The following SQL statement selects all employees with birthdate BETWEEN '12-09-1980' and
'31-07-1989':

SELECT * FROM EMPLOYEE


WHERE Bdate BETWEEN '1980-09-12' AND '1989-07-12';

Combining AND, OR, NOT and between


Example: - Retrieve all employees in department 5 whose salary is between '6000' AND '12000'
SELECT *
FROM EMPLOYEE
WHERE (SALARY BETWEEN '9000' AND '12000') AND DNO = '5';

Aggregate Functions and group by


These functions operate on the multiset of values of a column of a relation, and return a value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Example: let’s see with example step by step
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

6
DATA MANIPULATION language LAB 2 SQL

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Example:-
SELECT MIN(Salary) AS 'Smallest salary'
FROM EMPLOYEE;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
SELECT MAX(Salary) AS 'max salary'
FROM EMPLOYEE;

SQL COUNT
Example 2:- Find the number of tuples in the employee relation.
select count (*)
from employee1
Ex. Find the maximum salary, the minimum salary, and the average salary among all employees
for the Company database
SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Find the maximum salary, the minimum salary, and the average salary among employees who
work for the 'IT' department.
SELECT MAX(SALARY), MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='IT'
GROUP BY
GROUP BY: This query is used to group to all the records in a relation together for each
and every value of a specific key(s) and then display them for a selected set of fields the
relation.
 In many cases, we want to apply the aggregate functions to subgroups of tuples in a
relation
 Each subgroup of tuples consists of the set of tuples that have the same value for the
grouping attribute(s)

7
DATA MANIPULATION language LAB 2 SQL

 The function is applied to each subgroup Independently SQL has a GROUP BY-clause for
specifying the grouping attributes, which must also appear in the SELECT-clause
Note: Attributes in select clause outside of aggregate functions must appear in group by list
Syntax: SELECT <set of fields> FROM <relation_name>
GROUP BY <field_name>;
Example: For each department, retrieve the department number, the number of employees in the
department, and their average, minimum, maximum and sum salary.
SELECT DNO, COUNT (*), AVG (SALARY), sum (SALARY), min (SALARY), max
(SALARY)
FROM EMPLOYEE
GROUP BY DNO
 The EMPLOYEE tuples are divided into groups--each group having the same value for
the grouping attribute DNO
 The COUNT and AVG functions are applied to each such group of tuples separately
 The SELECT-clause includes only the grouping attribute and the functions to be applied
on each group of tuples
GROUP BY-HAVING : The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. The HAVING clause must follow the
GROUP BY clause in a query and must also precede the ORDER BY clause if used.
Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

1. Find the average salary for each department


SELECT Dept, Avg(Salary) AS AvgSal
FROM Employee
GROUP-BY Dept
2. For each project, retrieve the project number, project name, and the number of employees who
work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
In this case, the grouping and functions are applied after the joining of the two relations
 sometimes we want to retrieve the values of these functions for only those groups that satisfy
certain conditions
 The HAVING-clause is used for specifying a selection condition on groups
 Rather than on individual tuples!

8
DATA MANIPULATION language LAB 2 SQL

Example: For each project on which more than two employees work, retrieve the project number,
project name, and the number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2
Note: All aggregate operations except count(*) ignore tuples with null values on the aggregated
attributes.
The SQL ORDER BY Keyword
The ORDER BY clause is used to sort the tuples in a query result based on the values of some
attribute(s). it may specify desc for descending order or asc for ascending order, for each
attribute;. Ascending order is the default.

 The ORDER BY keyword is used to sort the result-set in ascending or descending order.
 The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

ORDER BY Several Columns


SELECT * FROM TABLE NAME
ORDER BY COLUMN1, COLUMN2;

Example: Retrieve a list of employees and the projects each works in, ordered by the employee's
department, and within each department ordered alphabetically by employee last name.
SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE,
WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME
Summary of SQL Queries
 A query in SQL can consist of up to six clauses, but only the first two, SELECT and
FROM, are mandatory.
 The clauses are specified in the following order:
SELECT <attribute list>

9
DATA MANIPULATION language LAB 2 SQL

FROM <table list>


[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]

In general:
 The SELECT-clause lists the attributes or functions to be retrieved
 The FROM-clause specifies all relations (or aliases) needed in the query but not those needed
in nested queries
 The WHERE-clause specifies the conditions for selection and join of tuples from the relations
specified in the FROM-clause
 GROUP BY specifies grouping attributes
 HAVING specifies a condition for selection of groups
 ORDER BY specifies an order for displaying the result of a query
 A query is evaluated by first applying the WHERE-clause, then
 GROUP BY and HAVING, and finally the SELECT-clause

UPDATE
UPDATE-SET-WHERE: This is used to update the content of a record in a relation.
Syntax: SQL>UPDATE relation name SET Field_name1=data,field_name2=data,
WHERE field_name=data;
Example: SQL>UPDATE employee SET fname = ‘bogale’ WHERE ssn=165;

DELETE

DELETE-FROM: This is used to delete all the records of a relation but it will retain the structure
of that relation.
a) DELETE-FROM: This is used to delete all the records of relation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM employee;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.
Syntax: DELETE FROM relation_name WHERE condition;

Example: DELETE FROM employee WHERE ssn = 166;

SQL Aliases

10
DATA MANIPULATION language LAB 2 SQL

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often
used to make column names more readable. An alias only exists for the duration of the query.

 The AS command is used to rename a column or table with an alias.

Alias Column Syntax


SELECT column_name AS alias_name FROM table_name;
Example: Find the maximum salary, the minimum salary, and the average salary among
employees who work for the 'IT' department.
SELECT MAX(SALARY) AS ‘max salary, MIN(SALARY) AS ‘min salary,
AVG(SALARY) AS ‘avg salary
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='IT'
Alias Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
SELECT fname, pname,address
FROM Employee AS E, project AS P
WHERE DNO=DNUMBER AND DNAME='IT'
In general:-
Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

11

You might also like