0% found this document useful (0 votes)
3 views28 pages

Searching Data and Patterns in SQL

This document provides a tutorial on searching data and patterns using SQL, covering the creation of sample tables, syntax differences across various RDBMS, and practical SQL queries for retrieving data based on specific conditions. It includes examples of using SQL commands like SELECT, LIKE, BETWEEN, IN, and aggregation functions to analyze student data. Additionally, it explains how to combine data from multiple tables and use subqueries for advanced data retrieval.

Uploaded by

loki85949
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)
3 views28 pages

Searching Data and Patterns in SQL

This document provides a tutorial on searching data and patterns using SQL, covering the creation of sample tables, syntax differences across various RDBMS, and practical SQL queries for retrieving data based on specific conditions. It includes examples of using SQL commands like SELECT, LIKE, BETWEEN, IN, and aggregation functions to analyze student data. Additionally, it explains how to combine data from multiple tables and use subqueries for advanced data retrieval.

Uploaded by

loki85949
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/ 28

🔍in SQL

Searching Data and Patterns

🏁 Introduction
Structured Query Language (SQL) is the backbone of querying and managing
data in relational databases. One of the essential operations is searching —
retrieving information that matches patterns or specific values. This tutorial
begins by creating sample tables and demonstrates pattern searching with
simple SQL commands. It also highlights the syntax differences between SQLite,
MySQL, Oracle, and PostgreSQL.

📦 Step 1: Creating Tables


We will work with three simple tables:

STUDENT – stores student details

ENROLLED – stores course enrollment info

MARKS – stores marks of students

🧱 SQL Table Definitions


✅ Common Schema
STUDENT(sid, name, city)

ENROLLED(sid, course_code, semester)

MARKS(sid, course_code, marks)

🔧 Table Creation Queries (for all RDBMS)


1. SQLite

CREATE TABLE STUDENT (


sid INTEGER PRIMARY KEY,
name TEXT,
city TEXT

🔍 Searching Data and Patterns in SQL 1


);

CREATE TABLE ENROLLED (


sid INTEGER,
course_code TEXT,
semester TEXT
);

CREATE TABLE MARKS (


sid INTEGER,
course_code TEXT,
marks INTEGER
);

2. MySQL

CREATE TABLE STUDENT (


sid INT PRIMARY KEY,
name VARCHAR(100),
city VARCHAR(50)
);

CREATE TABLE ENROLLED (


sid INT,
course_code VARCHAR(10),
semester VARCHAR(10)
);

CREATE TABLE MARKS (


sid INT,
course_code VARCHAR(10),
marks INT
);

3. Oracle

CREATE TABLE STUDENT (


sid NUMBER PRIMARY KEY,

🔍 Searching Data and Patterns in SQL 2


name VARCHAR2(100),
city VARCHAR2(50)
);

CREATE TABLE ENROLLED (


sid NUMBER,
course_code VARCHAR2(10),
semester VARCHAR2(10)
);

CREATE TABLE MARKS (


sid NUMBER,
course_code VARCHAR2(10),
marks NUMBER
);

4. PostgreSQL

CREATE TABLE STUDENT (


sid INT PRIMARY KEY,
name VARCHAR(100),
city VARCHAR(50)
);

CREATE TABLE ENROLLED (


sid INT,
course_code VARCHAR(10),
semester VARCHAR(10)
);

CREATE TABLE MARKS (


sid INT,
course_code VARCHAR(10),
marks INT
);

📌 Note: Differences in Table Creation Syntax


🔍 Searching Data and Patterns in SQL 3
Feature SQLite MySQL Oracle PostgreSQL

Dynamic types Uses


Strong types
Data Types (no strict VARCHAR2 , Strongly typed
(INT, VARCHAR)
typing) NUMBER

AUTO_INCREMENT
Use INTEGER Use sequences Use SERIAL or
Auto-Increment (with PRIMARY
PRIMARY KEY or IDENTITY GENERATED
KEY )

