CREATE TABLE
The CREATE TABLE command is used to define a new table in your database. You
specify the table name and then list the columns, along with their data types.
Syntax:
SQL
CREATE TABLE table_name (
column1_name datatype,
column2_name datatype,
column3_name datatype
);
Example:
Let's create a table called Students to store student information.
SQL
CREATE TABLE Students (
student_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT
);
INSERT INTO
The INSERT INTO command is used to add new rows of data into a table. You must
specify the table name and the values for each column.
Syntax:
SQL
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
Example:
Let's add a new student to our Students table.
SQL
INSERT INTO Students (student_id, first_name, last_name, age)
VALUES (1, 'Alice', 'Johnson', 20);
SELECT
The SELECT command is used to retrieve data from a table. You can select all
columns or just specific ones.
To select all columns:
SQL
SELECT * FROM table_name;
Example:
SQL
SELECT * FROM Students;
To select specific columns:
SQL
SELECT column1, column2 FROM table_name;
Example:
SQL
SELECT first_name, last_name FROM Students;
UPDATE
The UPDATE command is used to modify existing data in a table. You must use a
WHERE clause to specify which rows to update. If you don't use a WHERE clause, all
rows in the table will be updated.
Syntax:
SQL
UPDATE table_name
SET column1 = new_value1, column2 = new_value2
WHERE some_column = some_value;
Example:
Let's update Alice's age to 21.
SQL
UPDATE Students
SET age = 21
WHERE student_id = 1;
DELETE
The DELETE command is used to remove rows from a table. Just like with UPDATE,
you should always use a WHERE clause to specify which rows to delete.
Syntax:
SQL
DELETE FROM table_name
WHERE some_column = some_value;
Example:
Let's delete the student with student_id of 1.
SQL
DELETE FROM Students
WHERE student_id = 1;
ORDER BY
The ORDER BY clause is used with SELECT to sort the result set. You can sort in
ascending (ASC) or descending (DESC) order. ASC is the default if you don't specify
anything.
Syntax:
SQL
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
Example:
Let's get all students, ordered by age in ascending order.
SQL
SELECT * FROM Students
ORDER BY age ASC;
DROP TABLE
The DROP TABLE command is used to completely remove a table from the database,
including all of its data.
Syntax:
SQL
DROP TABLE table_name;
Example:
SQL
DROP TABLE Students;
Primary Key: A unique identifier for each row in a table. It cannot be null.
Foreign Key: A link between two tables, referring to the primary key of another table.
Candidate Key: Any key that can serve as the primary key.
Super Key: A key that can uniquely identify a row, but may contain extra columns.
Composite Key: A primary key made of two or more columns.
Unique Key: Uniquely identifies rows, but can have one null value.