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: Study Notes

Data, databases, and decision-making

Data consists of facts or recorded attributes about people, objects, events, or activities. Examples include a customer’s age, income, location, and purchasing history. Data can be collected in everyday settings as well as in large industries.

Data becomes useful when it is organized and interpreted. Analyzing it can reveal patterns and provide insights that support better decisions. For example, a business might use customer data to understand which products different groups prefer, improve its services, or increase efficiency and profits.

A database is an organized storage system for data. It allows data to be stored, managed, updated, searched, and analyzed. Databases are especially useful when an organization needs to work with large amounts of information.

Databases help organizations:

  • Keep data organized and accessible.

  • Add, change, and remove records.

  • Search and analyze information.

  • Protect data, which may be an important business asset.

  • Use evidence and patterns in decision-making.


What SQL is and how it works

SQL stands for Structured Query Language. It is commonly pronounced either “S-Q-L” or “sequel.” SQL is used to communicate with relational databases: a user writes a statement, the database processes it, and the database returns a result or performs the requested action.

SQL can be used to:

  • Retrieve data.

  • Add, change, and delete data.

  • Create and modify database structures.

  • Control access to database objects.

  • Manage transactions.

For example:

SELECT name
FROM customers;

This statement asks the database to return the name value for every row in the customers table. The database processes the request and returns a result set containing those names.

A typical SQL interaction follows this pattern:

  1. A user writes a query describing the data or action needed.

  2. The query is sent to a database management system.

  3. The system interprets and executes the query.

  4. The system returns results or reports that the operation was completed.

A relational database management system (RDBMS) stores data in related tables and processes SQL statements. SQL is widely used in data analysis, business intelligence, and software systems because it provides a standard way to work with relational data.


Relational database structure

Tables, rows, columns, and fields

A table stores a collection of related records. For example, a customer table could store information about customers, while a product table could store product details.

  • Row: One record in a table. A customer row might contain one customer’s ID, name, age, and city.

  • Column: An attribute shared by the records in a table, such as name, age, or city.

  • Field: The term can refer to a column or, in some contexts, to a particular value within a record.

  • Data type: Specifies what kind of values a column can store, such as integers or text.

Rows in a table follow the table’s defined structure: each row has values associated with the same columns. A table’s columns and data types make its structure consistent.

NULL values and NOT NULL

NULL represents a missing, unknown, or unavailable value. It is not the same as zero, an empty string, or a placeholder such as a period.

A column that permits NULL can be left without a known value for a row. A column declared NOT NULL must have a value for every row. For example, a customer ID should generally be required because each record needs a way to be identified.

Constraints

Constraints are rules applied to columns or tables to restrict the data that can be stored. They help preserve accuracy and consistency.

Common examples include:

  • NOT NULL: Requires a value.

  • PRIMARY KEY: Requires a unique identifier for each row.

  • FOREIGN KEY: Requires a reference to a matching row in another table.

  • Other rules, such as requiring values to be unique or to meet a specified condition.


Primary keys, foreign keys, and relationships

Primary keys

A primary key uniquely identifies each row in a table. A customer table might use an ID number rather than a person’s name, since different customers can share the same name.

A primary key:

  • Must uniquely identify each record.

  • Cannot be duplicated.

  • Cannot be NULL.

  • Provides a dependable way to refer to a particular row.

An automatically increasing integer ID is a common choice for a primary key. In MySQL, an integer column can be declared AUTO_INCREMENT so the database generates a new ID when a row is added.

Foreign keys and parent–child relationships

A foreign key is a column in one table that refers to a key in another table. It connects records across tables and helps ensure that references are valid.

In a common parent–child arrangement:

  • The parent table contains the referenced primary key.

  • The child table contains the foreign key that refers to the parent.

For example, a customer table could be the parent, and a product_model table could be the child. A customer_id column in product_model can refer to the customer who purchased or is associated with that product model. The referenced customer ID must exist in the parent table if the foreign-key rule is enforced.

Optionality and cardinality

Relationships have two important aspects: whether a relationship is required, and how many records can be associated.

Optionality indicates whether a relationship is required or may be absent. For instance, a customer might not yet have a recorded purchase. In a relationship diagram, optionality is often represented with a zero; a required relationship is often represented with a line indicating that at least one associated record is needed.

Cardinality describes how many records on one side of a relationship can be associated with records on the other side. Common forms include:

  • One-to-one: One record in one table is associated with at most one record in another.

  • One-to-many: One parent record can be associated with multiple child records. For example, one customer may have several purchases.

  • Many-to-many: Multiple records on each side can be associated with multiple records on the other. This relationship is commonly implemented using an additional linking table.


SQL command categories

Data Definition Language (DDL)

DDL defines or changes database structures, such as databases and tables.

  • CREATE: Creates a database, table, or other database object.

  • ALTER: Changes the structure of an existing object, such as adding a column or constraint.

  • DROP: Removes a database object, such as a table or database.

  • TRUNCATE: Removes all rows from a table while retaining the table structure. Exact behavior can vary by database system.

  • COMMENT: Adds explanatory metadata to a database object in systems that support the relevant syntax.

ALTER is used to change a table’s structure; changing the values stored in its rows is generally done with UPDATE.

Data Manipulation Language (DML) and data retrieval

DML is used to work with the data stored in tables.

  • INSERT: Adds rows.

  • UPDATE: Changes values in existing rows.

  • DELETE: Removes rows.

  • SELECT: Retrieves data. It is often placed in a separate category called Data Query Language (DQL), though some introductions group it with DML.

In MySQL, USE database_name selects the database to work with. It is a database-selection command rather than a standard data-manipulation operation.

Data Control Language (DCL)

DCL manages users’ access privileges.

  • GRANT: Gives a user specified privileges.

  • REVOKE: Removes privileges that were granted.

Transaction Control Language (TCL)

TCL manages transactions, which are groups of database operations treated as a unit.

  • COMMIT: Saves the changes made in the transaction.

  • ROLLBACK: Reverses changes that have not been committed.

  • SAVEPOINT: Creates a point within a transaction to which a partial rollback can be made.

  • SET TRANSACTION: Sets characteristics for a transaction, where supported.


CRUD operations

CRUD summarizes four common operations performed on data:

  • Create: Add records, commonly with INSERT.

  • Read: Retrieve records, commonly with SELECT.

  • Update: Change existing records, commonly with UPDATE.

  • Delete: Remove records, commonly with DELETE.

CRUD describes actions on data. It does not necessarily refer to creating or dropping entire tables or databases.


Creating and using a database in MySQL

SQL statements in MySQL are commonly ended with a semicolon. Keywords are often written in uppercase for readability, although MySQL generally accepts keywords in lowercase as well.

A typical database workflow begins by listing existing databases, creating a database, selecting it, and then creating tables:

SHOW DATABASES;

CREATE DATABASE customer_db;

USE customer_db;

SHOW TABLES;

SHOW DATABASES lists databases visible to the user. CREATE DATABASE creates a new database, and USE selects it as the current database. SHOW TABLES lists tables in the selected database.


Creating tables and defining keys

The following example creates a customer table with an automatically generated primary key:

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

This definition specifies:

  • id is an integer, cannot be NULL, and is generated automatically.

  • name is text of up to 30 characters and is required.

  • age is a required integer.

  • income is an integer that may be unknown or absent.

  • city is text of up to 30 characters and may be absent.

  • id uniquely identifies each row.

A related table can store product details and a customer reference:

CREATE TABLE product_model (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(30) NOT NULL,
    price INT NOT NULL,
    year INT,
    customer_id INT NOT NULL,
    PRIMARY KEY (id)
);

The customer_id column can then be constrained to reference the customer table:

ALTER TABLE product_model
ADD CONSTRAINT model_customer_fk
FOREIGN KEY (customer_id)
REFERENCES customer(id)
ON DELETE CASCADE;

This foreign key ensures that each non-NULL customer_id in product_model matches an ID in customer. ON DELETE CASCADE means that deleting a referenced customer also deletes the associated child rows. This behavior should be chosen deliberately because it can remove multiple records.

The two tables use separate primary keys: customer.id identifies a customer, and product_model.id identifies a product-model record. The relationship is made through product_model.customer_id, not by assuming the two primary keys have matching values.


Inserting and retrieving data

Adding a row

INSERT INTO adds a row. The listed columns should correspond, in order, to the values supplied:

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

The id is omitted because it is automatically generated. Text values are enclosed in quotes; numeric values are not. A required column must receive a value unless the database provides a default.

A product-model row can be inserted with a customer ID that already exists:

INSERT INTO product_model (name, price, year, customer_id)
VALUES ('Samsung Phone', 75000, 2019, 1);

If customer_id refers to no existing customer, the foreign-key constraint rejects the insertion.

Selecting columns and rows

SELECT retrieves data. The asterisk (*) means all columns:

SELECT *
FROM customer;

To return only selected columns, list them instead:

SELECT name, age
FROM customer;

Filtering with WHERE

WHERE restricts the result to rows that meet a condition:

SELECT *
FROM customer
WHERE city = 'Mumbai';

Multiple conditions can be combined with AND. Both conditions must be true for a row to be returned:

SELECT *
FROM customer
WHERE city = 'Bengaluru'
  AND product = 'Phone';

A filtering condition can use a column value, such as a city or product name, to find particular records among many rows.

Ordering results

ORDER BY sorts the returned rows:

SELECT *
FROM customer
ORDER BY income;

The default sort direction is generally ascending. DESC requests descending order, while ASC can be written explicitly:

SELECT *
FROM customer
ORDER BY income DESC;

Ordering by income in descending order places the largest income values first.


Aggregate functions and distinct values

Aggregate functions summarize values across rows. They can be used with WHERE to summarize only records that meet a condition.

SUM, AVG, MAX, and MIN

  • SUM(column) calculates the total of the selected numeric values.

  • AVG(column) calculates their average.

  • MAX(column) returns the highest value.

  • MIN(column) returns the lowest value.

For example, the total income associated with customers who bought a phone can be calculated with:

SELECT SUM(income)
FROM customer
WHERE product = 'Phone';

Removing the WHERE clause calculates the total across all applicable rows. The other aggregate functions use the same general pattern:

SELECT AVG(income) FROM customer;
SELECT MAX(income) FROM customer;
SELECT MIN(income) FROM customer;

COUNT

COUNT counts rows or non-NULL values, depending on the expression:

SELECT COUNT(name)
FROM customer;

This counts rows where name is not NULL. If a column may contain NULL, its count may be lower than the total number of rows. COUNT(*) counts rows regardless of whether individual column values are NULL.

DISTINCT

DISTINCT removes duplicate values from the result:

SELECT DISTINCT name
FROM customer;

This returns each customer name once. It does not remove rows from the underlying table; it only affects the query result. When multiple columns are selected with DISTINCT, the uniqueness check applies to the combination of those selected values.


Updating and deleting records

Updating records

UPDATE changes existing values. A WHERE clause identifies which rows should change:

UPDATE customer
SET city = 'Mumbai',
    income = 80000
WHERE name = 'Robert'
  AND product = 'TV';

Without a WHERE clause, the update applies to every row in the table. The condition should be specific enough to target the intended record or records.

Deleting records

DELETE removes rows from a table:

DELETE FROM customer
WHERE id = 3;

Without a WHERE clause, DELETE FROM customer removes every row from the table. The table itself remains. By contrast, DROP TABLE removes the table structure as well as its contents, while TRUNCATE TABLE removes all rows but retains the table structure.


Joining tables

A JOIN combines related rows from two or more tables so a query can retrieve information stored in different places. It is useful when customer details are in one table and product details are in another.

For example, customer name and income can be combined with product name and price using the foreign-key relationship:

SELECT
    customer.name,
    customer.income,
    product_model.name,
    product_model.price
FROM customer
JOIN product_model
    ON customer.id = product_model.customer_id;

The ON condition states how the tables are related: the customer’s primary key matches the product-model row’s foreign key. A join should use the relationship columns, not merely columns that happen to have the same values.

A table name followed by a period identifies which table a column belongs to, such as customer.name. This is especially useful when joined tables contain columns with identical names.


A practical way to approach SQL work

A beginner working with a relational database can follow this sequence:

  1. Identify the data to be stored and divide it into related tables.

  2. Choose columns and suitable data types for each table.

  3. Define a primary key for every table.

  4. Define foreign keys to express relationships between tables.

  5. Create the database and tables.

  6. Insert records and retrieve them with SELECT.

  7. Filter and sort results as needed.

  8. Use aggregate functions to summarize data.

  9. Update or delete records carefully, using precise WHERE conditions.

  10. Use transactions when a group of changes needs to be saved or reversed as a unit.

The central idea is that SQL statements operate on structured data: tables define the organization, keys define identity and relationships, and queries retrieve or modify the records.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent