1. Home
  2. Explore
  3. Computer Science
  4. SQL Basics for Beginners

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL Basics for Beginners

SQL Fundamentals: From Data to Queries

Data, databases, and why they matter

Data consists of facts or observations about something. A customer’s age, income, city, and purchases are all examples of data. Data becomes useful when it is organized and interpreted: a business might use customer purchase records to decide which products to offer or how to improve a service.

The same idea applies to decisions in everyday life. A decision is usually better informed when the relevant facts are available. Businesses face this challenge at a much larger scale: they may need to keep track of thousands or millions of customers, products, and transactions. They need a dependable way to store those facts and work with them.

A database is an organized collection of data. It provides a place to store information so that it can be managed, updated, searched, analyzed, and protected. A database can help turn a large collection of individual facts into patterns and insights that support decisions.

A database often contains multiple tables, each organized around a particular subject. For example, one table might describe customers, while another describes purchases or products. Separating information into related tables helps keep it organized and makes it possible to connect details when needed.

What SQL does

SQL, commonly pronounced either “S-Q-L” or “sequel,” is a language used to communicate with relational databases. A SQL statement tells a database what information to retrieve or what action to perform. The database processes the statement and returns a result or reports that the action succeeded.

For example:

SELECT name
FROM customers;

This statement asks for the name values in the customers table. The database checks the request, finds the matching data, and returns it.

SQL is useful because it can retrieve, insert, change, and delete data. It is widely used wherever people need to work with structured data, including business intelligence and database development.

SQL is the language used to request and manage data in a relational database; the database processes each statement and returns a result.

Think About It: How might a business use customer ages, cities, or purchase histories to make a better decision?

Tables, rows, columns, and constraints

A relational database organizes data in tables. A table has a consistent set of columns, and each row stores one record.

Imagine a customer table:

idnameageincomecity
1Lucas2290000Delhi
2Robert3580000Mumbai

A row, also called a record, contains the information for one entry—in this case, one customer. A column describes one type of information, such as name, age, or city. A particular value, such as Delhi, is stored where a row and a column meet. That location is sometimes called a field.

Columns have data types, which specify what kinds of values they can store. For instance, an integer type is suitable for whole-number values, while a character type is suitable for text. A column’s type helps the database interpret and check the values stored in it.

NULL and NOT NULL

A NULL value represents information that is missing or unknown. It is not the same as zero, an empty string, or a punctuation mark. For example, a customer’s income might be NULL if it has not been provided.

A NOT NULL constraint prevents a column from being left without a value. If every customer record must include a name, the name column can be declared NOT NULL. A column that is allowed to contain missing information can permit NULL values.

Constraints

A constraint is a rule that the database enforces on data. Constraints help maintain consistency and prevent invalid or contradictory records. Examples include requiring a value, preventing duplicate identifiers, or requiring a reference to match a record in another table.

The primary key is a column, or group of columns, that uniquely identifies each row in a table. A customer ID is often a better primary key than a name: two people can share a name, but each customer ID should identify only one customer. A primary key must be unique and cannot be NULL.

A foreign key is a column, or group of columns, in one table that refers to a key in another table. It allows the database to represent a relationship between records and helps prevent references to records that do not exist.

Think About It: Why is a unique customer ID generally a more reliable identifier than a customer’s name?

Relationships between tables

Relational databases are especially useful because separate tables can be connected. Suppose a customers table stores customer details and a purchases table stores purchase details. Keeping these subjects in separate tables avoids repeatedly copying all of a customer’s information into every purchase record.

A purchase can refer to the customer who made it by storing that customer’s ID as a foreign key. The customer’s ID is the primary key in the customer table and a foreign key in the purchase table.

A parent–child relationship is one way to describe this structure. The table containing the referenced primary key is the parent table; the table that stores the foreign key is the child table. In this example, customers is the parent and purchases is the child.

Two related ideas describe the shape of a relationship:

  • Cardinality describes how many records can be related. Common patterns include one-to-one, one-to-many, and many-to-many. One customer may have many purchases, for example.
  • Optionality, sometimes discussed using ordinality in diagramming, describes whether a relationship is required or can be absent. A customer might have no purchases yet, so the customer-to-purchase relationship can be optional. A purchase, however, may be required to refer to a customer.

In relationship diagrams, optional participation is often shown with a zero, while required participation is often shown with a line. The exact symbols can vary by diagram style. The central question is whether a related record may be absent and how many related records are allowed.

A many-to-many relationship usually needs a linking table. For example, if a student can take many courses and each course can have many students, a separate enrollment table can link student IDs with course IDs.

Think About It: If one customer can make several purchases, which table should contain the customer ID that connects a purchase to its customer?

Categories of SQL commands

SQL commands are often grouped by the kind of work they perform. These categories are useful for learning, although some database systems or learning materials classify particular commands differently.

Data definition language

Data definition language (DDL) commands define or change database structures, such as databases and tables.

  • CREATE creates a database or table.
  • ALTER changes a structure, such as adding a column.
  • DROP removes a database object, such as a table.
  • TRUNCATE removes all rows from a table while keeping the table structure.

DROP and TRUNCATE are not interchangeable. Dropping a table removes the table itself, including its definition. Truncating removes its rows but leaves the table available for future data. Their exact behavior, including transaction and identity-reset behavior, can vary between database systems.

A COMMENT command may be available for adding explanatory descriptions to database objects, but its syntax and support vary by system.

Data manipulation language

Data manipulation language (DML) commands work with the data stored in tables.

  • INSERT adds rows.
  • UPDATE changes values in existing rows.
  • DELETE removes rows.
  • SELECT retrieves rows and values.

SELECT is sometimes placed in its own category, called data query language, rather than grouped under DML.

The USE command selects a database to work with in systems such as MySQL. It is useful in practice, but it is not usually treated as a data-manipulation operation.

Data control language

Data control language (DCL) manages access privileges.

  • GRANT gives a user or role permission to perform specified actions.
  • REVOKE withdraws permissions that were previously granted.

These commands help control who can read or change information.

Transaction control language

Transaction control language (TCL) commands manage transactions—a set of database operations treated as a unit.

  • COMMIT saves the transaction’s changes.
  • ROLLBACK undoes uncommitted changes, subject to the database system’s rules.
  • SAVEPOINT marks a position within a transaction so that a rollback can return to that point.
  • SET TRANSACTION can specify characteristics for a transaction.

A transaction is useful when several related changes must succeed together. If an error occurs before the changes are committed, a rollback can help prevent an incomplete set of changes from being left in place.

CRUD

The four basic data operations are often summarized as CRUD:

  • Create: add new data.
  • Read: retrieve data.
  • Update: change existing data.
  • Delete: remove data.

In a typical SQL workflow, INSERT supports creating records, SELECT supports reading them, UPDATE changes them, and DELETE removes them.

Think About It: Why might a transaction be safer than committing each step of a multi-step change immediately?

Writing basic SQL queries

SQL keywords are commonly written in uppercase to make statements easier to read, but they are generally not case-sensitive in MySQL. Table and column names follow the rules of the particular database system. A semicolon commonly marks the end of a SQL statement.

Creating a database and selecting it

In MySQL, a database can be created and selected like this:

CREATE DATABASE customer_db;
USE customer_db;

The first statement creates the database. The second tells MySQL that later commands should work in that database.

Creating tables

A table definition specifies its columns, types, and rules. Here is a simple customer table:

CREATE TABLE customers (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(30) NOT NULL,
    age INT NOT NULL,
    income INT,
    city VARCHAR(30),
    PRIMARY KEY (id)
);

INT specifies integer values. VARCHAR(30) specifies text with a maximum length of 30 characters. AUTO_INCREMENT asks MySQL to generate a new identifier as rows are added. The primary key makes each customer’s id unique. The income and city columns permit NULL values in this example because they are not declared NOT NULL.

A related purchases table can use a foreign key to refer to the customer who made each purchase:

CREATE TABLE purchases (
    id INT NOT NULL AUTO_INCREMENT,
    customer_id INT NOT NULL,
    product_name VARCHAR(30) NOT NULL,
    price INT NOT NULL,
    year_made INT,
    PRIMARY KEY (id),
    FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Here, each purchase has its own primary key. Its customer_id refers to the id of a customer. The two IDs serve different purposes: one identifies the purchase, and the other links it to its customer.

Inserting rows

INSERT INTO adds data to a table. The column list shows which columns receive values:

INSERT INTO customers (name, age, income, city)
VALUES ('Lucas', 22, 90000, 'Delhi');

Text values are written in quotes; integer values are not. Because id is generated automatically, it is left out of the column list.

A purchase can then be added for that customer:

INSERT INTO purchases (customer_id, product_name, price, year_made)
VALUES (1, 'TV', 50000, 2023);

If customer ID 1 does not exist, the foreign-key constraint can prevent this purchase from being inserted. That check protects the relationship between the tables.

Retrieving data with SELECT

SELECT retrieves chosen columns. The asterisk, written as *, means all columns:

SELECT *
FROM customers;

To retrieve only specific columns, they are listed by name:

SELECT name, age
FROM customers;

Retrieving only the needed columns can make results easier to read and can avoid fetching irrelevant information.

Filtering rows with WHERE

The WHERE clause selects only rows that satisfy a condition:

SELECT *
FROM customers
WHERE city = 'Mumbai';

This returns customers whose city is Mumbai. Text comparisons use quotes. Conditions can be combined with AND when both must be true:

SELECT *
FROM customers
WHERE city = 'Bengaluru'
  AND income > 50000;

This finds customers who live in Bengaluru and have an income greater than 50,000. More generally, filtering lets a query focus on the records relevant to a particular question.

A missing value must be tested with IS NULL or IS NOT NULL, rather than using ordinary equality:

SELECT *
FROM customers
WHERE income IS NULL;

That query finds customers whose income is missing.

Sorting results with ORDER BY

ORDER BY sorts the result by one or more columns:

SELECT *
FROM customers
ORDER BY income;

Ascending order is the default in many systems. To put higher incomes first, the query can request descending order:

SELECT *
FROM customers
ORDER BY income DESC;

Sorting changes the order in which results are displayed; it does not change the stored rows.

Summarizing values with aggregate functions

An aggregate function calculates a summary from a set of rows. Common examples include:

  • SUM adds values.
  • AVG calculates an average.
  • MAX returns the largest value.
  • MIN returns the smallest value.
  • COUNT counts rows or non-NULL values, depending on what is counted.

For example, the total income of all customers can be calculated with:

SELECT SUM(income)
FROM customers;

A condition can limit the rows included in an aggregate:

SELECT SUM(income)
FROM customers
WHERE city = 'Mumbai';

This returns the sum for customers in Mumbai. To find an average or a maximum, the function can be changed:

SELECT AVG(income)
FROM customers;

SELECT MAX(income)
FROM customers;

SELECT MIN(income)
FROM customers;

COUNT(*) counts rows, including rows with NULL values in particular columns. By contrast, COUNT(column_name) counts non-NULL values in that column. This difference matters when a column is allowed to be missing.

Removing repeated results with DISTINCT

DISTINCT removes duplicate values from the query result:

SELECT DISTINCT name
FROM customers;

If multiple rows have the same name, that name appears only once in the result. DISTINCT affects the returned results; it does not delete or modify any stored records.

Updating data

UPDATE changes values in existing rows. The WHERE clause is crucial because it identifies which rows should change:

UPDATE customers
SET city = 'Mumbai',
    income = 80000
WHERE id = 2;

This changes the city and income for the customer with ID 2. Without a WHERE clause, an update can affect every row in the table. A reliable workflow is to check the intended rows with a SELECT query before running an update.

ALTER TABLE, by contrast, changes the table’s structure rather than the values in its rows. For example, an ALTER TABLE statement can add a new column. This distinction is important: UPDATE changes data; ALTER changes the design of the table.

Deleting data and removing tables

DELETE removes rows from a table. With a condition, it can target particular records:

DELETE FROM customers
WHERE id = 2;

Without a WHERE clause, DELETE may remove every row. The table itself remains.

TRUNCATE TABLE removes all rows while keeping the table structure:

TRUNCATE TABLE customers;

DROP TABLE removes the table and its definition:

DROP TABLE customers;

Because these operations can remove substantial data, their scope should be checked carefully before execution.

Think About It: What could happen if an UPDATE or DELETE statement is run without the intended WHERE condition?

Combining related tables with JOIN

A JOIN combines related rows from different tables so that a query can retrieve information stored in both places. For example, customer details are in customers, while product and purchase details are in purchases.

The join condition matches the foreign key in the child table with the primary key in the parent table:

SELECT
    customers.name,
    customers.age,
    customers.income,
    purchases.product_name,
    purchases.price
FROM customers
JOIN purchases
    ON customers.id = purchases.customer_id;

The condition customers.id = purchases.customer_id is what connects each purchase to its customer. The result can include a customer’s name and income alongside the product and price associated with that purchase.

A join is not simply a way to put two tables side by side. The relationship condition determines which rows belong together. If the wrong columns are matched, the query can produce misleading combinations. If a customer has several purchases, that customer’s details may appear on several result rows—one for each matching purchase.

Different join types determine what happens when a matching row is absent. An ordinary JOIN—also called an inner join—returns only rows with matches in both tables. Other join types can preserve unmatched rows from one side; those are useful when the absence of a related record also matters.

Comprehensive review

SQL makes it possible to work with organized data by sending statements to a relational database. Tables store records as rows and attributes as columns, while data types and constraints help keep values valid. Primary keys uniquely identify records; foreign keys connect records across tables.

The basic query workflow includes creating a structure, inserting rows, retrieving selected information, filtering with WHERE, sorting with ORDER BY, summarizing with aggregate functions, and joining related tables. UPDATE changes stored values, while DELETE, TRUNCATE, and DROP remove data or structures at different levels. DDL, DML, DCL, and TCL group commands by their purpose, and CRUD summarizes the fundamental operations performed on stored data.

The central idea is that SQL expresses a request or change, while the database applies it according to the table definitions, relationships, and constraints. Together, those features allow large collections of facts to remain organized, connected, and useful for analysis and decision-making.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent