SQL Commands
Introduction
SQL commands are organized into distinct categories based on their function. Understanding these categories helps you know which commands to use for different tasks and how they interact with the database.
In this tutorial, you will learn:
- The five categories of SQL commands
- What each command category does
- When to use each type of command
- Examples of commands in each category
- Which commands are most important for data analysis
Overview of SQL Command Categories
SQL commands are grouped into five main categories, often called "sublanguages" of SQL.
The Five Categories
| Category | Full Name | Purpose |
|---|---|---|
| DQL | Data Query Language | Retrieve data from the database |
| DML | Data Manipulation Language | Modify data in the database |
| DDL | Data Definition Language | Create and modify database structure |
| DCL | Data Control Language | Manage access and permissions |
| TCL | Transaction Control Language | Manage transaction behavior |
Visual Overview
Which Categories Are Most Important?
For data analysts and query writers, the priority order is:
- DQL (SELECT) - 80%+ of your work
- DML - Occasionally modifying data
- DDL - Creating tables, usually less frequent
- TCL/DCL - Typically handled by database administrators

DQL - Data Query Language
DQL is used to retrieve data from the database. It consists of just one command: SELECT.
The SELECT Statement
SELECT is the most commonly used SQL command. It retrieves data from one or more tables.
Basic Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column
HAVING group_condition
ORDER BY column
LIMIT number;
SELECT Capabilities
| Clause | Purpose | Example |
|---|---|---|
SELECT | Choose columns | SELECT name, email |
FROM | Specify table | FROM customers |
WHERE | Filter rows | WHERE state = 'SP' |
GROUP BY | Aggregate by groups | GROUP BY city |
HAVING | Filter groups | HAVING COUNT(*) > 10 |
ORDER BY | Sort results | ORDER BY name ASC |
LIMIT | Restrict rows | LIMIT 100 |
JOIN | Combine tables | JOIN orders ON ... |
Examples
Simple SELECT:
SELECT customer_city, customer_state
FROM olist_customers_dataset
LIMIT 5;
SELECT with Aggregation:
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC;
Why SELECT is Special
- Read-only: Does not modify any data
- Safe to run: Cannot accidentally delete or change data
- Most used: Analysts spend most time with SELECT
- Our focus: This course emphasizes mastering SELECT
DML - Data Manipulation Language
DML commands modify data within existing tables. They change the content but not the structure.
DML Commands
| Command | Purpose | What It Does |
|---|---|---|
INSERT | Add data | Creates new rows |
UPDATE | Modify data | Changes existing rows |
DELETE | Remove data | Deletes specific rows |
INSERT - Adding New Records
-- Insert a single row
INSERT INTO customers (customer_id, name, email)
VALUES ('C001', 'Alice Johnson', 'alice@mail.com');
-- Insert multiple rows
INSERT INTO customers (customer_id, name, email)
VALUES
('C002', 'Bob Smith', 'bob@mail.com'),
('C003', 'Carol Davis', 'carol@mail.com');
-- Insert from another table
INSERT INTO archive_customers
SELECT * FROM customers WHERE status = 'inactive';
UPDATE - Modifying Existing Records
-- Update specific rows
UPDATE customers
SET email = 'newemail@mail.com'
WHERE customer_id = 'C001';
-- Update with calculation
UPDATE products
SET price = price * 1.10 -- 10% increase
WHERE category = 'electronics';
-- IMPORTANT: Always use WHERE!
-- Without WHERE, ALL rows are updated
UPDATE products SET price = 0; -- Dangerous!
DELETE - Removing Records
-- Delete specific rows
DELETE FROM orders
WHERE order_status = 'canceled';
-- Delete based on date
DELETE FROM logs
WHERE created_at < '2023-01-01';
-- IMPORTANT: Always use WHERE!
-- Without WHERE, ALL rows are deleted
DELETE FROM orders; -- Deletes everything!
DML Safety Tips
⚠️ Critical Warning:
-- ALWAYS preview before modifying:
SELECT * FROM orders WHERE order_status = 'canceled';
-- Then run:
DELETE FROM orders WHERE order_status = 'canceled';
-- Use transactions for safety:
BEGIN TRANSACTION;
DELETE FROM orders WHERE order_status = 'canceled';
-- Check the result, then:
COMMIT; -- or ROLLBACK; if wrong
DDL - Data Definition Language
DDL commands define and modify database structure. They work on tables, indexes, and other database objects.
DDL Commands
| Command | Purpose | What It Does |
|---|---|---|
CREATE | Build new objects | Tables, indexes, views |
ALTER | Modify objects | Add columns, change types |
DROP | Remove objects | Delete tables, views |
TRUNCATE | Empty table | Delete all rows quickly |
CREATE - Building Database Objects
-- Create a new table
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- Create a table with foreign key
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_date DATETIME,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
-- Create an index for faster queries
CREATE INDEX idx_customer_email ON customers(email);
-- Create a view (saved query)
CREATE VIEW active_customers AS
SELECT * FROM customers WHERE status = 'active';
ALTER - Modifying Existing Objects
-- Add a new column
ALTER TABLE customers
ADD COLUMN phone TEXT;
-- Rename a column (syntax varies by DBMS)
ALTER TABLE customers
RENAME COLUMN phone TO phone_number;
-- Drop a column
ALTER TABLE customers
DROP COLUMN phone_number;
DROP - Removing Objects
-- Drop a table (deletes everything!)
DROP TABLE old_customers;
-- Drop only if exists (prevents errors)
DROP TABLE IF EXISTS temp_data;
-- Drop a view
DROP VIEW customer_summary;
-- Drop an index
DROP INDEX idx_customer_email;
TRUNCATE vs DELETE
| Aspect | TRUNCATE | DELETE |
|---|---|---|
| Speed | Very fast | Slower |
| WHERE clause | Not allowed | Allowed |
| Transaction | Cannot rollback (usually) | Can rollback |
| Triggers | Does not fire | Fires |
| Use case | Empty entire table | Remove specific rows |
DCL - Data Control Language
DCL commands manage access and security. They control who can do what in the database.
DCL Commands
| Command | Purpose | What It Does |
|---|---|---|
GRANT | Give permissions | Allow users to perform actions |
REVOKE | Remove permissions | Take away access rights |
GRANT - Giving Permissions
-- Grant SELECT permission on a table
GRANT SELECT ON customers TO analyst_user;
-- Grant multiple permissions
GRANT SELECT, INSERT, UPDATE ON orders TO sales_team;
-- Grant all permissions
GRANT ALL PRIVILEGES ON products TO admin_user;
-- Grant with ability to pass on
GRANT SELECT ON reports TO manager WITH GRANT OPTION;
REVOKE - Removing Permissions
-- Revoke specific permission
REVOKE INSERT ON customers FROM intern_user;
-- Revoke all permissions
REVOKE ALL PRIVILEGES ON sensitive_data FROM public;
Common Permission Types
| Permission | Allows |
|---|---|
SELECT | Read data |
INSERT | Add new records |
UPDATE | Modify records |
DELETE | Remove records |
CREATE | Create new tables |
DROP | Delete tables |
ALTER | Modify table structure |
ALL PRIVILEGES | Everything |
Typical Permission Patterns
-- Read-only analyst
GRANT SELECT ON ALL TABLES TO analyst;
-- Application user
GRANT SELECT, INSERT, UPDATE, DELETE ON app_tables TO app_user;
-- Report viewer
GRANT SELECT ON report_views TO reporting_team;
Note: DCL is typically managed by Database Administrators (DBAs). As a data analyst, you'll usually just use the permissions granted to you.
TCL - Transaction Control Language
TCL commands manage transactions—groups of SQL statements that should succeed or fail together.
TCL Commands
| Command | Purpose | What It Does |
|---|---|---|
BEGIN / START TRANSACTION | Start transaction | Opens a transaction block |
COMMIT | Save changes | Makes changes permanent |
ROLLBACK | Undo changes | Reverts to last commit |
SAVEPOINT | Create checkpoint | Mark a point to rollback to |
Why Transactions Matter
Consider a bank transfer:
-- Transfer $100 from Account A to Account B
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
What if the second statement fails?
- Account A lost $100
- Account B never received it
- Money is lost!
Using Transactions
-- Start a transaction
BEGIN TRANSACTION;
-- Perform operations
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
-- If everything worked:
COMMIT;
-- If something went wrong:
-- ROLLBACK; -- Undo everything
SAVEPOINT - Partial Rollback
BEGIN TRANSACTION;
INSERT INTO orders VALUES (1, 'Order 1');
SAVEPOINT after_order1;
INSERT INTO orders VALUES (2, 'Order 2');
-- Oops, this was wrong!
ROLLBACK TO SAVEPOINT after_order1;
-- Order 1 is kept, Order 2 is undone
COMMIT;
Transaction Example Flow
┌──────────────────────────────────────────────────┐
│ │
│ BEGIN TRANSACTION │
│ │ │
│ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Statement│───►│Statement│───►│Statement│ │
│ │ 1 │ │ 2 │ │ 3 │ │
│ └─────────┘ └─────────┘ └─────────┘ │
│ │ │ │
│ │ All OK? │ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ │
│ │ COMMIT │ Any Error? │ROLLBACK │ │
│ │(Saved) │◄─────────────────►│(Undone) │ │
│ └─────────┘ └─────────┘ │
│ │
└──────────────────────────────────────────────────┘
Command Categories Summary
Here's a complete reference of SQL command categories:
Quick Reference Table
| Category | Commands | Effect on Data | Effect on Structure |
|---|---|---|---|
| DQL | SELECT | Read only | None |
| DML | INSERT, UPDATE, DELETE | Modifies data | None |
| DDL | CREATE, ALTER, DROP, TRUNCATE | May delete data | Modifies structure |
| DCL | GRANT, REVOKE | None | Changes permissions |
| TCL | COMMIT, ROLLBACK, SAVEPOINT | Controls when saved | None |
Command Impact Levels
| Command | Risk Level | Reversible? |
|---|---|---|
| SELECT | 🟢 Safe | N/A (no change) |
| INSERT | 🟡 Low | Yes (with DELETE) |
| UPDATE | 🟠 Medium | Difficult |
| DELETE | 🔴 High | No (without backup) |
| DROP | 🔴 Very High | No |
| TRUNCATE | 🔴 Very High | No |
What You'll Use Most
As a Data Analyst (80%+):
SELECT ... FROM ... WHERE ... GROUP BY ... ORDER BY ...
Occasionally:
INSERT INTO ... VALUES ...
UPDATE ... SET ... WHERE ...
CREATE TABLE ... AS SELECT ...
Rarely (handled by DBAs):
GRANT ... TO ...
ALTER TABLE ...
DROP TABLE ...
Practice
Let's practice with SELECT commands, which are the focus of this course. Our practice database only allows SELECT queries (read-only for safety).
Exercise 1: Basic SELECT (DQL)
The most common SQL command—retrieve data from a table.
-- DQL Example: SELECT data from a table
-- This is read-only and safe to run
SELECT
customer_id,
customer_city,
customer_state
FROM olist_customers_dataset
LIMIT 10;Exercise 2: SELECT with Filtering
Use WHERE to filter which rows are returned.
-- DQL Example: SELECT with WHERE filter
-- Returns only customers from São Paulo state
SELECT
customer_id,
customer_city,
customer_state
FROM olist_customers_dataset
WHERE customer_state = 'SP'
LIMIT 10;Exercise 3: SELECT with Aggregation
Use GROUP BY and aggregate functions to summarize data.
-- DQL Example: SELECT with GROUP BY
-- Count customers per state
SELECT
customer_state,
COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC
LIMIT 10;Exercise 4: SELECT with JOIN
Combine data from multiple tables using JOIN.
-- DQL Example: SELECT with JOIN
-- Combine customers and orders
SELECT
c.customer_state,
COUNT(o.order_id) AS order_count
FROM olist_customers_dataset c
JOIN olist_orders_dataset o
ON c.customer_id = o.customer_id
GROUP BY c.customer_state
ORDER BY order_count DESC
LIMIT 10;Summary
You now understand the complete landscape of SQL commands!
Key Takeaways
✅ DQL (SELECT) - Query data (read-only, safe, most used)
✅ DML (INSERT, UPDATE, DELETE) - Modify data within tables
✅ DDL (CREATE, ALTER, DROP) - Define and modify table structure
✅ DCL (GRANT, REVOKE) - Control user permissions
✅ TCL (COMMIT, ROLLBACK) - Manage transactions
What to Focus On
| If You Are | Focus On |
|---|---|
| Data Analyst | DQL (SELECT) primarily |
| Application Developer | DQL + DML |
| Data Engineer | DQL + DML + DDL |
| Database Administrator | All categories |
Safety Reminder
🟢 SELECT - Always safe
🟡 INSERT - Usually safe (adds data)
🔴 UPDATE/DELETE - Use WHERE clause!
🔴 DROP/TRUNCATE - Be very careful!
Next Up
Continue to Why Learn SQL? to understand the career benefits and practical applications of SQL skills!