SQL SELECT Queries for Beginners: WHERE, ORDER BY & Conditions Explained

DBMS Chapter 11 · SQL Query Builder Workshop
SQL SELECT Queries for Beginners: WHERE, ORDER BY & Conditions Explained

This chapter teaches you how to read data from a database using SELECT. You will learn how to choose columns, choose a table, filter rows with WHERE, combine conditions with AND, OR and NOT, search ranges with BETWEEN, test lists with IN, find patterns with LIKE, handle NULL correctly, remove duplicate results with DISTINCT, rename output with aliases, sort rows with ORDER BY and limit results where your DBMS supports it. Every query uses a small student database so you can understand the logic in one reading.

Beginner to strong foundation Interactive query builder WHERE conditions ORDER BY sorting Solved SQL examples Checked: 18 September 2026
First understand what SELECT really does

What Is a SELECT Query in SQL?

SQL SELECT Queries for Beginners: WHERE, ORDER BY & Conditions Explained

A SELECT query asks the database to return data. You choose which columns you want, where the data should come from, which rows should remain, and how the final result should be arranged.

Suppose your college has 10,000 student records. You usually do not want all rows and all columns. You may want only the names of CSE students in semester 2, sorted alphabetically. SELECT lets you describe exactly that result.

SELECTWhich columns?
FROMWhich table?
WHEREWhich rows?
ORDER BYWhat order?
ResultFinal output

Shortcut #1: Columns → Table → Rows → Order

SELECT → FROM → WHERE → ORDER BY

If SQL data types, literals, commands and operators are still new, revise SQL Basics in DBMS: Data Types, Literals, Commands & Operators Explained first. This chapter assumes you already know what a table, column, string literal and comparison operator are.

One table for the whole chapter

Student Table Used in All Examples

student_idnamebranchsemestermarkscityemail
S01AshaCSE285Patnaasha@example.com
S02RaviECE272Delhiravi@example.com
S03NehaCSE191Patnaneha@example.com
S04AmanME366LucknowNULL
S05RiyaCSE278Delhiriya@example.com

Using one table again and again makes the chapter easier because you only learn the SQL, not a new dataset every time.

Pictorial + interactive practice

Interactive SQL Query Builder

Choose columns, a condition and sorting. The query and result will update together.

Build your query

SELECT name, branch FROM Student WHERE branch = 'CSE' ORDER BY name ASC;

Result preview

namebranch
AshaCSE
NehaCSE
RiyaCSE
First WHERE keeps CSE rows. Then ORDER BY sorts the final result by name.
Part 01 · choose columns and source

SELECT and FROM Explained From Zero

SELECT chooses output columns

SELECTWhich columns or expressions should appear in the result?
FROMWhich table or relation should SQL read?

Select all columns

SELECT *
FROM Student;

The asterisk means all columns.

Select specific columns

SELECT name, branch
FROM Student;

This query returns only name and branch. The database does not need to show student_id, semester, marks, city or email in the result.

Column order in SELECT matters for display

SELECT branch, name
FROM Student;

The result now shows branch before name because that is the order written in the SELECT list.

Shortcut #2: SELECT controls what you see

It does not change the stored table. It only controls the query result.

Remove repeated result rows

DISTINCT in SELECT

Suppose several students belong to CSE. This query:

SELECT branch
FROM Student;

may show CSE multiple times because several rows have that value.

SELECT DISTINCT branch
FROM Student;

DISTINCT removes duplicate rows from the final SELECT result.

DISTINCT works on the whole selected row

SELECT DISTINCT branch, semester
FROM Student;

Now uniqueness is checked on the combination of branch and semester, not only branch.

Shortcut #3: DISTINCT = keep unique result rows

Make output easier to read

Column and Table Aliases

Column alias

SELECT name AS student_name,
       marks AS exam_marks
FROM Student;

AS gives a temporary readable name to an output column.

Table alias

SELECT s.name, s.branch
FROM Student AS s;

s is a short temporary name for Student. Table aliases become especially useful when joins are introduced later.

The original database column or table name is not renamed permanently by these aliases.

Part 02 · filter rows

WHERE Clause Explained Simply

WHERE decides which rows remain

The condition is checked for each candidate row. Rows for which the condition is TRUE remain in the result. Rows for which it is FALSE or UNKNOWN are filtered out.

Example: CSE students

SELECT *
FROM Student
WHERE branch = 'CSE';

Example: marks at least 80

SELECT name, marks
FROM Student
WHERE marks >= 80;

Example: one exact student ID

SELECT *
FROM Student
WHERE student_id = 'S03';

Shortcut #4: WHERE = row filter

SELECT chooses columns · WHERE chooses rows
Build simple conditions

Comparison Operators in WHERE

=Equal to
<>Not equal to in standard SQL; many DBMSs also support !=
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Examples

WHERE marks = 85
WHERE semester <> 1
WHERE marks > 70

Character values are usually written as string literals using single quotes:

WHERE city = 'Patna'
Part 03 · combine conditions

AND, OR and NOT in SQL

AND: all conditions must be true

SELECT name
FROM Student
WHERE branch = 'CSE'
  AND semester = 2;

Result: Asha and Riya.

OR: at least one condition must be true

SELECT name, branch
FROM Student
WHERE branch = 'CSE'
   OR branch = 'ECE';

NOT: reverse a condition

SELECT name, city
FROM Student
WHERE NOT city = 'Patna';

A clearer equivalent in many cases is:

WHERE city <> 'Patna'

Shortcut #5: AND = both · OR = either · NOT = reverse

A common source of wrong answers

AND, OR and Parentheses: Operator Precedence

SQL commonly evaluates NOT before AND, and AND before OR. That means a query may not mean what you think it means if you mix conditions carelessly.

Ambiguous-looking query

WHERE branch = 'CSE'
   OR branch = 'ECE'
  AND semester = 2

The AND part is evaluated more tightly than the OR part.

Clear query

WHERE
  (branch = 'CSE' OR branch = 'ECE')
  AND semester = 2

Parentheses clearly show the intended logic.

Shortcut #6: If the condition looks long, add parentheses

Range conditions

BETWEEN: Search Inside a Range

SELECT name, marks
FROM Student
WHERE marks BETWEEN 70 AND 90;

BETWEEN is generally inclusive, so both 70 and 90 are included.

A similar condition can be written as:

WHERE marks >= 70
  AND marks <= 90

NOT BETWEEN

WHERE marks NOT BETWEEN 70 AND 90

This keeps values outside the range, subject to NULL behavior.

List conditions

IN: Match Any Value From a List

Instead of writing many OR conditions:

WHERE branch = 'CSE'
   OR branch = 'ECE'
   OR branch = 'ME'

you can write:

WHERE branch IN ('CSE', 'ECE', 'ME')

NOT IN

WHERE branch NOT IN ('CSE', 'ECE')

NULL warning: NOT IN can behave unexpectedly when a subquery or list contains NULL. For beginner fixed lists without NULL, the idea is simple; when you reach subqueries, revisit NULL semantics carefully.

Shortcut #7: IN = cleaner OR list

Pattern matching

LIKE With % and _ Wildcards

LIKE searches character patterns.

Names starting with A

WHERE name LIKE 'A%'

% represents any sequence of zero or more characters in common SQL pattern syntax.

Names ending with a

WHERE name LIKE '%a'

Second character is a

WHERE name LIKE '_a%'

_ represents one character.

Case sensitivity

Whether LIKE 'a%' matches names beginning with uppercase A depends on the DBMS, collation and configuration. Do not assume identical behavior everywhere.

Important condition rule

IS NULL and IS NOT NULL

NULL means the absence of a normal value. It is not zero and it is not the text 'NULL'.

Find students without an email

SELECT name
FROM Student
WHERE email IS NULL;

Find students with an email

SELECT name, email
FROM Student
WHERE email IS NOT NULL;

Wrong idea

WHERE email = NULL

Correct test

WHERE email IS NULL

NULL uses SQL's three-valued logic. Comparisons involving NULL can become UNKNOWN rather than TRUE or FALSE.

For the deeper database meaning of NULL and key constraints, revise Integrity Constraints in DBMS.

Part 04 · sort the result

ORDER BY: Sort Query Results

ORDER BY controls display order

It does not permanently rearrange the stored rows. It only sorts the result returned by the query.

Ascending order

SELECT name, marks
FROM Student
ORDER BY marks ASC;

ASC means ascending and is commonly the default.

Descending order

SELECT name, marks
FROM Student
ORDER BY marks DESC;

Sort by more than one column

SELECT name, branch, marks
FROM Student
ORDER BY branch ASC, marks DESC;

First SQL groups the display by branch order. Inside the same branch, higher marks appear first.

Shortcut #8: ORDER BY = final arrangement

Sort expressions and aliases

ORDER BY With Aliases and Expressions

SELECT name,
       marks + 5 AS adjusted_marks
FROM Student
ORDER BY adjusted_marks DESC;

Many DBMSs allow an output alias to be used in ORDER BY. This makes long expressions easier to read.

You may also see queries that sort by column position such as ORDER BY 2, but explicit names are usually clearer and safer for readable code.

Return only a few rows

LIMIT, TOP and FETCH FIRST

Limiting rows is useful for “top 5,” preview and pagination-style queries, but syntax differs by DBMS.

MySQL / PostgreSQL styleLIMIT 5
SQL Server styleSELECT TOP 5 ...
Standard-style patternFETCH FIRST 5 ROWS ONLY where supported.

Example idea: top 3 marks

SELECT name, marks
FROM Student
ORDER BY marks DESC
FETCH FIRST 3 ROWS ONLY;

Use the syntax supported by your actual DBMS.

Shortcut #9: Sort first, limit second

Without ORDER BY, “first 3” does not mean “top 3.”

SELECT can calculate values too

Expressions Inside SELECT

SELECT name,
       marks,
       marks + 5 AS bonus_marks
FROM Student;

SELECT can return stored columns and calculated expressions together.

Simple CASE expression

SELECT name,
       marks,
       CASE
         WHEN marks >= 80 THEN 'Strong'
         WHEN marks >= 60 THEN 'Average'
         ELSE 'Needs Improvement'
       END AS performance
FROM Student;

CASE lets a query produce different output based on conditions. It is useful once basic WHERE logic is clear.

Conditions on text values

Text Conditions and Case Sensitivity

These look similar:

WHERE city = 'Patna'
WHERE city = 'patna'

Whether they match the same rows depends on the database system and collation settings.

For portable beginner SQL, do not assume all systems compare text with the same case-sensitivity rules.

Written order vs logical processing

SQL Query Written Order and Logical Processing Order

You usually write a query like this:

SELECT name, branch
FROM Student
WHERE semester = 2
ORDER BY name;

But a useful beginner mental model for logical processing is:

FROMFind source rows
WHEREFilter rows
SELECTBuild output columns
DISTINCTRemove duplicates if asked
ORDER BYSort final output

This mental model explains why WHERE generally cannot use a SELECT alias in many systems: WHERE is logically evaluated before the SELECT list creates that alias.

The DBMS optimizer may use a physically different execution plan internally. The model above is for understanding query semantics, not predicting exact low-level execution.

Complete solved query

Solved Example: CSE or ECE Students With Good Marks

Question

Show the name, branch and marks of students who are in CSE or ECE, have marks of at least 75, and sort them from highest marks to lowest.

Choose output columnsname, branch, marks.
Choose sourceStudent.
Build branch conditionbranch IN ('CSE', 'ECE').
Add marks conditionmarks >= 75.
Sort resultORDER BY marks DESC.
SELECT name, branch, marks
FROM Student
WHERE branch IN ('CSE', 'ECE')
  AND marks >= 75
ORDER BY marks DESC;
namebranchmarks
NehaCSE91
AshaCSE85
RiyaCSE78
Practice patterns students should know

10 Useful SELECT Query Patterns

-- 1. All rows and columns
SELECT * FROM Student;

-- 2. Specific columns
SELECT name, branch FROM Student;

-- 3. One exact condition
SELECT * FROM Student
WHERE branch = 'CSE';

-- 4. Multiple conditions
SELECT name FROM Student
WHERE branch = 'CSE' AND semester = 2;

-- 5. List condition
SELECT name FROM Student
WHERE city IN ('Patna', 'Delhi');

-- 6. Range condition
SELECT name, marks FROM Student
WHERE marks BETWEEN 70 AND 90;

-- 7. Pattern condition
SELECT name FROM Student
WHERE name LIKE 'A%';

-- 8. NULL condition
SELECT name FROM Student
WHERE email IS NULL;

-- 9. Unique values
SELECT DISTINCT branch FROM Student;

-- 10. Sorted result
SELECT name, marks FROM Student
ORDER BY marks DESC;
Preview of the next SQL level

WHERE vs HAVING: Do Not Confuse Them

WHERE filters rows before grouping. HAVING filters groups after GROUP BY.

WHERE

Used with normal row conditions.

WHERE marks >= 80

HAVING

Used for conditions on grouped/aggregate results.

HAVING COUNT(*) > 5

GROUP BY, aggregate functions and HAVING deserve a separate deep chapter, so this section is only a preview.

Practical safety note

Do Not Build Real Queries by Joining Raw User Input

When building real applications, do not create SQL by directly concatenating untrusted user input into query strings. That can create SQL injection vulnerabilities.

Use parameterized queries or prepared statements provided by your programming language or database library.

Shortcut #10: Values should be parameters, not pasted SQL

This is an application-development rule rather than a semester SELECT-syntax rule, but it is important from the beginning.

Common beginner mistakes

SELECT Query Mistakes to Avoid

Using double meaning for SELECTSELECT chooses result columns; WHERE filters rows.
Writing text without quotesUse 'CSE', not bare CSE.
Using = NULLUse IS NULL or IS NOT NULL.
Mixing AND and OR without parenthesesPrecedence can change the result.
Forgetting DESCORDER BY is ascending by default in common SQL behavior.
Using LIMIT syntax everywhereRow-limiting syntax varies by DBMS.
Thinking DISTINCT affects one column onlyIt applies to the whole selected result row.
Assuming LIKE is always case-sensitiveBehavior depends on DBMS and collation.
Using NOT IN carelessly with NULLNULL can make conditions evaluate to UNKNOWN.
Thinking ORDER BY changes stored rowsIt only changes result display order.
Connect SQL with the theory you already learned

How SELECT Connects to Relational Algebra

SQL is not identical to Relational Algebra, but beginner SELECT queries connect naturally with its ideas.

WHERESimilar to relational-algebra selection: choose rows.
SELECT column listSimilar to projection: choose output columns.
DISTINCTMoves SQL result behavior closer to set-style uniqueness.
JOINConnects related rows from multiple tables.

For the full theory, revise Relational Algebra in DBMS: Operations With Solved Examples. The declarative viewpoint behind SQL also connects with Relational Calculus.

Write according to marks

How to Write SELECT Queries in Semester Exams

2 marks

Syntax + one line

Write the basic SELECT-FROM-WHERE syntax and one short example.

5 marks

Explain conditions

Show WHERE with comparison operators, AND/OR, BETWEEN, IN or LIKE using a small table.

8-10 marks

Full query family

Explain SELECT, DISTINCT, aliases, WHERE conditions, NULL handling, ORDER BY and one multi-condition solved query.

For presentation technique, use How to Write High-Scoring Answers in University Semester Exams. For unit priority, use the previous-year-paper method.

Practice questions with answers

Practice Questions With Answers

1. What does SELECT do in SQL?

SELECT defines which columns or expressions should appear in the query result.

2. What is the purpose of FROM?

FROM identifies the table or source from which the query reads data.

3. What does WHERE do?

WHERE filters rows using a condition. Rows that do not satisfy the condition are excluded from the result.

4. What is the difference between AND and OR?

AND requires all connected conditions to be true. OR requires at least one connected condition to be true.

5. Is BETWEEN inclusive?

Yes, SQL BETWEEN is generally inclusive of both boundary values.

6. What is the difference between IN and OR?

IN is a compact way to test whether one expression matches any value in a list or subquery result. For a simple fixed list, it can replace several equality conditions connected with OR.

7. What do % and _ mean in LIKE?

% commonly matches any sequence of characters, while _ matches one character.

8. Why is = NULL wrong?

NULL follows special three-valued logic, so IS NULL or IS NOT NULL is used to test its presence.

9. What is the use of ORDER BY?

ORDER BY sorts the final query result using one or more expressions in ascending or descending order.

10. What does DISTINCT do?

DISTINCT removes duplicate rows from the SELECT result based on the complete selected expression list.

60-second revision

SELECT Queries One-Minute Revision Sheet

SELECTChoose output columns or expressions.
FROMChoose the source table.
WHEREFilter rows.
DISTINCTRemove duplicate result rows.
ASCreate a temporary alias.
ANDAll connected conditions must be true.
ORAt least one connected condition must be true.
NOTReverse a condition.
BETWEENInclusive range test.
INMatch one value from a list/result.
LIKEPattern matching.
IS NULLTest for NULL.
ORDER BYSort final output.
DESCDescending sort order.

Ultimate memory line

SELECT what · FROM where · WHERE which rows · ORDER BY what order
Frequently asked questions

Frequently Asked Questions

How do I write a basic SELECT query in SQL?

Start with SELECT for the required columns, FROM for the source table, add WHERE when rows need filtering, and use ORDER BY when the result needs sorting.

What is the difference between SELECT and WHERE?

SELECT chooses the columns or expressions shown in the result, while WHERE chooses which rows are allowed into that result.

What is the difference between WHERE and ORDER BY?

WHERE filters rows. ORDER BY sorts the rows that remain in the final result.

How do AND and OR work in SQL conditions?

AND requires every connected condition to be true, while OR requires at least one condition to be true. Parentheses should be used when mixed logic could be unclear.

How do I search for NULL values?

Use IS NULL to find NULL values and IS NOT NULL to find rows where a normal value is present.

What should I study after SELECT, WHERE and ORDER BY?

Study aggregate functions, GROUP BY, HAVING, joins, subqueries, set operations and views. These are the next major SQL query topics.

Next chapter

What Should You Learn Next?

Next: Aggregate Functions, GROUP BY & HAVING

You now know how to choose columns, filter rows and sort output. The next step is to summarize many rows using COUNT, SUM, AVG, MIN and MAX, create groups with GROUP BY, and filter grouped results with HAVING.

After that, continue with joins, subqueries, set operations and views. For video revision after reading, use the DBMS YouTube study guide only as a secondary resource.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources