Welcome to Day 2 of the 30-Day SQL Challenge! Today, we'll cover the fundamental SQL CREATE statement used to define and create tables, and the SELECT statement to retrieve data from a database. 🚀
- What is the CREATE Statement?
- Creating Your First Table
- What is the SELECT Statement?
- Basic Syntax of SELECT
- Using SELECT with Simple Queries
- Practice Exercises
- Summary
The CREATE statement is used to define new database objects such as tables, views, indexes, or databases. For today, we’ll focus on creating tables.
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
);column1, column2: The names of the columns.datatype: The data type for each column (e.g.,INT,VARCHAR,DATE).constraints: Optional rules likePRIMARY KEYorNOT NULL.
Let’s create a table named students:
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT,
enrollment_date DATE
);student_id: An integer that uniquely identifies each student.name: A string of up to 100 characters.age: An integer representing the student’s age.enrollment_date: A date indicating when the student enrolled.
The SELECT statement is the backbone of SQL queries. It allows you to retrieve data from one or more tables in a database. By specifying columns or using special symbols like *, you can determine exactly what data you want to retrieve.
SELECT column1, column2, ...
FROM table_name;column1, column2, ...: The columns you want to retrieve.table_name: The table from which you want to retrieve the data.
To retrieve all columns, use *:
SELECT *
FROM table_name;Imagine a table named employees:
| id | name | age | department |
|---|---|---|---|
| 1 | John Doe | 30 | HR |
| 2 | Jane Smith | 25 | IT |
| 3 | Sam Brown | 35 | Marketing |
- Retrieve all columns:
SELECT *
FROM employees;- Retrieve specific columns:
SELECT name, age
FROM employees;- Write a
CREATE TABLEstatement to create a new table namedproductswith the following structure:product_id(integer, primary key)product_name(string, maximum 50 characters, cannot be null)price(decimal with 2 decimal places)stock_quantity(integer)
- Insert some sample data into the
studentstable you created. - Write a
SELECTquery to retrieve only thenameanddepartmentcolumns from theemployeestable. - Use
SELECTto retrieve all rows from yourstudentstable.
Today, you learned about:
- The
CREATEstatement for defining and creating tables. - Writing basic
CREATE TABLEqueries. - The
SELECTstatement and its syntax for retrieving data. - Using
SELECTwith specific columns and*.
Tomorrow, we’ll dive deeper into filtering data with the WHERE clause. 🌟
Previous: Day 1 - Introduction to SQL 🔙
Next: Day 3 - Filtering Data with WHERE 🔜