
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.