String Type TEXT VARCHAR(n) VARCHAR2(n) VARCHAR(n)

🔢 Step 2: Inserting Sample Data


📋 Table: STUDENT

INSERT INTO STUDENT (sid, name, city) VALUES


(101, 'Amit Kumar', 'Kolkata'),
(102, 'Amitesh Sharma', 'New Delhi'),
(103, 'Rahul Sharma', 'Delhi'),
(104, 'Sneha Singh', 'Pune'),
(105, 'Aniket Das', 'South Kolkata'),
(106, 'Kavya Nair', 'Chennai'),
(107, 'Amit Sharma', 'South Delhi'),
(108, 'Anita Sharma', 'Delhi'),
(109, 'Amrita Kumari', 'New Delhi'),
(110, 'Aman Verma', 'Bangalore');

📋 Table: ENROLLED

INSERT INTO ENROLLED (sid, course_code, semester) VALUES


(101, 'CS101', 'Sem1'),
(102, 'CS101', 'Sem1'),
(103, 'CS102', 'Sem1'),
(104, 'CS103', 'Sem2'),
(105, 'CS101', 'Sem1'),
(106, 'CS102', 'Sem1'),
(107, 'CS103', 'Sem2'),
(108, 'CS101', 'Sem1'),

🔍 Searching Data and Patterns in SQL 4


(109, 'CS104', 'Sem3'),
(110, 'CS105', 'Sem3');

📋 Table: MARKS

INSERT INTO MARKS (sid, course_code, marks) VALUES


(101, 'CS101', 78),
(102, 'CS101', 85),
(103, 'CS102', 69),
(104, 'CS103', 91),
(105, 'CS101', 42),
(106, 'CS102', 56),
(107, 'CS103', 88),
(108, 'CS101', 75),
(109, 'CS104', 90),
(110, 'CS105', 34),
(110, 'CS101', 60); -- Aman Verma enrolled in two courses

🔎 Step 3: Finding Patterns in Student Names


We use LIKE , _ (single-character wildcard), and % (multi-character wildcard) to
identify students based on specific string patterns.

🟢 Query 1: Find all student names that start with 'A'


SELECT * FROM STUDENT
WHERE name LIKE 'A%';

✅ Result:
sid name city

101 Amit Kumar Kolkata

102 Amitesh Sharma New Delhi

105 Aniket Das South Kolkata

107 Amit Sharma South Delhi

108 Anita Sharma Delhi

🔍 Searching Data and Patterns in SQL 5


109 Amrita Kumari New Delhi

110 Aman Verma Bangalore

🟢 Query 2: Find student names that end with 'a'


SELECT * FROM STUDENT
WHERE name LIKE '%a';

✅ Result:
sid name city

102 Amitesh Sharma New Delhi

103 Rahul Sharma Delhi

107 Amit Sharma South Delhi

108 Anita Sharma Delhi

110 Aman Verma Bangalore

🟢 Query 3: Find student names where second character is 'm'


SELECT * FROM STUDENT
WHERE name LIKE '_m%';

✅ Result:
sid name city

101 Amit Kumar Kolkata

102 Amitesh Sharma New Delhi

Amit Sharma
107 South Delhi

109 Amrita Kumari New Delhi

110 Aman Verma Bangalore

🟢 Query 4: Find student names where third character is 'i'


SELECT * FROM STUDENT
WHERE name LIKE '__i%';

🔍 Searching Data and Patterns in SQL 6


✅ Result:
sid name city

101 Amit Kumar Kolkata

102 Amitesh Sharma New Delhi

105 Aniket Das South Kolkata

107 Amit Sharma South Delhi

108 Anita Sharma Delhi

🟢 Query 5: Find students whose surname is 'Sharma'


SELECT * FROM STUDENT
WHERE name LIKE '%Sharma';

✅ Result:
sid name city

102 Amitesh Sharma New Delhi

103 Rahul Sharma Delhi

107 Amit Sharma South Delhi

108 Anita Sharma Delhi

🟢 Query 6: Find students with first name 'Amit'


