DEV Community

Cover image for Learning SQL? Here is a Practical Guide to Read and Write SQL Queries.
Okall Omondi
Okall Omondi

Posted on

Learning SQL? Here is a Practical Guide to Read and Write SQL Queries.

Introduction

Every web application, BI dashboard, and digital checkout system has one thing in common: it runs on data. User profiles, product inventories, and transaction logs have to live somewhere durable, and that somewhere is almost always a relational database.

To get that data out, you need to talk to the database in a language it understands. That language is SQL.

If you have never written a line of code in your life, SQL is arguably the gentlest entry point into tech. It reads shockingly close to plain English, and unlike other general-purpose languages such as Python, you don't need to instruct the computer how to loop through lists or manage memory. You simply describe what data you want, and the database figures out how to retrieve it.

Let's walk through how it works, how a query is structured, and how you can write your first one today.


What SQL Actually Is

SQL stands for Structured Query Language. People pronounce it either as three individual letters ("S-Q-L") or as "sequel." Both are widely accepted across engineering teams, so use whichever feels natural.

At its core, SQL is a domain-specific language designed to manage and retrieve data stored in a relational database management system (RDBMS). Popular examples of these systems include PostgreSQL, MySQL, SQLite, and Microsoft SQL Server.

While each system has slight dialect differences, the baseline syntax remains remarkably consistent. Once you learn standard SQL, switching between MySQL and PostgreSQL feels like moving between different dialects of English: a few spelling tweaks and regional idioms, but the underlying grammar is identical.

How Data Is Organized

Before querying data, you need a mental model of where it lives.

Think of a relational database as a collection of spreadsheets.

  • A database is the entire workbook.
  • A table is a single sheet within that workbook.
  • A column represents a specific category or attribute (such as email, first_name, or created_at).
  • A row (often called a record) is a single entry across those columns (one specific user or one distinct order).

When you write a query, you are simply asking the database to open a specific sheet, inspect its columns, and hand back the rows that match your criteria.


Anatomy of a SQL Query

A SQL statement consists of reserved keywords combined with the names of your tables and columns.

Consider a practical scenario: you have a table named customers, and you want to view the first names and email addresses of everyone in that table.

Here is what that query looks like:

SELECT first_name, email
FROM customers;
Enter fullscreen mode Exit fullscreen mode

Notice a few conventions right away:

  1. Keywords are capitalized: SELECT and FROM are commands built into the language. Capitalizing them is not strictly required by most database engines, but doing so makes your code substantially easier to read.
  2. Column names are separated by commas: You list the exact fields you want back, separated by a comma.
  3. The statement ends with a semicolon: In SQL, the semicolon acts like a period at the end of a sentence. It tells the engine that your instruction is complete.

If you wanted to inspect every single column in the table without typing out every field name, you can use the asterisk wildcard:

SELECT *
FROM customers;
Enter fullscreen mode Exit fullscreen mode

A quick word of caution from experience: using SELECT * is convenient when exploring a new dataset on your local laptop, but it becomes a performance bottleneck in production systems with millions of rows and dozens of columns. Get into the habit of asking only for what you actually need.


Filtering Data with the WHERE Clause

Pulling every record from a table is rarely useful in the real world. Usually, you want answers to specific questions: Which customers live in Nairobi? Which orders were placed today? Which accounts are inactive?

To filter rows, add a WHERE clause:

SELECT first_name, email, city
FROM customers
WHERE city = 'Nairobi';
Enter fullscreen mode Exit fullscreen mode

When filtering text values (strings), wrap the text in single quotes. Numbers, on the other hand, do not take quotes:

SELECT product_name, price
FROM products
WHERE price > 50;
Enter fullscreen mode Exit fullscreen mode

Combining Conditions

Real-world questions often have multiple layers. You can chain conditions together using AND, OR, and NOT.

  • AND requires both conditions to be true:
  SELECT product_name, price, stock_quantity
  FROM products
  WHERE price > 50 AND stock_quantity > 0;
Enter fullscreen mode Exit fullscreen mode
  • OR requires at least one condition to be true:
  SELECT first_name, city
  FROM customers
  WHERE city = 'Nairobi' OR city = 'Kisumu';
Enter fullscreen mode Exit fullscreen mode
  • IN handles lists cleanly: Instead of stringing together six different OR checks, you can test membership against a list:
  SELECT first_name, city
  FROM customers
  WHERE city IN ('Nairobi', 'Kisumu', 'Mombasa');
Enter fullscreen mode Exit fullscreen mode

Sorting and Limiting Results

Databases do not store records in any guaranteed default order. If you run a query twice, the rows might return in a different sequence unless you explicitly tell the database how to arrange them.

Ordering Rows

The ORDER BY clause lets you sort by one or more columns, either ascending (ASC, the default) or descending (DESC):

SELECT product_name, price
FROM products
ORDER BY price DESC;
Enter fullscreen mode Exit fullscreen mode

This returns your product inventory starting with the most expensive item.

Restricting the Row Count

When you only care about top performers or want a quick sample of the data, pair ORDER BY with LIMIT:

SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5;
Enter fullscreen mode Exit fullscreen mode

Now you have a clean list of your five most expensive products.


The Hidden Rule: Written Order vs. Execution Order

Here is something that catches almost every newcomer off guard: the order in which you write a SQL query is not the order in which the database executes it.

When you write a query, standard syntax requires this sequence:

  1. SELECT
  2. FROM
  3. WHERE
  4. ORDER BY
  5. LIMIT

Under the hood, however, the database processes your instructions in a completely different order:

  1. FROM: First, it locates the target table on disk.
  2. WHERE: Next, it evaluates your filters and discards rows that do not match.
  3. SELECT: Then, it extracts the requested columns from the remaining rows.
  4. ORDER BY: It sorts those extracted values.
  5. LIMIT: Finally, it trims the result set to the requested count.

Understanding this sequence prevents endless debugging headaches down the road, particularly when you begin using aliases and aggregate functions.


Common Mistakes Beginners Make

  • Mixing up single quotes and backticks: Use single quotes ('text') for literal string values. Backticks or double quotes are reserved in some dialects for table and column names that contain spaces or special characters.
  • Forgetting that NULL means unknown: Missing data in SQL is represented as NULL. Because NULL signifies the absence of a value, it cannot be equal or unequal to anything. Writing WHERE status = NULL will never return any rows. You must write WHERE status IS NULL or WHERE status IS NOT NULL.
  • Trailing commas in SELECT lists: Placing a comma after the final column in your SELECT clause (for example, SELECT id, name, FROM users;) is an immediate syntax error in nearly every SQL engine.
  • Treating case sensitivity carelessly: While SQL keywords (SELECT, FROM) are case-insensitive, text comparisons within single quotes often are case-sensitive depending on your database configuration. 'Nairobi' and 'nairobi' may not match.

Key Takeaways

  • SQL is a declarative language: you specify the data you want, not the step-by-step algorithms required to fetch it.
  • A standard read query follows a strict written template: SELECT columns FROM a table WHERE conditions apply.
  • The query execution engine reads FROM and WHERE before it ever looks at SELECT.
  • Always use IS NULL and IS NOT NULL when checking for empty fields rather than standard equality operators.
  • Request only the columns and rows you actually need to keep queries fast and clean.

Next Steps

Reading about syntax only gets you so far. The fastest way to build intuition for SQL is to sit down in front of a real dataset and start breaking things.

You do not need to install complicated database servers on your computer to begin. Web tools like SQLite Online or DB-Fiddle give you a sandboxed database directly in your browser. You can also check SQL Bolt for free interactive lessons. Load in a simple sample dataset, start asking basic questions using SELECT and WHERE, and see how the database responds. Once the core grammar clicks, you will have a durable, transferable skill that remains relevant across every corner of the software industry.

Top comments (0)