SQL commands are categorized into several types of statements, each designed for a specific purpose:
These statements retrieve data from a database:
The SELECT
statement is used to retrieve one or more rows of data from one or more tables. You can specify the columns you want to retrieve, filter results, and sort data using the ORDER BY
clause.
SELECT column1, column2 FROM table WHERE condition;
These statements modify data in the database:
The INSERT
statement adds new rows to a table:
INSERT INTO table (column1, column2) VALUES (value1, value2);
The UPDATE
statement modifies existing data in a table:
UPDATE table SET column1 = value1 WHERE condition;
The DELETE
statement removes rows from a table:
DELETE FROM table WHERE condition;
These statements define, alter, or drop database objects:
The CREATE TABLE
statement creates a new table with specified columns and data types:
CREATE TABLE table_name (
column1 datatype,
column2 datatype
);
The ALTER TABLE
statement modifies an existing table, such as adding or dropping columns:
ALTER TABLE table_name
ADD column_name datatype;
The DROP TABLE
statement deletes an existing table and its data:
DROP TABLE table_name;
SQL statements often include one or more clauses to refine their behaviour:
The WHERE
clause filters rows based on a specified condition:
SELECT column1, column2 FROM table WHERE condition;
The ORDER BY
clause sorts the result set based on one or more columns:
SELECT column1, column2 FROM table ORDER BY column1 ASC, column2 DESC;
The GROUP BY
clause groups rows based on specified columns, often used with aggregate functions like COUNT
, SUM
, or AVG
:
SELECT column1, COUNT(column2) FROM table GROUP BY column1;
SQL includes a set of reserved keywords that are fundamental to constructing queries:
SELECT
: Retrieves data from a table.FROM
: Specifies the source table for a query.WHERE
: Filters rows based on a condition.INSERT INTO
: Adds new rows to a table.UPDATE
: Modifies existing data in a table.DELETE FROM
: Removes rows from a table.CREATE TABLE
: Defines a new table.ALTER TABLE
: Modifies an existing table.DROP TABLE
: Deletes a table.ORDER BY
: Sorts the result set.GROUP BY
: Groups rows for aggregation.Understanding SQL syntax is crucial for effectively working with relational databases. This overview provides a foundation for constructing SQL statements, using clauses to refine queries, and recognizing essential SQL keywords. SQL’s power lies in its ability to retrieve, manipulate, and manage data, making it a fundamental tool for anyone dealing with databases.