SQL Syntax
SQL follows a unique set of rules and guidelines called syntax. This tutorial gives you a quick start with SQL by listing all the basic SQL syntax.
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g., "Customers" or "Orders"), and tables contain records (rows) with data.
Example - Customers Table
| CustomerID | CustomerName | ContactName | City | Country |
|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Berlin | Germany |
| 2 | Ana Trujillo | Ana Trujillo | México D.F. | Mexico |
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
Tip:
SQL keywords are NOT case sensitive:
select is the same as SELECT. However, it's a common convention to write SQL keywords in uppercase.
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
SELECT * FROM Customers;
Most Important SQL Commands
SELECT- extracts data from a databaseUPDATE- updates data in a databaseDELETE- deletes data from a databaseINSERT INTO- inserts new data into a databaseCREATE DATABASE- creates a new databaseALTER DATABASE- modifies a databaseCREATE TABLE- creates a new tableALTER TABLE- modifies a tableDROP TABLE- deletes a tableCREATE INDEX- creates an index (search key)
SQL Statement Syntax
SELECT
SELECT column1, column2, ...
FROM table_name;
SELECT DISTINCT
SELECT DISTINCT column1, column2, ...
FROM table_name;
WHERE
SELECT column1, column2, ...
FROM table_name
WHERE condition;
ORDER BY
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
INSERT INTO
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
UPDATE
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DELETE
DELETE FROM table_name
WHERE condition;
Important:
Be careful when updating or deleting records! If you omit the
WHERE clause, ALL records will be updated or deleted!