LESSON 9 OF 14

SELECT Queries, Filtering, and Sorting

This lesson explains how to retrieve selected columns and rows with T-SQL SELECT queries, apply conditions, handle NULL values, and sort results.

75 dk 86

Introduction

In the previous lesson, you learned how to insert, update, and delete data with T-SQL. This lesson focuses on reading data from SQL Server in a controlled and meaningful way. The SELECT statement is one of the most frequently used SQL commands for creating reports, supplying data to applications, and inspecting table contents.

A basic SELECT query can return every column and row in a table. In real projects, however, you usually need to select only the required columns, filter rows according to business rules, remove duplicate values, and return the result in a predictable order. In this lesson, you will use WHERE, DISTINCT, LIKE, IN, BETWEEN, IS NULL, AND, OR, and ORDER BY.

Sample table and basic SELECT syntax

The examples assume that the KursDB database and the dbo.Urunler table were created in earlier lessons. Assume that the table contains at least the following columns:

ColumnDescription
UrunIDUnique product identifier
UrunAdiProduct name
KategoriProduct category
FiyatProduct price
StokAdediQuantity in stock
RenkProduct color; may be empty

First, select the correct database:

USE KursDB;
GO

To return every column and row, you can use the asterisk:

SELECT *
FROM dbo.Urunler;

This is useful for quick inspection, but it is usually better to name the required columns in application and reporting queries. A table may gain new columns over time, and returning unnecessary data can increase network and processing costs:

SELECT UrunID, UrunAdi, Fiyat
FROM dbo.Urunler;

Filtering rows with WHERE

The WHERE clause returns only rows that satisfy a specified condition. The following query lists products whose price is greater than 1000:

SELECT UrunID, UrunAdi, Fiyat
FROM dbo.Urunler
WHERE Fiyat > 1000;

Common comparison operators include =, <>, >, <, >=, and <=. Text values are written inside single quotation marks:

SELECT UrunAdi, Kategori
FROM dbo.Urunler
WHERE Kategori = 'Elektronik';

In SQL Server, the behavior of text comparisons with respect to uppercase and lowercase letters can depend on the database or column collation. Therefore, matching behavior may differ between environments with different collation settings.

Using AND and OR

Use AND when all conditions must be true. The following query returns products that belong to the Electronics category and cost more than 1000:

SELECT UrunAdi, Kategori, Fiyat
FROM dbo.Urunler
WHERE Kategori = 'Elektronik'
  AND Fiyat > 1000;

Use OR when at least one condition may be true:

SELECT UrunAdi, Kategori
FROM dbo.Urunler
WHERE Kategori = 'Elektronik'
   OR Kategori = 'Ofis';

When AND and OR are combined, parentheses make the intended logic explicit. In T-SQL, AND has higher precedence than OR. These two examples may therefore produce different results:

-- Without parentheses
SELECT UrunAdi, Kategori, Fiyat
FROM dbo.Urunler
WHERE Kategori = 'Elektronik'
   OR Kategori = 'Ofis'
  AND Fiyat > 1000;

-- Explicit and controlled logic
SELECT UrunAdi, Kategori, Fiyat
FROM dbo.Urunler
WHERE (Kategori = 'Elektronik' OR Kategori = 'Ofis')
  AND Fiyat > 1000;

Removing duplicate values with DISTINCT

To see the different category values stored in a column, use DISTINCT:

SELECT DISTINCT Kategori
FROM dbo.Urunler;

When more than one column is selected, uniqueness is evaluated for the combination of those columns:

SELECT DISTINCT Kategori, Renk
FROM dbo.Urunler;

This query returns different category-color combinations. Because DISTINCT may require additional processing on large result sets, use it when removing duplicates is actually part of the requirement.

Searching text patterns with LIKE

The LIKE operator finds values that match a text pattern rather than requiring exact equality. Common wildcard characters include:

  • %: Represents zero or more characters.
  • _: Represents exactly one character.
  • [abc]: Matches one character from the specified set.
  • [^abc]: Matches one character not in the specified set.

To find products whose names begin with the letter “K”:

SELECT UrunID, UrunAdi
FROM dbo.Urunler
WHERE UrunAdi LIKE 'K%';

To find products containing “pro” anywhere in the name, place the percent wildcard on both sides:

SELECT UrunAdi
FROM dbo.Urunler
WHERE UrunAdi LIKE '%pro%';

To find names whose second character is “a”, use an underscore:

SELECT UrunAdi
FROM dbo.Urunler
WHERE UrunAdi LIKE '_a%';

The wildcard pattern must match the requirement. For example, LIKE 'K' matches only the value “K”, while LIKE 'K%' matches values that begin with “K”.

Filtering from a list with IN

When one column must be compared with several possible values, IN is clearer than a long sequence of OR conditions:

SELECT UrunAdi, Kategori
FROM dbo.Urunler
WHERE Kategori IN ('Elektronik', 'Ofis', 'Kırtasiye');

This is logically similar to:

WHERE Kategori = 'Elektronik'
   OR Kategori = 'Ofis'
   OR Kategori = 'Kırtasiye'

To exclude the listed values, use NOT IN:

SELECT UrunAdi, Kategori
FROM dbo.Urunler
WHERE Kategori NOT IN ('Elektronik', 'Ofis');

Be careful with NOT IN when NULL values are possible in the compared column or in a subquery result. NULL introduces an unknown comparison result, so a separate IS NULL condition may be required.

Filtering ranges with BETWEEN

The BETWEEN operator checks whether a value falls within two boundaries. In SQL Server, both boundary values are included:

SELECT UrunAdi, Fiyat
FROM dbo.Urunler
WHERE Fiyat BETWEEN 500 AND 1500;

This includes products priced at exactly 500 or exactly 1500. The same condition can be written as:

WHERE Fiyat >= 500 AND Fiyat <= 1500

When filtering dates, be aware of the time portion of datetime values. A condition that uses a date at midnight as the upper boundary may omit rows later on that same day. For date-time filtering, an inclusive lower boundary and an exclusive next-day upper boundary is often safer. The main focus here is numeric ranges, but the same boundary principle is important in future queries.

Checking NULL values with IS NULL

NULL does not mean zero or an empty string. It represents an unknown, missing, or inapplicable value. For that reason, = NULL and <> NULL should not be used to test for NULL. Use IS NULL and IS NOT NULL instead:

SELECT UrunAdi, Renk
FROM dbo.Urunler
WHERE Renk IS NULL;
SELECT UrunAdi, Renk
FROM dbo.Urunler
WHERE Renk IS NOT NULL;

For example, later lessons may use functions such as COALESCE to display a substitute label for a missing color. When filtering rows, however, the direct and correct form is IS NULL or IS NOT NULL.

Sorting results with ORDER BY

When an ORDER BY clause is not specified, SQL Server does not guarantee the order in which rows are returned. If a screen or report requires a meaningful order, include ORDER BY.

Sort prices from lowest to highest:

SELECT UrunAdi, Fiyat
FROM dbo.Urunler
ORDER BY Fiyat ASC;

ASC is the default direction. To sort from highest to lowest, use DESC:

SELECT UrunAdi, Fiyat
FROM dbo.Urunler
ORDER BY Fiyat DESC;

You can sort by multiple columns. The following query sorts categories in ascending order and products within each category by descending price:

SELECT UrunAdi, Kategori, Fiyat
FROM dbo.Urunler
ORDER BY Kategori ASC, Fiyat DESC;

You can use a column alias in the ORDER BY clause:

SELECT UrunAdi, Fiyat AS ListeFiyati
FROM dbo.Urunler
ORDER BY ListeFiyati DESC;

For consistent results, consider adding a unique column such as UrunID as a secondary sort key when the primary sort values can be equal.

Combined example

The following query returns products from the Electronics or Office categories, priced between 500 and 3000, whose names begin with “A” and whose color is not NULL. The most expensive products appear first:

SELECT UrunID, UrunAdi, Kategori, Fiyat, Renk
FROM dbo.Urunler
WHERE Kategori IN ('Elektronik', 'Ofis')
  AND Fiyat BETWEEN 500 AND 3000
  AND UrunAdi LIKE 'A%'
  AND Renk IS NOT NULL
ORDER BY Fiyat DESC, UrunID ASC;

The written structure of a query is commonly SELECT, FROM, WHERE, and ORDER BY. Although the SQL Server query processor uses its own logical and physical processing stages, keeping this readable clause order makes queries easier to understand and maintain.

Common mistakes

  • Using equality with NULL: WHERE Renk = NULL does not perform the expected test. Use WHERE Renk IS NULL.
  • Using double quotes for text: Use single quotes for string literals, such as 'Elektronik'.
  • Omitting parentheses: Add parentheses when combining AND and OR so the business rule is unambiguous.
  • Expecting a default row order: A table may appear to return rows in a familiar order, but that order is not guaranteed without ORDER BY.
  • Always using SELECT *: Name the required columns to avoid unnecessary data and unstable result shapes.
  • Building the LIKE pattern incorrectly: Use 'A%' for values beginning with A and '%A%' for values containing A anywhere.

Short practice exercise

Complete the following tasks using dbo.Urunler:

  1. List the product name, category, and stock quantity.
  2. Find products with fewer than 10 items in stock.
  3. Filter products in the Electronics, Office, or Stationery categories with IN.
  4. List products whose price is between 250 and 750.
  5. Find products without a specified color using IS NULL.
  6. Search for products whose names contain “kit” with LIKE.
  7. Sort results by stock quantity descending, then by product name ascending when quantities are equal.

One possible solution is:

SELECT UrunAdi, Kategori, StokAdedi, Fiyat, Renk
FROM dbo.Urunler
WHERE StokAdedi < 10
  AND Kategori IN ('Elektronik', 'Ofis', 'Kırtasiye')
  AND UrunAdi LIKE '%kit%'
ORDER BY StokAdedi DESC, UrunAdi ASC;

Conclusion

This lesson showed how to use SELECT not merely to display data, but to produce precise and useful result sets. You selected specific columns, filtered rows with WHERE, removed duplicates with DISTINCT, searched patterns with LIKE, and applied list and range filters with IN and BETWEEN. You also learned to test missing values with IS NULL and sort results with ORDER BY.

In the next stage, these filtering techniques will be combined with JOIN expressions to retrieve related data from multiple tables. The concepts covered here therefore form the foundation for nearly every later T-SQL query.

Sources