SQL Basics: Tables, Rows, Columns, and SELECT
Learn how relational databases organize data in tables and how to retrieve data with your first SQL queries.
What SQL and databases do
SQL (Structured Query Language) is used to work with relational databases. A database stores organized information, usually in related tables.
A table is similar to a spreadsheet, but it has a defined structure:
- A table holds one type of entity, such as
customers. - A row is one complete record, such as one customer.
- A column stores one kind of attribute, such as
city. - A primary key is a column whose value uniquely identifies each row, such as
customer_id.
Creating a table and inserting records
A table is created with CREATE TABLE. Each column needs a name and a data type.
Here, customer_id is the primary key. INTEGER stores whole numbers, while TEXT stores words and other character data.
Add rows with INSERT INTO:
Listing column names in the INSERT statement makes it clear which value belongs in each column.
Reading data with SELECT
Use SELECT to retrieve data from a table.
This returns only the customer_name column:
To retrieve several columns, separate them with commas:
To retrieve every column, use *:
SELECT * is useful for quick exploration, but naming the needed columns is usually clearer and avoids retrieving unnecessary data.
Worked example: finding a specific group of rows
Suppose the table contains customers in several cities:
To show only customers in Bristol, add a WHERE condition:
Step by step:
FROM customerschooses the table.WHERE city = 'Bristol'keeps only matching rows.SELECT customer_name, citychooses the displayed columns.
Result:
Text values are normally enclosed in single quotes. Column and table names are not.
Check yourself
- 1.
What is the difference between a row and a column in a database table?
Show the answer
A row is one complete record, such as one customer. A column is one type of information shared by records, such as
city. - 2.
Write a query that shows every column from the
customerstable.Show the answer
- 3.
Write a query that returns only
customer_nameandcityfromcustomers.Show the answer
- 4.
Why is
customer_idusually a stronger primary key thancustomer_name?Show the answer
A primary key must be unique. Different customers can share the same name, while each
customer_idis assigned to only one row.
Written with Kuest's AI tutor from a study session and checked before publishing; no personal details are included. Spot a mistake? Tell us.