0% found this document useful (0 votes)
17 views25 pages

SQL Data Manipulation Language Guide

The document provides an overview of SQL Data Manipulation Language (DML), detailing its main commands: SELECT, INSERT, UPDATE, and DELETE for managing database records. It includes syntax examples for each command, as well as explanations of GROUP BY, aggregate functions, and various SQL operators. Additionally, it covers set operators for combining query results and string concatenation methods across different database systems.

Uploaded by

alemsetegn757
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)
17 views25 pages

SQL Data Manipulation Language Guide

The document provides an overview of SQL Data Manipulation Language (DML), detailing its main commands: SELECT, INSERT, UPDATE, and DELETE for managing database records. It includes syntax examples for each command, as well as explanations of GROUP BY, aggregate functions, and various SQL operators. Additionally, it covers set operators for combining query results and string concatenation methods across different database systems.

Uploaded by

alemsetegn757
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

CHapteR two

SQl Data Manipulation language


Introduction
SQL Data Manipulation Language (DML) is used to manipulate and
retrieve data from a database.

DML commands are essential for accessing, transforming, and


analysing data.

The main DML commands include:


1) SELECT – Retrieve data from tables.
2) INSERT – Add new records to a table.
3) UPDATE – Modify existing records.
4) DELETE – Remove records from a table.
1. The SELECT Statement (Retrieving Data)
The SELECT statement fetches data from one or more tables.

It can be used with filtering (WHERE), sorting (ORDER BY), and
grouping (GROUP BY).

Basic Syntax: SELECT column1, column2, ... FROM table_name


WHERE condition;

column1, column2, ... → Specifies which columns to retrieve.

table_name → The table from which to fetch data.

WHERE condition → (Optional) Filters the results.


Examples
i. Retrieve All Data: SELECT * FROM employees;

ii. Retrieve Specific Columns: SELECT name, salary FROM


employees;

iii. Filter Data (WHERE Clause): SELECT name, salary FROM


employees WHERE salary > 5000;

iv. Sorting Results (ORDER BY Clause): Sort employees by salary in


descending order:

SELECT name, salary FROM employees ORDER BY salary


DESC;
2. INSERT Statement (Adding Data)
The INSERT statement adds new records to a table.
 There are multiple ways to use INSERT, depending on whether you're
adding specific values, inserting data from another table, or inserting
multiple rows at once.
 Syntax: INSERT INTO table_name (column1, column2, ...) VALUES
(value1, value2, ...);
 table_name: The name of the table where data will be inserted.
 column1, column2, ... → The columns where values will be
inserted.
 VALUES (value1, value2, ...) → The values to be inserted.
Examples
i. Insert a Single Row: INSERT INTO students (student_id, name, age,
grade) VALUES (101, 'Alice Johnson', 21, 'A');
ii. Insert Multiple Rows:
INSERT INTO students (student_id, name, age, grade) VALUES
(102, 'Bob Smith', 22, 'B'),
(103, 'Charlie Brown', 20, 'A'),
(104, 'Diana Prince', 23, 'B+');
iii. Insert Data Without Specifying Columns: If inserting values into all
columns in order, you can omit column names:
INSERT INTO students
VALUES (105, 'Edward Norton', 24, 'A-');
 Note: This requires that values match the exact order of the columns in the table.
Continued..
iv. Insert Data from Another Table: You can insert data from another
table using a SELECT statement.

INSERT INTO graduates (student_id, name, graduation_year)

SELECT student_id, name, 2025 FROM students WHERE grade =


'A';

v. Insert with Default Values: This assumes other columns have


default values or allow NULLs. If some columns have default
values, you can insert partial data:

INSERT INTO employees (name, department) VALUES ('John


Doe', 'IT');
3. UPDATE Statement (Modifying Data)
The UPDATE statement modifies existing records in a table.

Syntax:

 UPDATE table_name SET column1 = value1, column2 = value2


WHERE condition;

SET column1 = value1 → Defines the changes.

WHERE condition → Specifies which rows to update.


Examples:
1. Increase Salary of Employees in HR by 10%
UPDATE employees SET salary = salary * 1.10 WHERE
department = 'HR';
2. Change Employee Department
UPDATE employees SET department = 'Marketing' WHERE name
= 'Alice';
3. Increase Salary for All Employees
UPDATE employees SET salary = salary + 500;
Note: Without a WHERE clause, all records in the table will be
updated.
4. DELETE Statement (Removing Data)
The DELETE statement removes records from a table.

Syntax:

 DELETE FROM table_name WHERE condition;

WHERE condition → Specifies which rows to delete.


Examples:
1. Delete a Specific Employees

DELETE FROM employees WHERE name = 'Bob';

2. Delete All Employees in a Department

DELETE FROM employees WHERE department = 'Sales';

Note: Omitting WHERE will delete all records.

 DELETE FROM employees; -- Deletes all rows!

3. Delete Employees with Salary Below 4000

DELETE FROM employees WHERE salary < 4000;


5. GROUP BY (Grouping and Aggregation)
The GROUP BY clause groups rows that have the same values in
specified columns.

It is often used with aggregate functions.

Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name GROUP BY column_name;

aggregate_function(column_name) → Performs calculations like


COUNT(), SUM(), AVG(), MIN(), MAX().
Examples:
1. Count Employees in Each Department

SELECT department, COUNT(*) FROM employees GROUP BY


department;

2. Find Average Salary Per Department

SELECT department, AVG(salary) FROM employees GROUP BY


department;

3. Get Maximum Salary in Each Department

SELECT department, MAX(salary) FROM employees GROUP BY


department;
6. Aggregate Functions (Mathematical Calculations)
Aggregate functions operate on a set of values and return a single result.
Function Description
COUNT()  It counts the number of rows.
 Ex: Count the Number of Employees
SELECT COUNT(*) FROM employees;
SUM()  Returns the sum of values
 Ex: Find Total Salary Paid to Employees
SELECT SUM(salary) FROM employees;
AVG() Returns the average value
MIN()  Returns the smallest value
 Ex: Find Minimum and Maximum Salary
SELECT MIN(salary), MAX(salary) FROM employees;
MAX()  Returns the largest value
7. SQL Operators
A. Arithmetic Operators

Operator Description Example

+ Addition SELECT 10 + 5; → Returns 15

- Subtraction SELECT 10 - 5; → Returns 5

* Multiplication SELECT 10 * 5; → Returns 50

/ Division SELECT 10 / 5; → Returns 2

% Modulus (Remainder) SELECT 10 % 3; → Returns 1

 Example: Calculate new salary with a 10% bonus:


SELECT name, salary, salary * 1.10 AS new_salary FROM employees;
Cont.….
B. Comparison Operators: Used to compare values in SQL queries.

Operator Description Example


Equal to SELECT * FROM employees WHERE salary = 5000;
=
Not equal to SELECT * FROM employees WHERE salary <> 5000;
!= or <>
Greater than SELECT * FROM employees WHERE salary > 5000;
>
Less than SELECT * FROM employees WHERE salary < 5000;
<
Greater than or equal to SELECT * FROM employees WHERE salary >= 5000;
>=
Less than or equal to SELECT * FROM employees WHERE salary <= 5000;
<=

 Example: Find employees earning more than 6000:

SELECT name, salary FROM employees WHERE salary > 6000;


Cont.….
C. Logical Operators: Used to combine multiple conditions in WHERE clauses.
Operator Description Example

AND Both conditions must be SELECT * FROM employees WHERE


department = 'IT' AND salary > 5000;
true
OR At least one condition SELECT * FROM employees WHERE
department = 'IT' OR department = 'HR';
must be true
NOT Negates a condition SELECT * FROM employees WHERE
NOT department = 'Sales';

 Example: Find employees in IT with salaries above 5000:


SELECT * FROM employees WHERE department = 'IT' AND salary > 5000;
Cont.….
D. Set Operators (Combining Query Results):

Set operators in SQL allow you to combine the results of


two or more SELECT queries into a single result set.

The main set operators are:


 UNION – Combines results and removes duplicates.

 UNION ALL – Combines results and keeps duplicates.

 INTERSECT – Returns only common rows between queries.

 EXCEPT (or MINUS in Oracle) – Returns rows from the first query that are
not in the second query.
Cont.….
1. UNION (Removes Duplicates)
The UNION operator merges the results of two or more SELECT statements and
automatically removes duplicate rows.

Syntax: SELECT column1, column2 FROM table1 UNION SELECT column1,


column2 FROM table2;

Example: Retrieve a unique list of employee names from employees and managers
tables:
 SELECT name FROM employees UNION SELECT name FROM managers;

Key Points:
 Both SELECT statements must have the same number of columns.
 The corresponding columns must have compatible data types.
 The result set does not contain duplicate rows.
Cont.….
2. UNION ALL (Keeps Duplicates)
The UNION ALL operator merges results from multiple SELECT
queries without removing duplicates.

Syntax: SELECT column1, column2 FROM table1 UNION ALL


SELECT column1, column2 FROM table2;

Example: Retrieve all employee names, including duplicates:

SELECT name FROM employees UNION ALL SELECT name


FROM managers;
Cont.….
3. INTERSECT (Common Rows)
The INTERSECT operator returns only the rows that are common between the two
queries.

Syntax: SELECT column1, column2 FROM table1 INTERSECT SELECT


column1, column2 FROM table2;
Example: Find employees who are also listed as managers:
 SELECT name FROM employees INTERSECT SELECT name FROM
managers;

 Not supported in MySQL (but can be simulated using INNER JOIN or


EXISTS).

 Alternative for MySQL: SELECT name FROM employees WHERE name


IN (SELECT name FROM managers);
Cont.….
4. EXCEPT (or MINUS in Oracle)
The EXCEPT operator returns rows from the first query that do not appear in the
second query.
Syntax: SELECT column1, column2 FROM table1 EXCEPT SELECT column1,
column2 FROM table2;
Example: Find employees who are not managers:
 SELECT name FROM employees EXCEPT SELECT name FROM managers;

 EXCEPT is not supported in MySQL, but you can use LEFT JOIN to achieve
the same result:

 Alternative for MySQL: SELECT [Link] FROM employees e LEFT


JOIN managers m ON [Link] = [Link] WHERE [Link] IS NULL;
Cont.….
E. Concatenation Operator in SQL
Concatenation operators are used to join two or more string values together in SQL.
The way concatenation is done depends on the database system you are using.
 In Oracle, the | | operator is used to concatenate strings.
 Example: SELECT first_name || ' ' || last_name AS full_name FROM
employees;
 SQL Server uses the + operator for string concatenation.
 Example: SELECT first_name + ' ' + last_name AS full_name FROM
employees;
 Important Note: If any column contains NULL, the result will be NULL. To
avoid this, use the COALESCE() function:
 SELECT COALESCE(first_name, '') + ' ' + COALESCE(last_name, '') AS
full_name FROM employees;
 MySQL and PostgreSQL use the CONCAT() function.
 Ex: SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Cont.….
F. SQL EXISTS Operator in SQL
The EXISTS operator is used in SQL to check whether a subquery returns any rows.
 If the subquery returns at least one row, EXISTS evaluates to TRUE; otherwise, it
evaluates to FALSE.
Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS (
SELECT 1 FROM another_table WHERE condition );
Example 1: Find employees who belong to a department:
 SELECT name FROM employees WHERE EXISTS ( SELECT 1 FROM
departments WHERE employees.department_id = [Link] );
Example 2: Find students who have enrolled in a course:
 SELECT student_name FROM students WHERE EXISTS ( SELECT 1
FROM enrollments WHERE students.student_id = enrollments.student_id );

You might also like