SQL Statements
Understanding Basic SQL Statements
Structured Query Language (SQL) is a powerful tool for managing and manipulating databases. Whether you are a beginner or looking to brush up on your SQL skills, understanding the fundamental SQL statements is essential. In this article, we will explore some of the most commonly used SQL statements, including SELECT FROM, WHERE, LIKE, AND, OR, BETWEEN, ALTER, and GO. Each statement is explained with examples to help you grasp their usage and syntax effectively.
SELECT FROM
Explanation: The SELECT
statement is used to select data from a database. The returned data is stored in a result table, sometimes called the result set.
SELECT column1, column2, ...
FROM table_name;
Example:
SELECT FirstName, LastName
FROM Employees;
WHERE
Explanation: The WHERE
clause is used to filter records. It returns only those records that meet the specified condition.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
SELECT FirstName, LastName
FROM Employees
WHERE Country = 'Vietnam';
LIKE
Explanation: The LIKE
operator is used in a WHERE
clause to search for a specified pattern in a column.
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Example:
SELECT FirstName
FROM Employees
WHERE FirstName LIKE 'A%';
AND
Explanation: The AND
operator is used to combine multiple conditions in a WHERE
clause. It returns records that satisfy all the conditions.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2;
Example:
SELECT FirstName, LastName
FROM Employees
WHERE Country = 'Vietnam' AND Age > 30;
OR
Explanation: The OR
operator is used to combine multiple conditions in a WHERE
clause. It returns records that satisfy at least one of the conditions.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2;
Example:
SELECT FirstName, LastName
FROM Employees
WHERE Country = 'Vietnam' OR Country = 'Japan';
BETWEEN
Explanation: The BETWEEN
operator is used to select values within a given range. The values can be numbers, text, or dates.
SELECT column1, column2, ...
FROM table_name
WHERE columnN BETWEEN value1 AND value2;
Example:
SELECT FirstName, LastName
FROM Employees
WHERE Age BETWEEN 25 AND 35;
ALTER
Explanation: The ALTER
statement is used to add, delete, or modify columns in an existing table.
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example:
ALTER TABLE Employees
ADD BirthDate DATE;
ALTER TABLE Employees
DROP COLUMN Age;
ALTER TABLE Employees
MODIFY COLUMN LastName VARCHAR(50);
GO
Explanation: The GO
command is used in SQL Server to separate batches of SQL statements.
CREATE TABLE Employees (
ID int,
FirstName varchar(255)
);
GO
INSERT INTO Employees (ID, FirstName)
VALUES (1, 'Phong');
GO
SELECT * FROM Employees;
Join the conversation