Resources | Subject Notes | Computer Science
This section focuses on understanding and writing SQL scripts to retrieve data from a database. We will cover fundamental SQL commands and how to combine them to perform various queries.
Let's consider a simple database for students:
Student ID | Name | Subject | Marks |
---|---|---|---|
1 | Alice | Maths | 85 |
2 | Bob | Science | 92 |
3 | Charlie | Maths | 78 |
4 | David | English | 95 |
5 | Eve | Science | 88 |
This query retrieves all columns and all rows from the table.
SELECT *
FROM Students;
This query retrieves only the 'Name' and 'Marks' columns.
SELECT Name, Marks
FROM Students;
This query retrieves the names and marks of students who study 'Maths'.
SELECT Name, Marks
FROM Students
WHERE Subject = 'Maths';
This query retrieves all data, sorted by 'Marks' in descending order.
SELECT *
FROM Students
ORDER BY Marks DESC;
This query retrieves only the first 2 students.
SELECT *
FROM Students
LIMIT 2;
This query retrieves the names and marks of students who study 'Science' and have marks greater than 90.
SELECT Name, Marks
FROM Students
WHERE Subject = 'Science' AND Marks > 90;
These examples provide a foundation for understanding and writing SQL queries. Further topics include aggregate functions (e.g., COUNT, SUM, AVG), grouping data (GROUP BY), and joining tables.