SELECT * FROM STUDENT
WHERE name LIKE 'Amit %';

✅ Result:
sid name city

101 Amit Kumar Kolkata

107 Amit Sharma South Delhi

🎯 Step 4: Finding Range of Marks Using BETWEEN


The BETWEEN operator allows us to retrieve rows where a value falls within a
specified inclusive range. Below, we’ll use it to analyze marks in the MARKS

🔍 Searching Data and Patterns in SQL 7


table.

🔹 Query 1: Students who scored marks between 60 and 90


SELECT * FROM MARKS
WHERE marks BETWEEN 60 AND 90;

✅ Result:
sid course_code marks

101 CS101 78

102 CS101 85

103 CS102 69

107 CS103 88

108 CS101 75

109 CS104 90

110 CS101 60

✔️ Total Matches: 7 rows


🔹90Query 2: Count how many students scored between 60 and
SELECT COUNT(*) AS total_students
FROM MARKS
WHERE marks BETWEEN 60 AND 90;

✅ Result:
total_students

📋 Step 3: Finding Values From a List Using


NOT IN
IN and

The IN and NOT IN operators are used in SQL to filter rows based on a list of
specific values.

🔍 Searching Data and Patterns in SQL 8


We’ll use these operators to search for students from specific cities in the
STUDENT table.

🔹'South
Query 1: Find students from cities in 'Delhi', 'New Delhi',
Delhi'

SELECT * FROM STUDENT


WHERE city IN ('Delhi', 'New Delhi', 'South Delhi');

✅ Result:
sid name city

102 Amitesh Sharma New Delhi

103 Rahul Sharma Delhi

107 Amit Sharma South Delhi

108 Anita Sharma Delhi

109 Amrita Kumari New Delhi

✔️ Total Matches: 5 students


🔹Delhi'
Query 2: Find students not in cities 'Delhi', 'New Delhi', 'South

SELECT * FROM STUDENT


WHERE city NOT IN ('Delhi', 'New Delhi', 'South Delhi');

✅ Result:
sid name city

101 Amit Kumar Kolkata

104 Sneha Singh Pune

105 Aniket Das South Kolkata

106 Kavya Nair Chennai

110 Aman Verma Bangalore

✔️ Total Matches: 5 students


🧠 Notes on IN and NOT IN

🔍 Searching Data and Patterns in SQL 9


IN (...) is functionally equivalent to multiple OR conditions.

NOT IN (...) excludes all rows matching listed values.

Works with numbers, strings, and subqueries.

🔗Multiple
Step 5: Finding Values by Combining Data from
Tables

🟢 Query 1: Find the name of each student and their marks


SELECT STUDENT.name, MARKS.course_code, MARKS.marks
FROM STUDENT, MARKS
WHERE STUDENT.sid = MARKS.sid;

✅ Result:
name course_code marks

Amit Kumar CS101 78

Amitesh Sharma CS101 85

Rahul Sharma CS102 69

Sneha Singh CS103 91

Aniket Das CS101 42

Kavya Nair CS102 56

Amit Sharma CS103 88

Anita Sharma CS101 75

Amrita Kumari CS104 90

Aman Verma CS105 34

Aman Verma CS101 60

🟢 Query 2: Find marks of students whose name starts with


'Amit'

SELECT STUDENT.name, MARKS.marks


FROM STUDENT, MARKS

🔍 Searching Data and Patterns in SQL 10


WHERE STUDENT.sid = MARKS.sid
AND STUDENT.name LIKE 'Amit%';

✅ Result:
name marks

Amit Kumar 78

Amitesh Sharma 85

Amit Sharma 88

🟢 Query 3: Find the semester of student 'Sneha Singh'


We combine STUDENT and ENROLLED using a Cartesian product with filtering:

SELECT STUDENT.name, ENROLLED.semester


FROM STUDENT, ENROLLED
WHERE STUDENT.sid = ENROLLED.sid
AND STUDENT.name = 'Sneha Singh';

✅ Result:
name semester

Sneha Singh Sem2

Operation How it's done without JOIN

Combine two tables FROM STUDENT, MARKS

Link the data meaningfully WHERE STUDENT.sid = MARKS.sid

Filter with conditions (name, range) Add AND clauses to WHERE

📊 Step 6: Aggregation and Grouping in SQL


SQL provides powerful functions to summarize and analyze data using:

SUM() – total value

AVG() – average

COUNT() – number of rows

🔍 Searching Data and Patterns in SQL 11


MAX() / MIN() – highest or lowest value

These are often used with GROUP BY to summarize data per group (e.g., per
student or per course).

🔹 Query 1: Find the total marks obtained by all students


SELECT SUM(marks) AS total_marks
FROM MARKS;

✅ Result:
total_marks

768

🔹 Query 2: Find the average marks


SELECT AVG(marks) AS average_marks
FROM MARKS;

✅ Result:
average_marks

69.82

🔹 Query 3: Find the highest and lowest marks


SELECT MAX(marks) AS highest,
MIN(marks) AS lowest
FROM MARKS;

✅ Result:
highest lowest

91 34

🔹 Query 4: Count the number of students per course


🔍 Searching Data and Patterns in SQL 12
SELECT course_code, COUNT(*) AS student_count
FROM MARKS
GROUP BY course_code;

✅ Result:
course_code student_count

CS101 5

CS102 2

CS103 2

CS104 1

CS105 1

🔹 Query 5: Find the total and average marks per course


SELECT course_code,
SUM(marks) AS total,
AVG(marks) AS average
FROM MARKS
GROUP BY course_code;

✅ Result:
course_code total average

CS101 340 68.00

CS102 125 62.50

CS103 179 89.50

CS104 90 90.00

CS105 34 34.00

🔹 Query 6: Find each student’s total marks across all courses


SELECT sid, SUM(marks) AS total_marks
FROM MARKS
GROUP BY sid;

🔍 Searching Data and Patterns in SQL 13


✅ Result:
sid total_marks

101 78

102 85

103 69

104 91

105 42

106 56

107 88

108 75

109 90

110 94

🧠 Notes
GROUP BY is mandatory when using aggregation with non-aggregated
columns.

You can use HAVING to filter groups (e.g., show only courses with average >
70).

SELECT course_code, AVG(marks)


FROM MARKS
GROUP BY course_code
HAVING AVG(marks) > 70;

🧩 Step 7: Subqueries in SQL


🔍 Query 1: Students who scored more than the average marks
✅ Main Query:
SELECT name
FROM STUDENT
WHERE sid IN (

🔍 Searching Data and Patterns in SQL 14


SELECT sid
FROM MARKS
WHERE marks > (SELECT AVG(marks) FROM MARKS)
);

📋 Result:
name

Amit Kumar

Amitesh Sharma

Sneha Singh

Amit Sharma

Anita Sharma

Amrita Kumari

🔄 Alternate Query:
SELECT DISTINCT STUDENT.name
FROM STUDENT, MARKS
WHERE STUDENT.sid = MARKS.sid
AND MARKS.marks > (SELECT AVG(marks) FROM MARKS);

🔍 Query 2: Find the highest marks


✅ Main Query:
SELECT marks
FROM MARKS
WHERE marks = (SELECT MAX(marks) FROM MARKS);

📋 Result:
marks

91

🔍 Searching Data and Patterns in SQL 15


🔄 Alternate Query:
SELECT MAX(marks) AS highest_mark
FROM MARKS;

🔍 Query 3: Names of students who got the highest marks


✅ Main Query:
SELECT name
FROM STUDENT
WHERE sid IN (
SELECT sid
FROM MARKS
WHERE marks = (SELECT MAX(marks) FROM MARKS)
);

📋 Result:
name

Sneha Singh

🔄 Alternate Query:
SELECT STUDENT.name
FROM STUDENT, MARKS
WHERE STUDENT.sid = MARKS.sid
AND MARKS.marks = (SELECT MAX(marks) FROM MARKS);

🔍 Query 4: Students enrolled in the same course(s) as


Sharma'
'Amit

✅ Main Query:
SELECT name
FROM STUDENT

🔍 Searching Data and Patterns in SQL 16


WHERE sid IN (
SELECT sid
FROM ENROLLED
WHERE course_code IN (
SELECT course_code
FROM ENROLLED
WHERE sid = (
SELECT sid
FROM STUDENT
WHERE name = 'Amit Sharma'
)
)
);

📋 Result:
name

Amit Sharma

Sneha Singh

🔄 Alternate Query:
SELECT DISTINCT S2.name
FROM STUDENT S1, STUDENT S2, ENROLLED E1, ENROLLED E2
WHERE S1.name = 'Amit Sharma'
AND S1.sid = E1.sid
AND S2.sid = E2.sid
AND E1.course_code = E2.course_code;

🔍 Query 5: Semester of the student who got the lowest marks


✅ Main Query:
SELECT semester
FROM ENROLLED
WHERE sid = (
SELECT sid

🔍 Searching Data and Patterns in SQL 17


FROM MARKS
WHERE marks = (SELECT MIN(marks) FROM MARKS)
LIMIT 1
);

📋 Result:
semester

Sem3

🔄 Alternate Query:
SELECT ENROLLED.semester
FROM STUDENT, MARKS, ENROLLED
WHERE STUDENT.sid = MARKS.sid
AND STUDENT.sid = ENROLLED.sid
ORDER BY MARKS.marks ASC
LIMIT 1;

🔁 Step 7.5:,Set
INTERSECT and
Operations —
EXCEPT
UNION ,

SQL allows you to combine the results of two or more SELECT statements using
set operations:

Operator Description
UNION Combines two result sets, removing duplicates
UNION ALL Combines two result sets, including duplicates
INTERSECT Returns only rows common to both result sets

EXCEPT / MINUS Returns rows in the first set but not in the second

⚠️ Note: All participating SELECT statements must return the


same number of columns with compatible data types.

🔍 Searching Data and Patterns in SQL 18


🧱 Example Data
STUDENT
sid name city

101 Amit Kumar Kolkata

102 Amit Sharma Delhi

103 Sneha Singh Pune

104 Rahul Sharma Delhi

105 Kavya Nair Chennai

ENROLLED
sid course_code semester

101 CS101 Sem1

102 CS101 Sem1

103 CS102 Sem2

106 CS101 Sem1

🔹table1. or ENROLLED
: Students who are either in the STUDENT
UNION

SELECT sid FROM STUDENT


UNION
SELECT sid FROM ENROLLED;

📋 Result:
✅ Combines and removes duplicates
🔹 2. UNION ALL : Include duplicates as well

SELECT sid FROM STUDENT


UNION ALL
SELECT sid FROM ENROLLED;

🔍 Searching Data and Patterns in SQL 19


📋 Result:
sid

✅ Combines and keeps duplicates


🔹and3.ENROLLED : Students who are in both STUDENT
INTERSECT

SELECT sid FROM STUDENT


INTERSECT
SELECT sid FROM ENROLLED;

📋 Result:
sid

✅ Only common sids


🔁 If you're using MySQL (which does not support
INTERSECT), use:

SELECT sid FROM STUDENT


WHERE sid IN (SELECT sid FROM ENROLLED);

🔹enrolled
4. EXCEPT / MINUS : Students in STUDENT but not

In PostgreSQL / SQL standard:

SELECT sid FROM STUDENT


EXCEPT
SELECT sid FROM ENROLLED;

In Oracle:

🔍 Searching Data and Patterns in SQL 20


SELECT sid FROM STUDENT
MINUS
SELECT sid FROM ENROLLED;

In MySQL (alternative):

SELECT sid FROM STUDENT


WHERE sid NOT IN (SELECT sid FROM ENROLLED);

📋 Result:
sid

104

105

✅ Shows sids only in STUDENT, not in ENROLLED


🧠 Summary of Set Operators
Operator Supports Duplicates? Common Use

UNION
❌ Removes Combine two result sets
duplicates
UNION ALL ✅ Keeps duplicates Combine and preserve all results

INTERSECT
❌ Removes Find overlap between two result sets
duplicates

EXCEPT
❌ Removes Find rows present in the first, not in the
duplicates second

🔗 Step 8: Joins in SQL


🧱 Example Data Setup
STUDENT Table
sid name city

🔍 Searching Data and Patterns in SQL 21


101 Amit Kumar Kolkata

102 Amit Sharma Delhi

103 Sneha Singh Pune

104 Rahul Sharma Delhi

105 Kavya Nair Chennai

MARKS Table
sid course_code marks

101 CS101 78

102 CS102 85

103 CS101 90

106 CS103 88

🔹column)
1. NATURAL JOIN (only matching rows by common

SELECT *
FROM STUDENT
NATURAL JOIN MARKS;

📋 Result:
sid name city course_code marks

101 Amit Kumar Kolkata CS101 78

102 Amit Sharma Delhi CS102 85

103 Sneha Singh Pune CS101 90

🔄 Alternate Query (using INNER JOIN on sid ):

SELECT *
FROM STUDENT
INNER JOIN MARKS ON STUDENT.sid = MARKS.sid;

🔹 2. LEFT JOIN (all students, even if no marks)


🔍 Searching Data and Patterns in SQL 22
SELECT STUDENT.sid, name, course_code, marks
FROM STUDENT
LEFT JOIN MARKS ON STUDENT.sid = MARKS.sid;

📋 Result:
sid name course_code marks

101 Amit Kumar CS101 78

102 Amit Sharma CS102 85

103 Sneha Singh CS101 90

104 Rahul Sharma NULL NULL

105 Kavya Nair NULL NULL

🔄 Alternate Query (simulate with UNION + WHERE):


SELECT *
FROM STUDENT
WHERE sid NOT IN (SELECT sid FROM MARKS)
UNION
SELECT STUDENT.sid, name, NULL, NULL
FROM STUDENT, MARKS
WHERE STUDENT.sid = MARKS.sid;

🔹student)
3. RIGHT JOIN (all marks entries, even if no

SELECT MARKS.sid, name, course_code, marks


FROM STUDENT
RIGHT JOIN MARKS ON STUDENT.sid = MARKS.sid;

📋 Result:
sid name course_code marks

101 Amit Kumar CS101 78

102 Amit Sharma CS102 85

🔍 Searching Data and Patterns in SQL 23


103 Sneha Singh CS101 90

106 NULL CS103 88

🔹where
4. FULL OUTER JOIN (all rows from both, match
possible)

SELECT STUDENT.sid, name, city, course_code, marks


FROM STUDENT
FULL OUTER JOIN MARKS ON STUDENT.sid = MARKS.sid;

📋 Result:
sid name city course_code marks

101 Amit Kumar Kolkata CS101 78

102 Amit Sharma Delhi CS102 85

103 Sneha Singh Pune CS101 90

104 Rahul Sharma Delhi NULL NULL

105 Kavya Nair Chennai NULL NULL

106 NULL NULL CS103 88

🔄JOINs):
Alternate Query (simulate using UNION of LEFT and RIGHT

SELECT STUDENT.sid, name, city, course_code, marks


FROM STUDENT
LEFT JOIN MARKS ON STUDENT.sid = MARKS.sid

UNION

SELECT MARKS.sid, name, city, course_code, marks


FROM MARKS
LEFT JOIN STUDENT ON STUDENT.sid = MARKS.sid;

🧠 Summary of Join Types


🔍 Searching Data and Patterns in SQL 24
Includes from Includes from
Join Type Missing Matches
STUDENT MARKS

NATURAL /
INNER
✅ if matched ✅ if matched ❌ excluded
LEFT JOIN ✅ all rows ✅ only if matched NULL if no marks
RIGHT JOIN ✅ only if matched ✅ all rows NULL if no student

FULL OUTER ✅ all rows ✅ all rows NULLs on both


sides

🧾Concepts
Additional SQL Commands and

🔧 1. ALTER — Modify Table Structure


Used to add, remove, or modify columns in an existing table.

ALTER TABLE STUDENT ADD email VARCHAR(100);

✅ Adds a new column email to the STUDENT table.

ALTER TABLE STUDENT DROP COLUMN city;

✅ Removes the city column from the STUDENT table.

📋 2. DESC or DESCRIBE — Describe Table Structure


Displays the structure of a table (column names, types, nullability).

DESC STUDENT;

✅ Lists all columns in the STUDENT table with their data types.

🔸 Works in MySQL, Oracle.


🔸 Use in SQLite or
.schema tablename \d tablename in PostgreSQL.

🔍 Searching Data and Patterns in SQL 25


🗑️ 3. DROP — Delete Table or Object
Permanently deletes a table, view, or other database object.

DROP TABLE MARKS;

✅ Deletes the MARKS table and all its data.

⚠️ Irreversible!
👁️ 4. VIEW — Create a Virtual Table
A view is a saved SQL query that behaves like a table.

CREATE VIEW top_students AS


SELECT name, marks
FROM STUDENT, MARKS
WHERE STUDENT.sid = MARKS.sid AND marks > 80;

✅ Creates a view top_students showing students with marks > 80.

SELECT * FROM top_students;

✅ Use the view like a regular table.


❌condition)
5. DELETE — Remove Data from Table (with

DELETE FROM MARKS


WHERE marks < 40;

✅ Deletes rows with marks less than 40 from the MARKS table.

Can be rolled back if inside a transaction.

🧹DELETE)
6. TRUNCATE — Delete All Data (faster than

🔍 Searching Data and Patterns in SQL 26


TRUNCATE TABLE MARKS;

✅ Deletes all records without logging individual deletions.


⚠️ Cannot be rolled back in many RDBMS.
💾 7. COMMIT — Save Changes Permanently

DELETE FROM MARKS WHERE marks < 40;


COMMIT;

✅ Permanently applies the deletion.


⚠️ After COMMIT, changes cannot be undone.
📍 8. CHECKPOINT — Save DB State (PostgreSQL)

CHECKPOINT;

✅ Forces a write of all in-memory changes to disk.


Used in PostgreSQL; not supported in MySQL or SQLite.

🔁 9. ROLLBACK — Undo Uncommitted Changes

DELETE FROM MARKS WHERE marks < 40;


ROLLBACK;

✅ Reverts deletion if not yet committed.


🚨 10. TRIGGER — Auto Action on Table Events
Triggers run automatically when a specific action happens
(INSERT/UPDATE/DELETE).

🔍 Searching Data and Patterns in SQL 27


Example: Log insertions to a table

CREATE TABLE audit_log (


log_id INTEGER PRIMARY KEY,
sid INTEGER,
log_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER log_insert


AFTER INSERT ON STUDENT
FOR EACH ROW
BEGIN
INSERT INTO audit_log (sid) VALUES (NEW.sid);
END;

✅ This trigger automatically logs every new student added to the STUDENT table.

✅ Summary Table
Command Purpose Reversible? Notes
ALTER Modify table structure ✅ Add/remove columns
DESC Describe table structure ✅ Read-only

DROP
Delete table/view
permanently
❌ Deletes structure and data

VIEW Create virtual table ✅ Doesn’t store actual data


DELETE Remove specific rows ✅ Needs condition
TRUNCATE Remove all rows ❌ Fast, no row-level logging

COMMIT Save transaction ❌ (final) After this, changes are


permanent

ROLLBACK
Undo uncommitted
transaction
✅ Before COMMIT

CHECKPOINT
Flush in-memory data to
disk
✅ PostgreSQL specific

TRIGGER
Auto action on DML
events
✅ (drop) Useful for logging, audit,
validation

🔍 Searching Data and Patterns in SQL 28

You might also like