Alright, let's dive into each concept with extreme depth, explaining every single word, as if
you're learning about databases for the very first time. We'll continue using our Students and
Courses tables, which are like simple lists of information.
Our Tables (Our Data Lists):
1. Students Table: (A list of students and their details)
StudentID Name Age Major GPA
101 Alice 20 Computer 3.8
Science
102 Bob 22 Engineering 3.2
103 Charlie 19 Arts 3.9
104 David 21 Computer 3.5
Science
105 Eve 20 Engineering 3.7
106 Frank 23 Arts 3.0
● StudentID: A unique number for each student. Think of it like their roll number or ID card
number.
● Name: The student's name.
● Age: How old the student is.
● Major: The main subject the student is studying (e.g., Computer Science, Engineering,
Arts).
● GPA: Grade Point Average, a number showing how well they are doing academically.
2. Courses Table: (A list of courses and who is taking them)
CourseID CourseName Credits StudentID
CS101 Intro to 3 101
Programming
ENG201 Mechanics 4 102
ART100 Art History 3 103
CS201 Data Structures 4 104
ENG201 Mechanics 4 105
ART100 Art History 3 106
CS101 Intro to 3 104
Programming
CS301 Algorithms 3 101
● CourseID: A unique code for each course (e.g., CS101).
● CourseName: The full name of the course.
● Credits: The number of academic credits the course is worth.
● StudentID: This column links back to the Students table. It tells us which student is
taking this specific course. For example, the first row says Student 101 (Alice) is taking
CS101.
1. Queries: Asking Questions to Your Data
Imagine your tables are like big, organized spreadsheets. A Query (pronounced "KWUH-ree")
is simply a question you ask to these spreadsheets to get specific information. You write
these questions in a special language called SQL (Structured Query Language).
The basic structure of most queries is:
SELECT (what columns you want to see)
FROM (which table you're asking about)
WHERE (what conditions rows must meet to be included)
1.1. Using MAX, GROUP BY, COUNT(*)
These are about summarizing and grouping your data.
● MAX(column_name):
○ What it does: Finds the largest value in a specific column.
○ Analogy: If you have a list of all your exam scores, MAX tells you your highest score.
○ Example: Get the highest GPA among all students.
○ SQL:
SQL
SELECT MAX(GPA) AS HighestGPA
FROM Students;
○ Explanation (word by word):
■ SELECT: "I want to see..."
■ MAX(GPA): "...the maximum value found in the 'GPA' column..."
■ AS HighestGPA: "...and I want to call this result 'HighestGPA' (this just makes the
output column name nicer)."
■ FROM Students: "...from the 'Students' table."
○ Output:
HighestGPA
| :--------- |
| 3.9 |
* This means, looking at all GPAs in the `Students` table (3.8, 3.2, 3.9, 3.5, 3.7, 3.0), the
largest one is 3.9.
● COUNT(*):
○ What it does: Counts the total number of rows (records) in your table or group.
○ Analogy: If you have a list of all your friends, COUNT(*) tells you how many friends
you have.
○ Example: Count how many students are in the 'Computer Science' major.
○ SQL:
SQL
SELECT COUNT(*) AS NumCompSciStudents
FROM Students
WHERE Major = 'Computer Science';
○ Explanation:
■ SELECT COUNT(*): "Count all the rows..."
■ AS NumCompSciStudents: "...and call the result 'NumCompSciStudents'."
■ FROM Students: "...from the 'Students' table."
■ WHERE Major = 'Computer Science': "...but only count those rows where the
'Major' column is exactly 'Computer Science'."
○ Output:
NumCompSciStudents
| :----------------- |
|2 |
* This shows there are 2 students whose major is 'Computer Science' (Alice and David).
● GROUP BY column_name:
○ What it does: Organizes rows into groups based on identical values in a specified
column. It's like sorting your laundry by color – all reds together, all whites together.
○ Why use it? After grouping, you can apply aggregate functions (like AVG, COUNT,
SUM, MAX, MIN) to each group separately.
○ Example (combined with AVG and COUNT): Find the average GPA for each major
and count how many students are in each major.
○ SQL:
SQL
SELECT
Major, -- I want to see the Major
AVG(GPA) AS AverageGPA, -- and the average GPA for that Major
COUNT(*) AS NumberOfStudents -- and the count of students in that Major
FROM Students
GROUP BY Major; -- Group the students by their Major
○ Explanation:
■ SELECT Major, AVG(GPA) AS AverageGPA, COUNT(*) AS NumberOfStudents:
"For each group, show me the 'Major' name, calculate the average of all 'GPA's
within that group and call it 'AverageGPA', and count all the rows (*) within that
group and call it 'NumberOfStudents'."
■ FROM Students: "Get this information from the 'Students' table."
■ GROUP BY Major: "First, gather all students with the same 'Major' into separate
bundles. Then, apply the AVG and COUNT functions to each bundle."
○ Output: | Major | AverageGPA | NumberOfStudents | | :--------------- | :---------
| :--------------- | | Computer Science | 3.65 | 2 | | Engineering | 3.45 | 2 | | Arts | 3.45 |
2|
■ How to read this: For "Computer Science", the average GPA of Alice (3.8) and
David (3.5) is (3.8+3.5)/2 = 3.65, and there are 2 students. Similarly for
Engineering and Arts.
1.2. IN, NOT IN, EXIST, NOT EXIST (Membership Operators)
These are used to check if a value is part of a set of values or if related records exist.
● IN (value1, value2, ...):
○ What it does: Checks if a value in a column is equal to any of the values in a list.
○ Analogy: "Is your favorite color IN (red, blue, green)?" (Yes, if it's red, or blue, or
green).
○ Example: Find students whose major is 'Computer Science' OR 'Engineering'.
○ SQL:
SQL
SELECT StudentID, Name, Major
FROM Students
WHERE Major IN ('Computer Science', 'Engineering');
○ Explanation:
■ WHERE Major IN ('Computer Science', 'Engineering'): "Only include rows where
the 'Major' column's value is either 'Computer Science' OR 'Engineering'."
○ Output: | StudentID | Name | Major | | :-------- | :-------- | :--------------- | | 101 |
Alice | Computer Science | | 102 | Bob | Engineering | | 104 | David | Computer
Science | | 105 | Eve | Engineering |
● NOT IN (value1, value2, ...):
○ What it does: Checks if a value in a column is NOT equal to any of the values in a
list.
○ Analogy: "Is your favorite color NOT IN (red, blue, green)?" (Yes, if it's yellow, or
purple, etc.).
○ Example: Find students whose major is neither 'Computer Science' nor
'Engineering'.
○ SQL:
SQL
SELECT StudentID, Name, Major
FROM Students
WHERE Major NOT IN ('Computer Science', 'Engineering');
○ Explanation:
■ WHERE Major NOT IN ('Computer Science', 'Engineering'): "Only include rows
where the 'Major' column's value is not 'Computer Science' AND not
'Engineering'."
○ Output: | StudentID | Name | Major | | :-------- | :------ | :---- | | 103 | Charlie | Arts | |
106 | Frank | Arts |
● EXISTS (subquery):
○ What it does: Checks if a subquery (a query inside another query) returns any rows.
It's a quick "yes/no" check for related data.
○ Analogy: "Does this student EXIST in the 'Courses' enrollment list?" You don't need
to see which courses, just if they're in any course.
○ Example: Find students who are enrolled in at least one course.
○ SQL:
SQL
SELECT S.Name, S.Major
FROM Students S -- We use 'S' as a short nickname (alias) for the Students table
WHERE EXISTS (
SELECT 1 -- We just select '1' because we only care IF rows exist, not what they
contain
FROM Courses C -- Use 'C' as a nickname for the Courses table
WHERE C.StudentID = S.StudentID -- This is the link: current student (S) must match a
student in Courses (C)
);
○ Explanation:
■ FROM Students S: "Start by looking at each row in the 'Students' table. Let's call
the current student we're looking at S."
■ WHERE EXISTS (...): "For this specific student S, go and run the query inside the
parentheses (...). If that inner query finds at least one matching row, then include
this student S in our final result."
■ SELECT 1 FROM Courses C WHERE C.StudentID = S.StudentID: "This inner query
says: 'Look in the Courses table. Is there any course C where the StudentID in
the Courses table matches the StudentID of the student S we're currently
considering from the outer Students table?'"
○ Output: (All our students are enrolled, so all will appear) | Name | Major | | :------
| :--------------- | | Alice | Computer Science | | Bob | Engineering | | Charlie | Arts | |
David | Computer Science | | Eve | Engineering | | Frank | Arts |
● NOT EXISTS (subquery):
○ What it does: Checks if a subquery returns no rows. It's a quick "yes/no" check for
the absence of related data.
○ Analogy: "Does this student NOT EXIST in the 'Courses' enrollment list?" (Are they
not enrolled in any course?)
○ Example: Find students who are not enrolled in any course. (For this, let's pretend
we add a new student, Zoe, with StudentID 107, who hasn't taken any courses yet).
○ SQL:
SQL
-- Imagine we added: INSERT INTO Students VALUES (107, 'Zoe', 21, 'Biology', 3.6);
SELECT S.Name, S.Major
FROM Students S
WHERE NOT EXISTS (
SELECT 1
FROM Courses C
WHERE C.StudentID = S.StudentID
);
○ Explanation:
■ WHERE NOT EXISTS (...): "For this specific student S, go and run the query inside
the parentheses (...). If that inner query finds no matching rows (meaning the
student is not linked to any course), then include this student S in our final
result."
○ Output (if Zoe (107) was added and had no courses): | Name | Major | | :---
| :------ | | Zoe | Biology |
1.3. Aggregate Functions (SUM, AVG, COUNT, MIN, MAX)
These are special functions that take a set of values (from a column across many rows) and
return a single summary value. They "aggregate" data.
● SUM(column_name):
○ What it does: Adds up all the numbers in a specified column.
○ Analogy: Total sales for the month.
○ Example: Find the total credits of all courses available in the Courses table.
○ SQL:
SQL
SELECT SUM(Credits) AS TotalCreditsOffered
FROM Courses;
○ Explanation:
■ SELECT SUM(Credits): "Add up all the values in the 'Credits' column."
■ AS TotalCreditsOffered: "Call the result 'TotalCreditsOffered'."
■ FROM Courses: "Do this calculation using the 'Courses' table."
○ Output:
TotalCreditsOffered
| :------------------ |
| 27 |
* (3 + 4 + 3 + 4 + 4 + 3 + 3 + 3 = 27)
● AVG(column_name):
○ What it does: Calculates the average (mean) of all numbers in a specified column.
(Sum of values / Number of values).
○ Analogy: Average exam score for the class.
○ Example: Find the average age of all students.
○ SQL:
SQL
SELECT AVG(Age) AS AverageStudentAge
FROM Students;
○ Explanation:
■ SELECT AVG(Age): "Calculate the average of all values in the 'Age' column."
■ AS AverageStudentAge: "Call the result 'AverageStudentAge'."
■ FROM Students: "Do this using the 'Students' table."
○ Output:
AverageStudentAge
| :---------------- |
| 20.833333 |
* (20+22+19+21+20+23) / 6 = 125 / 6 = 20.833333
● MIN(column_name):
○ What it does: Finds the smallest value in a specified column.
○ Analogy: The lowest price of an item.
○ Example: Find the minimum GPA among all students.
○ SQL:
SQL
SELECT MIN(GPA) AS LowestGPA
FROM Students;
○ Explanation: Similar to MAX, but finds the smallest.
○ Output:
LowestGPA
| :-------- |
| 3.0 |
2. Subqueries: Queries Inside Queries
A Subquery (also called an "inner query" or "nested query") is a SELECT statement that is
embedded inside another SQL query. Think of it as needing to figure out something small first
to help you answer a bigger question. The inner query runs first, and its result is then used by
the outer query.
2.1. Basic Subquery (Non-Correlated)
● What it does: The inner query runs completely independently of the outer query. It
provides a single value or a list of values that the outer query then uses.
● Analogy: To find students with above-average GPA, first, you need to know what the
average GPA is. That "what the average GPA is" is your subquery.
● Example: Find students whose GPA is higher than the average GPA of all students.
● SQL:
SQL
SELECT StudentID, Name, GPA
FROM Students
WHERE GPA > (SELECT AVG(GPA) FROM Students); -- This is the subquery
● Explanation (step-by-step):
1. (SELECT AVG(GPA) FROM Students): The database first executes this inner query. It
calculates the average GPA from all students, which we already found is 20.833333.
2. The outer query then becomes: SELECT StudentID, Name, GPA FROM Students
WHERE GPA > 20.833333;
3. Finally, the outer query fetches students whose individual GPA is greater than that
calculated average.
● Output: | StudentID | Name | GPA | | :-------- | :------ | :-- | | 101 | Alice | 3.8 | | 103 |
Charlie | 3.9 | | 105 | Eve | 3.7 |
2.2. Correlated Subquery
● What it does: The inner subquery depends on the outer query for its values. This means
the inner query re-runs for each row processed by the outer query. It's like asking a
specific question for each item on a list, using details from that item.
● Analogy: "For each student, find if that student has taken a course with 4 credits." The
"that student" part makes it correlated.
● Example: Find students who have taken at least one course with 4 credits.
● SQL:
SQL
SELECT S.StudentID, S.Name, S.Major
FROM Students S
WHERE EXISTS (
SELECT 1
FROM Courses C
WHERE C.StudentID = S.StudentID -- This is the correlation!
AND C.Credits = 4
);
● Explanation (step-by-step for each student in Students):
1. Student 101 (Alice):
■ The outer query considers Alice.
■ The inner query runs: SELECT 1 FROM Courses C WHERE C.StudentID = 101 AND
C.Credits = 4;
■ Are there courses for Student 101 (Alice) with 4 credits? No (she has CS101 (3),
CS301 (3)). So, EXISTS is false for Alice. Alice is not included.
2. Student 102 (Bob):
■ The outer query considers Bob.
■ The inner query runs: SELECT 1 FROM Courses C WHERE C.StudentID = 102 AND
C.Credits = 4;
■ Are there courses for Student 102 (Bob) with 4 credits? Yes (ENG201). So,
EXISTS is true for Bob. Bob is included.
3. ... and so on for every student.
● Output: | StudentID | Name | Major | | :-------- | :---- | :--------------- | | 102 | Bob |
Engineering | | 104 | David | Computer Science | | 105 | Eve | Engineering |
3. Joins: Combining Information from Multiple Tables
A Join is how you link rows from two or more tables together based on a related column
between them. It's like finding matching information across different lists and combining them
into one bigger, more complete list. The key to joining is having a common column (like
StudentID in our example) that exists in both tables.
3.1. INNER JOIN (Most Common)
● What it does: Returns only the rows where there's a match in the specified join column
in both tables. If a row in one table doesn't have a corresponding match in the other, it's
left out.
● Analogy: You have a list of students and a list of courses. An INNER JOIN shows you only
the students who are actually enrolled in a course, and the course they are enrolled in. If
a student isn't enrolled, or a course has no students, they don't show up.
● Example: List students and the courses they are enrolled in.
● SQL:
SQL
SELECT
S.Name, -- Student's Name
S.Major, -- Student's Major
C.CourseName, -- Course Name
C.Credits -- Course Credits
FROM Students S -- Start with the Students table (nickname S)
INNER JOIN Courses C -- Join it with the Courses table (nickname C)
ON S.StudentID = C.StudentID; -- The rule for joining: StudentID in Students must match
StudentID in Courses
● Explanation:
○ FROM Students S: "Start with every row in the Students table. Call it S."
○ INNER JOIN Courses C: "Now, for each student S, look at the Courses table (called
C)."
○ ON S.StudentID = C.StudentID: "Only combine a student S row with a course C row if
their StudentID values are exactly the same."
● Output: (Notice Alice appears twice because she's in two courses, and David appears
twice.) | Name | Major | CourseName | Credits | | :------ | :---------------
| :------------------- | :------ | | Alice | Computer Science | Intro to Programming | 3 | |
Alice | Computer Science | Algorithms | 3 | | Bob | Engineering | Mechanics | 4 | | Charlie |
Arts | Art History | 3 | | David | Computer Science | Data Structures | 4 | | David |
Computer Science | Intro to Programming | 3 | | Eve | Engineering | Mechanics | 4 | | Frank
| Arts | Art History | 3 |
3.2. LEFT JOIN (or LEFT OUTER JOIN)
● What it does: Returns all rows from the "left" table (the one listed first in the FROM
clause) and only the matching rows from the "right" table. If there's no match for a left
table row in the right table, the right table's columns will be filled with NULL (meaning
"no value").
● Analogy: "Show me all students. And if they are enrolled in a course, show me that
course. If a student isn't enrolled in any course, still show their name, but just leave the
course columns blank."
● Example: List all students and their courses. If a student has no courses, still list them.
● SQL:
SQL
SELECT S.Name, S.Major, C.CourseName, C.Credits
FROM Students S
LEFT JOIN Courses C ON S.StudentID = C.StudentID;
● Explanation:
○ FROM Students S: Students is the "left" table. All rows from Students will be in the
result.
○ LEFT JOIN Courses C: Courses is the "right" table.
○ ON S.StudentID = C.StudentID: The matching rule.
○ Consider Student 107 (Zoe) if she had no courses:
■ Students table has Zoe (107).
■ The LEFT JOIN says: "Always include Zoe from the Students table."
■ It then checks Courses for StudentID = 107. If no courses exist for Zoe, then
C.CourseName and C.Credits will show NULL.
● Output (with hypothetical Zoe): | Name | Major | CourseName | Credits | | :------
| :--------------- | :------------------- | :------ | | Alice | Computer Science | Intro to
Programming | 3 | | Alice | Computer Science | Algorithms | 3 | | Bob | Engineering |
Mechanics | 4 | | Charlie | Arts | Art History | 3 | | David | Computer Science | Data
Structures | 4 | | David | Computer Science | Intro to Programming | 3 | | Eve | Engineering
| Mechanics | 4 | | Frank | Arts | Art History | 3 | | Zoe | Biology | NULL | NULL |
3.3. RIGHT JOIN (or RIGHT OUTER JOIN)
● What it does: The opposite of a LEFT JOIN. Returns all rows from the "right" table (the
one listed after RIGHT JOIN) and only the matching rows from the "left" table. If there's
no match for a right table row in the left table, the left table's columns will be filled with
NULL.
● Analogy: "Show me all courses. And if there's a student taking that course, show me
their details. If a course has no students (unlikely in this example, but possible in others),
still show the course name, but leave the student columns blank."
● Example: List all courses and the students taking them. If a course has no students, still
list it.
● SQL:
SQL
SELECT S.Name, S.Major, C.CourseName, C.Credits
FROM Students S
RIGHT JOIN Courses C ON S.StudentID = C.StudentID;
● Explanation:
○ FROM Students S: Students is now the "left" table.
○ RIGHT JOIN Courses C: Courses is the "right" table. All rows from Courses will be in
the result.
○ Consider a hypothetical CourseID = 'MTH101' with CourseName = 'Calculus',
Credits = 5, but StudentID = NULL (no one is taking it yet):
■ The RIGHT JOIN would include this MTH101 course. Since its StudentID is NULL
(or simply doesn't match any student), the S.Name and S.Major columns would
show NULL for that row.
● Output (with hypothetical MTH101): | Name | Major | CourseName | Credits | | :------
| :--------------- | :------------------- | :------ | | Alice | Computer Science | Intro to
Programming | 3 | | Bob | Engineering | Mechanics | 4 | | Charlie | Arts | Art History | 3 | |
David | Computer Science | Data Structures | 4 | | Eve | Engineering | Mechanics | 4 | |
Frank | Arts | Art History | 3 | | David | Computer Science | Intro to Programming | 3 | |
Alice | Computer Science | Algorithms | 3 | | NULL | NULL | Calculus | 5 |
3.4. FULL OUTER JOIN (or FULL JOIN)
● What it does: Returns all rows when there's a match in either the left or the right table. It
combines the results of LEFT JOIN and RIGHT JOIN. If a row in the left table has no
match in the right, the right side gets NULLs. If a row in the right table has no match in
the left, the left side gets NULLs.
● Analogy: "Show me every student AND every course. If a student is taking a course, link
them up. If a student isn't taking any courses, show their name but leave course details
blank. If a course isn't being taken by any student, show the course but leave student
details blank."
● Example: List all students and all courses, showing relationships where they exist.
● SQL:
SQL
SELECT S.Name, S.Major, C.CourseName, C.Credits
FROM Students S
FULL OUTER JOIN Courses C ON S.StudentID = C.StudentID;
● Explanation: This will capture everything from both tables, showing NULLs where there
are no matches on either side. It's the most "inclusive" join.
● Output (with hypothetical Zoe and MTH101):
| Name | Major | CourseName | Credits |
| :------ | :--------------- | :------------------- | :------ |
| Alice | Computer Science | Intro to Programming | 3 |
| Alice | Computer Science | Algorithms | 3 |
| Bob | Engineering | Mechanics | 4 |
| Charlie | Arts | Art History | 3 |
| David | Computer Science | Data Structures | 4 |
| David | Computer Science | Intro to Programming | 3 |
| Eve | Engineering | Mechanics | 4 |
| Frank | Arts | Art History | 3 |
| Zoe | Biology | NULL | NULL |
| NULL | NULL | Calculus | 5 |
3.5. CROSS JOIN
● What it does: Creates a "Cartesian Product." This means it combines every single row
from the first table with every single row from the second table. There's no ON clause
because it doesn't look for matching values.
● Analogy: If you have 3 shirts and 4 pairs of pants, a cross join tells you all 3x4=12
possible outfit combinations, whether they match or not.
● Example: Pair every student with every course.
● SQL:
SQL
SELECT S.Name, C.CourseName
FROM Students S
CROSS JOIN Courses C;
● Explanation:
○ If Students has 6 rows and Courses has 8 rows, the result will have 6 * 8 = 48 rows.
○ The first student (Alice) will be listed with every course. Then the second student
(Bob) will be listed with every course, and so on.
● Partial Output (first few rows to illustrate): | Name | CourseName | | :----
| :------------------- | | Alice | Intro to Programming | | Alice | Mechanics | | Alice | Art
History | | Alice | Data Structures | | Alice | Mechanics | | Alice | Art History | | Alice | Intro
to Programming | | Alice | Algorithms | | Bob | Intro to Programming | | Bob | Mechanics |
| ... | ... |
3.6. Self Join
● What it does: Joining a table with itself. You treat the same table as if it were two
different tables by giving it two different temporary names (aliases). This is useful for
comparing rows within the same table.
● Analogy: You have a list of employees, and each employee has a manager, who is also
an employee in the same list. You can "self-join" to find out who reports to whom. Or,
finding people who share the same characteristic (like age in our example).
● Example: Find pairs of students who are the same age.
● SQL:
SQL
SELECT
S1.Name AS Student1Name, -- Name of the first student in the pair
S1.Age, -- Their age
S2.Name AS Student2Name, -- Name of the second student in the pair
S2.Age -- Their age
FROM Students S1 -- Treat Students table as 'S1'
INNER JOIN Students S2 -- Join it with itself, treated as 'S2'
ON S1.Age = S2.Age -- Condition 1: Their ages must be equal
AND S1.StudentID < S2.StudentID; -- Condition 2: To avoid duplicate pairs (Alice, Eve AND Eve,
Alice) and self-comparison (Alice, Alice)
● Explanation:
○ FROM Students S1 INNER JOIN Students S2: We're pretending we have two copies of
the Students table, one called S1 and one called S2.
○ ON S1.Age = S2.Age: We're looking for rows where the Age in S1 is the same as the
Age in S2.
○ AND S1.StudentID < S2.StudentID: This is a trick! If Alice (ID 101, Age 20) is compared
to Eve (ID 105, Age 20):
■ S1.Age = S2.Age is true (20 = 20).
■ S1.StudentID < S2.StudentID is true (101 < 105). So, this pair (Alice, Eve) is
included.
■ Later, when Eve (ID 105) is S1 and Alice (ID 101) is S2: S1.StudentID <
S2.StudentID (105 < 101) would be false, so this duplicate pair is skipped. It also
ensures a student isn't compared to themselves (101 < 101 is false).
● Output: | Student1Name | Age | Student2Name | Age | | :----------- | :-- | :-----------
| :-- | | Alice | 20 | Eve | 20 |
4. Views: Your Custom Window into Data
A View is like a saved query. It's a "virtual table" because it doesn't actually store data itself.
Instead, it's a definition that tells the database how to assemble data from one or more
underlying tables whenever you query the view. Think of it as a custom lens or filter you apply
to your data.
4.1. Create a View
● What it does: Defines a new "virtual table" based on a SELECT query.
● Analogy: You tell the librarian, "Whenever I ask for 'My Favorite Books List', show me all
books by my top 3 authors published after 2020." You're defining a shortcut for a
complex query.
● Example: Create a view that shows the StudentID, Name, and Major of students only in
'Computer Science'.
● SQL:
SQL
CREATE VIEW ComputerScienceStudents AS
SELECT StudentID, Name, Major
FROM Students
WHERE Major = 'Computer Science';
● Explanation:
○ CREATE VIEW ComputerScienceStudents: "I want to make a new view and call it
ComputerScienceStudents."
○ AS: "The definition of this view is (what comes next)..."
○ SELECT StudentID, Name, Major FROM Students WHERE Major = 'Computer
Science';: "...this query. So, whenever someone uses ComputerScienceStudents, run
this query behind the scenes."
4.2. Using a View
● What it does: You query a view just like you would a regular table.
● Analogy: You just ask the librarian for "My Favorite Books List," and they already know
the complex query to run to get it for you.
● Example: Get the name and ID of a specific student from the ComputerScienceStudents
view.
● SQL:
SQL
SELECT Name, StudentID
FROM ComputerScienceStudents -- Using the view like a table
WHERE StudentID = 101;
● Explanation:
○ FROM ComputerScienceStudents: "Get data from my ComputerScienceStudents
view."
○ The database now knows to execute the SELECT StudentID, Name, Major FROM
Students WHERE Major = 'Computer Science' query first.
○ Then, it applies the WHERE StudentID = 101 condition to the result of that query.
● Output: | Name | StudentID | | :---- | :-------- | | Alice | 101 |
4.3. Updating a View (and its limitations)
● What it does: For simple views, you can sometimes use INSERT, UPDATE, or DELETE
statements on the view, and these changes will directly affect the underlying base table.
However, this is heavily restricted for complex views.
● Analogy (simple view): If your "My Favorite Books List" view only filters books from one
shelf and shows all columns, you might be able to add a new book to that shelf through
the view.
● Example (Hypothetical successful update):
SQL
-- If 'ComputerScienceStudents' was a simple enough view, this *might* work:
UPDATE ComputerScienceStudents
SET Name = 'Alicia'
WHERE StudentID = 101;
-- Then, to confirm the change in the original table:
SELECT StudentID, Name FROM Students WHERE StudentID = 101;
● Explanation:
○ UPDATE ComputerScienceStudents SET Name = 'Alicia' WHERE StudentID = 101;:
"Change the Name to 'Alicia' for the student with StudentID 101, by going through
the ComputerScienceStudents view."
○ The database would translate this into an update on the original Students table.
● Why are there limitations?
○ If a view combines data from multiple tables (with joins), how would an UPDATE know
which table to modify?
○ If a view uses aggregate functions (COUNT, AVG), how can you update an average?
It's a calculated value, not stored data.
○ If a view omits certain columns, what values would be inserted if you tried to INSERT
into it?
○ Because of these complexities, many views are "read-only."
4.4. Dropping a View
● What it does: Deletes the definition of the view. The view no longer exists.
● Analogy: You decide you don't need "My Favorite Books List" shortcut anymore, so you
discard its definition. The books on the shelves (the actual data) are not affected.
● Example: Remove the ComputerScienceStudents view.
● SQL:
SQL
DROP VIEW ComputerScienceStudents;
● Explanation:
○ DROP VIEW ComputerScienceStudents;: "Permanently remove the view named
ComputerScienceStudents."
○ This command only affects the view itself; the Students table and its data remain
exactly as they were.
I know this was a lot, but by breaking down each command and concept with analogies and
step-by-step explanations, I hope it makes database queries and structures much clearer!