DML COMMANDS
insert
INSERT INTO STATEMENT IS USED TO INSERT NEW
RECORDS IN A TABLE.
ITS SYNTAX IS:
INSERT INTO TABLENAME VALUES(VALUE 1, VALUE
2,....); HERE, VALUE 1 CORRESPONDS TO
AT TRIBUTE 1, VALUE 2 CORRESPONDS TO
AT TRIBUTE 2 AND SO ON.
NOTE THAT WE NEED NOT HAVE TO SPECIFY
AT TRIBUTE NAMES IN THE INSERT STATEMENT IF
THERE ARE EXACTLY THE SAME NUMBERS OF
VALUES IN THE INSERT STATEMENT AS THE TOTAL
NUMBER OF AT TRIBUTES IN THE TABLE
Insert
IF WE WANT TO INSERT VALUES ONLY FOR SOME OF
THE AT TRIBUTES IN A TABLE (SUPPOSING OTHER
AT TRIBUTES HAVING NULL OR ANY OTHER DEFAULT
VALUE), THEN WE SHALL SPECIFY THE AT TRIBUTE
NAMES IN WHICH THE VALUES ARE TO BE INSERTED
USING THE FOLLOWING SYNTAX OF INSERT INTO
STATEMENT.
SYNTAX: INSERT INTO TABLENAME (COLUMN1,
COLUMN2, ...) VALUES
(VALUE1, VALUE2, ...);
1)Write a SQL query to insert a new product into the products table, which has the
columns product_name, price, and discounted_price. The discounted_price should
be calculated as 10% off the price using an arithmetic expression."
INSERT INTO products (product_name, price, discounted_price)
VALUES ('Bluetooth Speaker', 50.00, 50.00 * 0.9);
2)Write an SQL query to insert a new employee with the
following details:
•EmpID: 105
•Name: 'Ravi Kumar'
•Email: Unknown at the time of entry
3)Can you use DEFAULT values while inserting data? Give an example.
➤ Yes.
INSERT INTO Orders (OrderID, Status) VALUES (101, DEFAULT);
"Imagine you have a list of student grades on paper. One student improved their marks
—
Instead of rewriting the whole list, you just correct that one student's grade.
In SQL, we use UPDATE to do the same thing in a database."
The UPDATE statement is used to make such
modifications in existing data
Syntax: UPDATE table_name SET attribute1 = value1,
attribute2 = value2, ... WHERE condition;
Suppose we have a table called Students:
id name grade
1 John 85
2 Sarah 90
Change John's grade to 95.
"What happens if we forget the WHERE?"
Answer: It will update every student!
"Always use a WHERE clause when updating unless
you truly want to update everything!"
In a table called Students (id, name, grade), update the
grade of the student
with id = 5 to 90.
In a table called Products (id, name, price, stock),
update the price to 50 and
the stock to 100 for the product with id = 3.
e a column to NULL in SQL — it's super useful when you want to "erase" a va
t deleting the entire record.
mployee
employee_id name phone_number
1 John 1234567890
2 Sarah 9876543210
You want to remove Sarah's phone number (set it to NULL).
Customers
table:
customer_id name phone address
1 Alice 5551234 Street 1
2 Bob 5555678 Street 2
Set one column to NULL SET column = NULL
You want to clear both phone and address for Bob.
Users table, remove wrong birthdates (e.g., before 1900).
UPDATE Users
SET birthdate = NULL
WHERE birthdate < '1900-01-01';
UPDATE with Expressions or
Formulas
1)Increase salary by 10% for
all employees
2)Change the final price of products table using the formula final _price
= price - (price * discount_percent / 100)
Ans)UPDATE Products
SET final _price = price - (price * discount_percent / 100);
3)in a Products table, apply 18% tax to all prices.
Ans UPDATE Products
SET tax = price * 1.18;
consider a database table called customers with a column
customer_name that stores the names of all customers.
You need to update the customer_name for all customers by adding the
prefix "VIP - " to each customer's name. Which SQL query would
accomplish this task?
A) UPDATE customers
SET customer_name = 'VIP - ' + customer_name;
•DELETE is used to remove rows from a table.
syntax
DELETE
•It doesFROM
NOTtable_name
remove the table itself, just the data inside.
WHERE condition;
•After a DELETE, the row is gone forever (unless there’s a
backup).
1) deletes the student whose ID is 101.“
2) Delete all students whose grade is “F”
3) Delete all data
4) Write a DELETE query to remove employees who have salary less
than 2000.“
5) This deletes all employees with a salary less than 2000.
6) This deletes all customers who don't have a phone number.
7) This deletes all employees with a salary less than 2000.
TRUNCATE is used to quickly remove all rows from a table —
but the table itself remains.
It’s like "emptying" the table completely without deleting the table itself.
This removes all student records, but keeps the Students table ready
to add new students.
Syntax :- TRUNCATE TABLE table_name;
Write the correct SQL command to remove all rows from the Products
table using TRUNCATE.
What is the main difference between DELETE and TRUNCATE
commands?
•DELETE is a Data Manipulation Language (DML) command used to
remove specific rows from a table based on a condition (using the
WHERE clause). If no WHERE clause is specified, it removes all rows.
Each row deletion is logged individually.
•TRUNCATE is a Data Definition Language (DDL) command used to
remove all rows from a table. It does not support a WHERE clause.
SELECT Statement The SQL statement SELECT is used
to retrieve data from the tables in a database and the
output is also displayed in tabular form.
Syntax: SELECT attribute1, attribute2, ... FROM
table_name WHERE condition
Sorting with ORDER BY
SELECT * FROM books ORDER BY price
DESC;
To select all the data available in a table, we use the
following select statement:
SELECT * FROM table_name;
Filtering with WHERE
SELECT * FROM books WHERE price > 400;
Use examples like:
Books cheaper than 400.
Books written by "Jane Smith".
Selecting Unique Values with DISTINCT
SELECT DISTINCT author FROM books;
Interactive Practice
Let them try small queries:
•List all book titles.
•Show all books with price below 500.
•Get all unique authors.
•Sort books by title.
Operators you can use:
•=, !=, <, >, <=, >=
•BETWEEN, LIKE, IN, IS NULL
bookid title author price genre pub_year fine
B001 SQL Basics John Carter 300 Education 2020 NULL
Learning
B002 Jane Smith 450 Education 2019 20
MySQL
Deep
B003 Ali Hassan 800 Technology 2021 30
Learning
Python for
B004 Jane Smith 600 Programming 2022 10
Data
Web Dev
B005 Nina George 550 Web 2018 NULL
Essentials
Machine
B006 Learning John Carter 900 Technology 2023 40
Now
[Link] all books where the price is greater than 500.
2. Show all books not written by ‘Jane Smith’.
3. Display books published in or after 2020.
4. Find books where the price is exactly 450.
5. Show books where the fine is not equal to 10.
6 List books where the genre is either “Technology” or “Programming”.
7 Find books with missing fine values.
8 Show books where a fine is present (not NULL).
9 Find books with price between 400 and 800.
10Find books where the price is greater than 600 and the fine is NULL.
11Find books that are not by 'Jane Smith' and have price less than 700.
12List books published between 2019 and 2022, and the fine is not NULL.
13 Show books where:
Price is greater than 400
Genre is not 'Education'
Fine is either NULL or greater than 20
14 )List books where:
•The genre is either ‘Programming’, ‘Technology’
•But the price is not between 500 and 900
15) Show all books:
Where the title ends with 'Data' or starts with 'Machine'
AND fine is not NULL
16) Display books where:
Author is in ('John Carter', 'Jane Smith')
Genre is NOT ‘Technology’
AND fine is either NULL or less than 30
17) List books where:
•Fine is greater than 10
operator BETWEEN
In SQL, the BETWEEN operator filters the result set within a certain range. It is inclusive, meaning
it includes the boundary values.
The NOT BETWEEN operator is used to filter the result set outside of a certain range
SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Value1 is the lower bound.
Value 2 is the upper bound.
Both value1 and value2 are included in the result.
.
Table: Employees
EmployeeID Name Age Salary JoinDate
1 Alice 25 30000 2022-01-10
2 Bob 32 45000 2023-03-15
3 Charlie 29 52000 2024-06-20
4 David 45 60000 2021-11-05
5 Eva 38 70000 2023-12-01
Q1. Retrieve employees whose salaries are between 40,000 and 60,000.
Q2. Find employees who joined the company outside the year 2023.
Q3. List employees whose age is not between 30 and 40.
[Link] employees whose names are alphabetically between 'B' and 'E'.
Q5Which employees have salaries not between 50,000 and 70,000?
[Link] all employees who joined the company between 2022 and 2024.
Membership operator IN The IN operator
compares a value with a set of values and
returns true if the value belongs to that set
syntax
The IN operator is used to match a column's value against a list of specific values.
The NOT IN operator is used to exclude rows that match any value in the list.
🔹 IN Syntax
SELECT column_name FROM table_name
WHERE column_name IN (value1, value2, value3, ...);
Employees
EmployeeID Name Department Age Salary
1 Alice HR 25 30000
2 Bob IT 32 45000
3 Charlie Finance 29 52000
4 David Marketing 45 60000
5 Eva IT 38 70000
1) Select employees from IT and Finance departments
2)find employees aged 25, 32, or 45
3)Select employees not in the HR or Marketing departments
4) Find employees whose age is not 29 or 38
5) Get names of employees from HR or Finance who have a salary between 40,000 and 60,000.
6) Find employees not in the IT or Marketing departments who joined between 2022 and 2024.
7) List employees aged between 30 and 45 who are not from HR or Finance.
Many a times we come across situations where we do not want to query by matching exact
text or value. Rather, we are interested to find matching of only a few characters or values in
column values. For example, to find out names starting with “T”
SQL provides a LIKE operator that can be used with the WHERE clause to search for a
specified pattern in a column.
The LIKE operator makes use of the following two wild card characters:
% (per cent)- used to represent zero, one, or multiple characters
_ (underscore)- used to represent exactly a single character
It's commonly used in SELECT, UPDATE, or DELETE statements with WHERE.
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
Example: ‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character
‘B’ ‘_ _ _’ represents any 3 letter string.
A pattern is case sensitive and can be used with LIKE operator.
mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE ‘%Kumar%’
Students
Customers:
ID Name Grade City
1 Alice A London
2 Bob B Liverpool
3 Amanda A Leeds
4 Brian C London
5 Andy B Leeds
Find students whose names start with 'A' and who got Grade 'A‘
Find students whose names end with 'n' and live in London
Sql
Find students whose names contain 'an' and have Grade 'B‘
Names that have 5 letters and grade is A
Names that contain 'll' and are in Grade B
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE column_name LIKE pattern;
Table name employee
Suppose you have a table called customers and
you want to update the status to 'inactive' for all
customers whose names start with 'A':
Delete names with a single character between 'J' and 'hn‘
Delete names that start with 'J' and have any 3 characters after
Delete all customers whose name ends with 'Johnson‘
Handling NULL Values
SQL supports a special value called NULL to represent a missing or unknown value
NULL is used to represent such unknown values. It is important to note that NULL
is different from 0 (zero). Also, any arithmetic operation performed with NULL value gives NULL. For example: 5 +
NULL = NULL
Write a query selects details of all those employees who have not been given a bonus.
Employees:
ID Name Department
1 Alice HR
2 Bob NULL
null null IT
4 David NULL
1)Find employees with no department assigned
2) Get all employee details without an id
3) Remove all records where the name is missing.
4) Assign department 'General' to employees with no department
Write a query to select the names of all employees who have been given a bonus and work in
the department D01
SELECT Name FROM EMPLOYEE WHERE Bonus IS NOT NULL AND DeptID = ‘D01’;
Sql Aliases
SQL Aliases are temporary names assigned to a table or a column for the purpose of a particular
SQL query. They are useful for providing a shorthand method of referencing columns or tables
You can rename a table or a column temporarily by giving another name known as alias..
The renaming is a temporary change and the actual table name does not change in the
database.
. Syntax:
SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];
SELECT column_name AS alias_name
SELECT
FROM CONCAT(firstname, ' ', lastname) AS FullName, mark FROM Students;
table_name;
Select all students' names and grades, but rename the grade column to Score.
Show the first name and last name of employees, but rename the columns
as Name and Surname
Display the product name and price, and show the price as Cost
display name and the yearly salary of employees (monthly salary × 12), and label it as annual salary
.
Name Grade
Alice A
Bob B
Charlie C
David D
Emma A
B.
Show the Name, Grade, and a column called Status which shows "Pass"
for Grade A orB.
SELECT Name, Grade, 'Pass' AS Status
FROM students WHERE Grade LIKE 'A' OR Grade LIKE 'B';
Name Grade Status
Alice A Pass
Bob B Pass
Emma A Pass
Aggregate functions
Max()
min()
Sum()
Avg()
Count()
Count(*)
RollNo Name Class Section Marks Gender
1 Rahul 12 A 85 M
2 Priya 12 A 92 F
3 Ankit 12 B 76 M
4 Sneha 12 B 89 F
5 Manish 12 A NULL M
6 Riya 12 B 81 F
7 Nikhil 12 A 90 M
[Link] the total number of students.
[Link] the total number of male students who have scored marks (i.e., Marks is not
NULL).
[Link] the total sum of marks scored by all students.
[Link] is the average marks of all students who have marks?
[Link] is the highest and lowest mark among all students?
Group by
•Find the average marks scored in each section.
•Find the number of students in each section.
•Display the highest marks obtained by students in each section.
•Find the number of students by gender.
•Display the total marks scored by students grouped by gender.
•Count the number of male students who have submitted marks.
•Find the total number of students who scored more than 80.
•Find the average marks of female students only.
•Find the total marks of Section 'A' students where marks are above 85.
•Display number of students in each section having average marks greater than 80.
Group by
A feature to display data in groups
It groups rows that have same values often used with aggregate functions
Group by is used along with select statement
Group by is placed after where clause in sql
Where clause is used to place conditions on selected column where as having clause place
condition on groups created by aggregate function
having is placed after group by clause
1)write a query to find number of employees in each department
2)write a query to display number of employees in each department sort in
ascending order
3)write a query to display sum of salaries of all employees from each
department
4)Find the average salary of all employees in each department
5)select max, min salary from each department
6)write a query to find the number of employee in each department location
wise
Clause When to Use Applies To
WHERE Before grouping (raw rows) Individual records
To perform aggregate calculations
GROUP BY Grouped data
by group
HAVING After grouping (aggregate filters) Group-level conditions
•Use GROUP BY to group rows
•Use HAVING to filter grouped results
•Use WHERE to filter individual rows before grouping
Use GROUP BY when you want to summarize data. Use
HAVING when you want to filter summarized (grouped) data.”
Student Subject Marks
A Math 90
B Math 70
C Science 95
D Science 85
1)group them by subject and find out which subjects have an average score above 80.
SELECT subject, AVG(marks)
FROM results
GROUP BY subject
HAVING AVG(marks) > 80;
orders
order_id customer product quantity amount order_date
1 Alice Laptop 1 1200 2024-01-01
2 Bob Laptop 2 2400 2024-01-02
3 Alice Phone 3 1500 2024-01-02
4 Carol Laptop 1 1200 2024-01-03
5 Bob Tablet 2 800 2024-01-04
6 Alice Tablet 1 400 2024-01-05
Total quantity ordered by each customer (more than 3 items)
Total amount spent per customer (above $2000)
Count how many times each product was ordered (more than once)
Average amount per customer (above 1000)
Total sales per product where quantity sold > 2
SELECT customer, SUM(quantity) AS total_quantity
FROM orders
GROUP BY customer
HAVING SUM(quantity) > 3;
2) SELECT customer, SUM(amount) AS total_spent
FROM orders
GROUP BY customer
HAVING SUM(amount) > 2000;
3) SELECT product, COUNT(*) AS order_count
FROM orders
GROUP BY product
HAVING COUNT(*) > 1;
SELECT customer, AVG(amount) AS avg_amount
FROM orders
GROUP BY customer
HAVING AVG(amount) > 1000;
SELECT product, SUM(quantity) AS total_quantity
FROM orders
GROUP BY product
HAVING SUM(quantity) > 2;
MPNO 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
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1987-04-19 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1987-05-23 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
8001 SINGH HR 7839 2005-01-15 4500.00 NULL 10
8002 AHMED HR 7839 2008-03-20 4800.00 NULL 10
8003 DAVIS IT 7782 2010-06-01 6000.00 NULL 10
8004 GARCIA IT 7782 2012-09-10 6500.00 NULL 10
Which job roles have an average salary greater than $5000, and what is that average salary for
each of those roles?
List the departments where the total number of employees is exactly 5, and also show the count
of employees for those departments.
Identify departments where the maximum salary is less than $10000 and the minimum salary is
greater than $3000. Also, display the maximum and minimum salaries for these departments.
For departments that have at least 3 employees, show the department name and the sum of
salaries of all employees in those departments.
Which departments have an average commission (COMM) that is not null and greater than $200
, and what is that average commission? (Assuming COMM is a column in the EMP table)
Find the job roles where the count of employees is less than 2, and list the job title and
the number of employees for those roles
SELECT JOB, AVG(SAL) FROM EMP GROUP BY JOB HAVING AVG(SAL) > 5000;
SELECT DEPT, COUNT(*) FROM EMP GROUP BY DEPT HAVING COUNT(*) = 5;
SELECT DEPT, MAX(SAL), MIN(SAL) FROM EMP GROUP BY DEPT HAVING MAX(SAL) < 10000 AND MIN(SAL) > 3000;
SELECT DEPT, SUM(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) >= 3;
SELECT DEPT, AVG(COMM) FROM EMP GROUP BY DEPT HAVING AVG(COMM) IS NOT NULL AND AVG(COMM) > 200;
SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB HAVING COUNT(*) < 2;
join
RollNo Name Class Section
101 Aman 12 A
102 Neha 12 B
103 Raj 12 A
104 Priya 12 B
RollNo Subject Marks
101 CS 92
102 CS 85
103 CS 75
104 CS 88
Write a query to display student names along with their marks
Display names of students who scored more than 80
Write a query to list the RollNo, Name, and marks of students of section ‘A’
Display all student names and their subject names with marks..
(i) SELECT SUBJECT, SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT * FROM SCHOOL WHERE EXPERIENCE BETWEEN 12 AND 15;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL
Based on the given table, write SQL queries for the following:
(i) To increase the ROLl by 5 of all the items whose quantity is more than 100
(ii) To display the all the items in the ascending order of quantity.
(iii) To insert a new record in to the above table.
The respective column values are given below.
5,”PEN DRIVE”,50,”JANVI COMPUTERS”,25