Topic 6 – SQL Data Query Language (DQL)

image 2

Play Store Application link – SQL in 18 steps – App on Google Play

Introduction to DQL

DQL (Data Query Language) is used to retrieve data from databases. Think of it as searching for specific information in a large listβ€”like finding a particular contact in your phone.


1. SELECT Statement – Fetching Data

The SELECT statement is used to retrieve data from a table.

Basic Example

SELECT * FROM Students;

This retrieves all students from the Students table.

Selecting Specific Columns

SELECT name, age FROM Students;

This fetches only the name and age of students.


2. WHERE Clause – Filtering Data

Use WHERE to filter specific records.

Example: Find Students Older Than 20

SELECT * FROM Students WHERE age > 20;

Example: Find Students with a Specific Name

SELECT * FROM Students WHERE name = 'John Doe';

Using Logical Operators (AND, OR)

SELECT * FROM Students WHERE age > 18 AND age < 25;


3. ORDER BY – Sorting Data

Use ORDER BY to sort results in ascending or descending order.

Sort Students by Age (Ascending)

SELECT * FROM Students ORDER BY age ASC;

Sort Students by Age (Descending)

SELECT * FROM Students ORDER BY age DESC;


4. GROUP BY & HAVING – Aggregating Data

GROUP BY – Group Data Based on a Column

Find the number of students in each age group:

SELECT age, COUNT(*) AS total_students 
FROM Students 
GROUP BY age;

HAVING – Filter Aggregated Results

Find age groups with more than 2 students:

SELECT age, COUNT(*) AS total_students 
FROM Students 
GROUP BY age
HAVING COUNT(*) > 2;


5. DISTINCT – Removing Duplicates

Example: Get Unique Ages of Students

SELECT DISTINCT age FROM Students;


6. LIMIT, ROWNUM, FETCH FIRST N ROWS

Different databases handle result limits differently.

MySQL – Use LIMIT

SELECT * FROM Students LIMIT 5;

Oracle – Use ROWNUM

SELECT * FROM Students WHERE ROWNUM <= 5;

PostgreSQL, SQL Server – Use FETCH FIRST N ROWS

SELECT * FROM Students FETCH FIRST 5 ROWS ONLY;


Conclusion

DQL is the foundation of retrieving and filtering data. Understanding SELECT, WHERE, ORDER BY, GROUP BY, and LIMIT helps in fetching meaningful results efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *