SQL Server Day 2

Master data retrieval, filtering, sorting, logical operators (AND, OR, NOT), range filters (IN, BETWEEN), and text pattern matching with LIKE and wildcards.

Quick Warm-Up: Day 1 Revision

Test your memory from Day 1 before writing today's queries. Tap any question to check your answer.

SQL Server is a Database Management System (DBMS) developed by Microsoft to store, manage, and retrieve data.
SQL Server Management Studio (SSMS) is the graphical tool used to connect to SQL Server and write SQL queries.
CREATE DATABASE StudentDB;
USE StudentDB;
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(100) );
INSERT INTO Students VALUES (1, 'Rahul');
SELECT * FROM Students;
UPDATE Students SET Name = 'Ravi' WHERE StudentID = 1;
DELETE FROM Students WHERE StudentID = 1;
VARCHAR (for standard variable-length text) or NVARCHAR (for Unicode text like Telugu and Hindi).

Practical Setup: CollegeDB & SELECT

Let us create a fresh database called CollegeDB, build our Students table, and insert five student records to practice with.

-- Create and switch to CollegeDB
CREATE DATABASE CollegeDB;
GO

USE CollegeDB;
GO

-- Create Students table
CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    Name VARCHAR(100),
    Age INT,
    Course VARCHAR(50),
    Marks INT,
    City VARCHAR(50)
);

-- Insert sample records
INSERT INTO Students VALUES
(1, 'Rahul', 20, 'Python', 90, 'Hyderabad'),
(2, 'Anjali', 21, 'SQL', 95, 'Chennai'),
(3, 'Kiran', 22, 'Java', 78, 'Bangalore'),
(4, 'Priya', 20, 'Python', 85, 'Hyderabad'),
(5, 'Arjun', 23, 'SQL', 92, 'Delhi');

Retrieving Data with SELECT

SELECT is used to retrieve data from a table. You can fetch every column with * or pick only the exact columns you need.

-- Display everything
SELECT *
FROM Students;

-- Display only Name
SELECT Name
FROM Students;

-- Display Name and Course
SELECT Name, Course
FROM Students;
Class Pop Quiz #1

1. Which query displays only the Name and City of all students?

WHERE Clause & Comparison Operators

The WHERE clause filters records so SQL Server returns only the rows that match your condition.

-- Age greater than 20
SELECT *
FROM Students
WHERE Age > 20;

-- Marks 90 and above
SELECT *
FROM Students
WHERE Marks >= 90;

-- Only Python students
SELECT *
FROM Students
WHERE Course = 'Python';

-- Students from Hyderabad
SELECT *
FROM Students
WHERE City = 'Hyderabad';

Comparison Operators

Operator Meaning Example Condition
=Equal toCourse = 'SQL'
>Greater thanAge > 20
<Less thanMarks < 85
>=Greater than or equalMarks >= 90
<=Less than or equalAge <= 21
<>Not equalMarks <> 90

Example using the Not Equal (<>) operator:

SELECT *
FROM Students
WHERE Marks <> 90;

Output: Returns Anjali (95), Kiran (78), Priya (85), and Arjun (92) — excluding Rahul (90).

Class Pop Quiz #2

1. Which comparison operator means "Not Equal" in SQL Server?

2. In our Students table, how many rows are returned by SELECT * FROM Students WHERE Marks >= 90;?

ORDER BY, TOP & DISTINCT

Sorting Data with ORDER BY

ORDER BY sorts your query results. By default, it sorts in ascending order (lowest to highest, or A to Z). Add DESC for descending order.

-- Ascending (default)
SELECT *
FROM Students
ORDER BY Marks;

-- Descending (highest marks first)
SELECT *
FROM Students
ORDER BY Marks DESC;

-- Sort alphabetically by Name
SELECT *
FROM Students
ORDER BY Name;

Limiting Rows with TOP

TOP returns only a specific number of rows. Combine TOP with ORDER BY DESC to find top scorers.

-- First three students
SELECT TOP 3 *
FROM Students;

-- Top two marks
SELECT TOP 2 *
FROM Students
ORDER BY Marks DESC;

Output for Top 2 Marks: Anjali (95) and Arjun (92).

Removing Duplicates with DISTINCT

DISTINCT eliminates duplicate values so each unique entry appears only once.

-- Unique courses
SELECT DISTINCT Course
FROM Students;

-- Unique cities
SELECT DISTINCT City
FROM Students;

Unique Courses Output: Python, SQL, Java.

Class Pop Quiz #3

Why is SELECT TOP 2 * FROM Students; different from SELECT TOP 2 * FROM Students ORDER BY Marks DESC;?

Answer: Without ORDER BY Marks DESC, SQL Server simply returns the first 2 rows it reads (Rahul and Anjali). Adding ORDER BY Marks DESC sorts all students by highest marks first and then picks the true top 2 scorers (Anjali with 95 and Arjun with 92).

Practice Questions (Do in Class — CollegeDB)

Try writing each query in SSMS first, then tap any question to verify your SQL command.

SELECT * FROM Students;
SELECT Name FROM Students;
SELECT * FROM Students WHERE Age > 21;
SELECT * FROM Students WHERE Marks > 80;
SELECT * FROM Students WHERE Course = 'SQL';
SELECT * FROM Students WHERE City = 'Hyderabad';
SELECT * FROM Students ORDER BY Name;
SELECT * FROM Students ORDER BY Marks DESC;
SELECT TOP 2 * FROM Students;
SELECT DISTINCT City FROM Students;

Quick Check & CompanyDB Setup

Before diving into AND, OR, NOT, IN, BETWEEN, and LIKE, run through this rapid 7-question recap.

SELECT * FROM Students;
WHERE
ORDER BY
DISTINCT
TOP
>
<>

Create CompanyDB & Employees Table

Execute this script in SSMS to create the CompanyDB database with 10 employee records:

CREATE DATABASE CompanyDB;
GO

USE CompanyDB;
GO

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    Name VARCHAR(100),
    Department VARCHAR(50),
    Salary DECIMAL(10,2),
    City VARCHAR(50),
    Experience INT
);

INSERT INTO Employees VALUES
(1, 'Rahul', 'IT', 45000, 'Hyderabad', 2),
(2, 'Anjali', 'HR', 35000, 'Chennai', 3),
(3, 'Kiran', 'IT', 60000, 'Bangalore', 5),
(4, 'Priya', 'Finance', 50000, 'Hyderabad', 4),
(5, 'Arjun', 'Sales', 30000, 'Delhi', 1),
(6, 'Sneha', 'IT', 70000, 'Hyderabad', 6),
(7, 'Ravi', 'HR', 28000, 'Mumbai', 2),
(8, 'Deepa', 'Finance', 55000, 'Chennai', 4),
(9, 'Ajay', 'Sales', 40000, 'Delhi', 3),
(10, 'Pooja', 'IT', 65000, 'Bangalore', 5);

Logical Operators: AND, OR & NOT

AND (All Conditions Must Be TRUE)

AND displays a row only when every condition is true at the same time.

-- IT employees earning more than 50,000
SELECT *
FROM Employees
WHERE Department = 'IT'
  AND Salary > 50000;

-- Hyderabad employees with 4 or more years of experience
SELECT *
FROM Employees
WHERE City = 'Hyderabad'
  AND Experience >= 4;

First Query Output: Kiran (₹60,000), Sneha (₹70,000), and Pooja (₹65,000) — only IT employees earning more than ₹50,000.

OR (Any One Condition Can Be TRUE)

OR displays a row if at least one of the conditions is true.

-- Employees from Hyderabad or Delhi
SELECT *
FROM Employees
WHERE City = 'Hyderabad'
   OR City = 'Delhi';

-- Employees in HR or Finance
SELECT *
FROM Employees
WHERE Department = 'HR'
   OR Department = 'Finance';

NOT (Exclude Records)

NOT reverses a condition to exclude matching records.

-- Exclude IT department
SELECT *
FROM Employees
WHERE NOT Department = 'IT';

-- Exclude Hyderabad
SELECT *
FROM Employees
WHERE NOT City = 'Hyderabad';
Class Pop Quiz #4

1. In WHERE Department = 'IT' AND Salary > 50000, why is Rahul (IT, ₹45,000) NOT displayed?

2. Who is returned by WHERE City = 'Hyderabad' AND Experience >= 4?

IN, NOT IN & BETWEEN

Cleaner Lists with IN & NOT IN

Instead of repeating multiple OR conditions like WHERE City='Hyderabad' OR City='Delhi' OR City='Chennai', use IN to keep queries clean and readable.

-- Match any city inside the list
SELECT *
FROM Employees
WHERE City IN ('Hyderabad', 'Delhi', 'Chennai');

-- Exclude multiple cities at once
SELECT *
FROM Employees
WHERE City NOT IN ('Hyderabad', 'Delhi');

Range Filtering with BETWEEN

BETWEEN finds values within a starting and ending range (both boundary values are included).

-- Salary between 30,000 and 50,000 (inclusive)
SELECT *
FROM Employees
WHERE Salary BETWEEN 30000 AND 50000;

-- Experience between 2 and 5 years (inclusive)
SELECT *
FROM Employees
WHERE Experience BETWEEN 2 AND 5;
[Pro Tip]: BETWEEN 30000 AND 50000 includes both 30,000 and 50,000. It works exactly like writing Salary >= 30000 AND Salary <= 50000.
Class Pop Quiz #5

1. When running WHERE Salary BETWEEN 30000 AND 50000, are Arjun (₹30,000) and Priya (₹50,000) included?

2. Which clause is the cleanest replacement for multiple OR checks on the same column?

LIKE, Wildcards & Combined Conditions

LIKE searches text columns for patterns using two essential wildcards:

%

Percent Wildcard

Matches any number of characters (zero, one, or many).

_

Underscore Wildcard

Matches exactly one single character in that position.

-- Starts with R
SELECT * FROM Employees WHERE Name LIKE 'R%';

-- Ends with a
SELECT * FROM Employees WHERE Name LIKE '%a';

-- Contains "ee"
SELECT * FROM Employees WHERE Name LIKE '%ee%';

-- Second letter is a
SELECT * FROM Employees WHERE Name LIKE '_a%';

Wildcard Pattern Cheat Sheet

Pattern Matches Example Matches (Employees)
LIKE 'A%'Starts with AAnjali, Arjun, Ajay
LIKE '%a'Ends with aPriya, Sneha, Deepa, Pooja
LIKE '%ra%'Contains "ra" anywhereRahul, Kiran, Ravi
LIKE '_a%'Second letter is aRahul, Ravi

Combined Conditions

In real projects, you combine AND, IN, and comparison operators inside a single WHERE clause:

-- IT employees in Hyderabad earning above 50,000
SELECT *
FROM Employees
WHERE Department = 'IT'
  AND Salary > 50000
  AND City = 'Hyderabad';

-- Employees from Hyderabad or Delhi earning above 35,000
SELECT *
FROM Employees
WHERE City IN ('Hyderabad', 'Delhi')
  AND Salary > 35000;
Class Pop Quiz #6

1. Which LIKE pattern finds all employees whose second letter is 'a'?

2. Who is returned by WHERE Department = 'IT' AND Salary > 50000 AND City = 'Hyderabad'?

Class Activity (CompanyDB)

Write queries for all 10 challenges below in SSMS, then click each card to compare your answer.

SELECT * FROM Employees WHERE City = 'Hyderabad';
SELECT * FROM Employees WHERE City IN ('Hyderabad', 'Bangalore');
SELECT * FROM Employees WHERE NOT Department = 'IT';
SELECT * FROM Employees WHERE Salary BETWEEN 40000 AND 70000;
SELECT * FROM Employees WHERE Name LIKE 'P%';
SELECT * FROM Employees WHERE Name LIKE '%a';
SELECT * FROM Employees WHERE Department IN ('Finance', 'HR');
SELECT * FROM Employees WHERE Experience > 3;
SELECT * FROM Employees WHERE City IN ('Chennai', 'Mumbai');
SELECT * FROM Employees WHERE Name LIKE '%ra%';
Final Boss Challenge

Write a single query on Employees to find the top 2 highest-paid employees from Hyderabad or Bangalore whose names end with 'a' and whose salary is between ₹40,000 and ₹75,000.

Solution: SELECT TOP 2 * FROM Employees WHERE City IN ('Hyderabad', 'Bangalore') AND Name LIKE '%a' AND Salary BETWEEN 40000 AND 75000 ORDER BY Salary DESC;

Output: Sneha (₹70,000, Hyderabad) and Pooja (₹65,000, Bangalore).

Your Day 2 Pop Quiz Score

Answer the clickable quiz questions above to track your score.

0 / 9

Post a Comment

0 Comments