SQL beginner course · Chapter 3 of 10
SQL SELECT Queries: WHERE, DISTINCT, ORDER BY and HAVING explained in simple steps. Examples use practice tables such as students and scores; adapt names to your database.
SELECT columns
SELECT returns chosen columns from a table. Prefer naming the columns you need over SELECT * in application code.
Example
SELECT student_name, grade FROM students;Expected result: Only name and grade are returned.
Practice: Predict the result, run the query on a practice database, then change one part and explain what changed. For write commands, use disposable data.
WHERE and comparison
WHERE tests each row before it reaches the result. =, <, > and <> compare values; use IS NULL for unknown values.
Example
SELECT student_name FROM students WHERE grade >= 8;Expected result: Students in grade 8 or above appear.
Practice: Predict the result, run the query on a practice database, then change one part and explain what changed. For write commands, use disposable data.
DISTINCT
DISTINCT removes repeated combinations of selected values. It does not change the stored table.
Example
SELECT DISTINCT grade FROM students;Expected result: Each grade appears once.
Practice: Predict the result, run the query on a practice database, then change one part and explain what changed. For write commands, use disposable data.
ORDER BY
ORDER BY sorts the final result. ASC is ascending; DESC puts high values first. Sorting by a second column breaks ties.
Example
SELECT student_name, grade FROM students ORDER BY grade DESC, student_name ASC;Expected result: Highest grades appear first, then names alphabetically.
Practice: Predict the result, run the query on a practice database, then change one part and explain what changed. For write commands, use disposable data.
GROUP BY and HAVING
GROUP BY creates groups, usually for aggregate results. WHERE filters rows before grouping; HAVING filters groups afterward.
Example
SELECT grade, COUNT(*) AS total FROM students GROUP BY grade HAVING COUNT(*) >= 2;Expected result: Only grades containing at least two students appear.
Practice: Predict the result, run the query on a practice database, then change one part and explain what changed. For write commands, use disposable data.
Quick review
Explain each concept in your own words. Recreate one example without looking at the code. Compare your result with the expected result above.
Browse the full SQL learning path. This is original teaching material; the syllabus was checked against the w3resource SQL tutorial index.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.