Skip to main content

What is SQL Query

Introduction

Welcome to the world of SQL queries! A query is the fundamental way we communicate with databases to retrieve information.

In this tutorial, you will learn:

  • What a SQL query is and why we use it
  • The basic structure of a SQL query
  • How queries are processed by the database
  • The difference between queries and other SQL commands

What is a Query?

A SQL query is a request for data from a database. Think of it like asking a question - you send a query to the database, and it responds with the information you requested.

The Word "Query" Means "Question"

In everyday language, to query something means to ask about it. In SQL, a query is quite literally a question you ask the database:

Real-World QuestionSQL Query Equivalent
"How many customers do we have?"Count all rows in customers table
"Who are our customers in São Paulo?"Find customers where city = 'sao paulo'
"What are our top-selling products?"Find products with highest sales counts
"Which orders are still pending?"Find orders where status = 'pending'

Why Do We Need Queries?

Databases store enormous amounts of data - millions or even billions of rows. Without queries, you would have to:

  • Look through every single record manually
  • Remember where specific information is stored
  • Perform calculations by hand

Queries let you:

  • Find specific data among millions of records in seconds
  • Filter to see only what matters
  • Sort data in meaningful ways
  • Calculate totals, averages, and other statistics
  • Combine information from multiple tables

The Anatomy of a SQL Query

Every SQL query follows a basic structure. The simplest possible query looks like this:

SELECT column_name FROM table_name;

Breaking Down the Parts

PartPurposeRequired?
SELECTSpecifies which columns to retrieveYes
column_nameThe actual column(s) you wantYes
FROMIndicates which table to queryYes
table_nameThe name of the tableYes
;Marks the end of the statementRecommended

Example: A Simple Query

SELECT customer_city FROM olist_customers_dataset;

This query asks the database: "Give me the city column from the customers table."

Multiple Columns

You can request multiple columns by separating them with commas:

SELECT customer_city, customer_state FROM olist_customers_dataset;

All Columns

To get every column in the table, use the asterisk *:

SELECT * FROM olist_customers_dataset;

The asterisk is a wildcard meaning "everything."

Annotated SQL query showing each clause labeled with its purpose: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
Annotated SQL query showing each clause labeled with its purpose: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY

How Database Processes a Query

When you send a query to the database, it goes through several steps:

1. Parsing

The database reads your query and checks if it follows correct SQL syntax. If you have a typo or syntax error, it will reject the query.

2. Validation

The database verifies that:

  • The table you mentioned exists
  • The columns you requested exist in that table
  • You have permission to access this data

3. Optimization

The database creates an execution plan - the most efficient way to get your data. This is like planning the fastest route before a road trip.

4. Execution

The database follows its plan to retrieve the data, reading from storage and processing as needed.

5. Return Results

Finally, the database sends back the results - a table of data matching your query.

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  Your SQL   │ ──▶ │  Database   │ ──▶ │   Results   │
│   Query     │     │  Processing │     │   (Data)    │
└─────────────┘     └─────────────┘     └─────────────┘

Queries vs Other SQL Commands

Not all SQL commands are queries. Understanding the difference is important:

Queries (DQL - Data Query Language)

Purpose: Read data from the database
Keyword: SELECT
Effect: Does NOT modify the database

SELECT * FROM customers;  -- This is a query

Non-Query Commands

These commands modify the database:

TypeCommandsPurpose
DMLINSERT, UPDATE, DELETEModify data
DDLCREATE, ALTER, DROPModify structure
DCLGRANT, REVOKEModify permissions
INSERT INTO customers ...;  -- NOT a query (adds data)
UPDATE customers SET ...;   -- NOT a query (changes data)
DELETE FROM customers ...;  -- NOT a query (removes data)

Why This Matters

  • Queries are safe - they only read data, never change it
  • In practice, 80% of SQL work involves queries
  • Learning queries first is the foundation for everything else

Practice

Let's write some simple queries to get comfortable with the basic syntax. Try running these queries against our Brazilian E-Commerce database.

Exercise 1: Your First Query

Run this query to see customer IDs and cities from our customers table:

-- Your first SQL query!
-- This retrieves customer_id and customer_city from the customers table

SELECT customer_id, customer_city
FROM olist_customers_dataset
LIMIT 10;

Exercise 2: Select All Columns

Use the asterisk to see all columns in the orders table:

-- Select ALL columns from the orders table
-- The * (asterisk) means "everything"

SELECT *
FROM olist_orders_dataset
LIMIT 5;

Exercise 3: Try It Yourself

Now write your own query! Select the product_id and price columns from the olist_order_items_dataset table.

-- Write a query to select product_id and price
-- from the olist_order_items_dataset table

SELECT product_id, price
FROM olist_order_items_dataset
LIMIT 10;

Common Query Mistakes

When writing queries, beginners often make these mistakes:

1. Misspelling Table or Column Names

-- Wrong: 'costumer' instead of 'customer'
SELECT * FROM olist_costumers_dataset;

-- Correct
SELECT * FROM olist_customers_dataset;

2. Forgetting FROM Clause

-- Wrong: No FROM clause
SELECT customer_city;

-- Correct
SELECT customer_city FROM olist_customers_dataset;

3. Using Wrong Quote Marks

-- Wrong: Double quotes for string values (in most databases)
SELECT * FROM customers WHERE city = "New York";

-- Correct: Single quotes for strings
SELECT * FROM customers WHERE city = 'New York';

4. Missing Commas Between Columns

-- Wrong: No comma between columns
SELECT customer_city customer_state FROM olist_customers_dataset;

-- Correct
SELECT customer_city, customer_state FROM olist_customers_dataset;

Summary

Congratulations! You now understand what SQL queries are and how they work.

Key Takeaways

✅ A query is a request for data from a database using the SELECT statement

✅ The basic query structure is: SELECT columns FROM table;

✅ Use * to select all columns

✅ Queries only read data - they never modify the database

✅ The database parses, validates, optimizes, and executes your query

Query Cheat Sheet

-- Select specific columns
SELECT column1, column2 FROM table_name;

-- Select all columns
SELECT * FROM table_name;

-- Limit results (good practice for large tables)
SELECT * FROM table_name LIMIT 10;

What's Next?

Now that you understand what queries are, let's learn about the components that make up more powerful SQL queries - including filtering with WHERE, sorting with ORDER BY, and grouping with GROUP BY.