Introduction to SQL Syntax
SQL (Structured Query Language) is the standard language for interacting with relational databases. It's used to manage and manipulate data efficiently.
Basic SQL Statements
Most actions you perform on a database are done using SQL statements. These statements are made up of keywords and are relatively easy to learn. Let's start with a simple example.
Selecting All Records from a Table
Syntax
SELECT * FROM table_name;
This selects all columns and rows from a table. Here's an example using the "Customers" table:
Example
SELECT * FROM Customers;
Output
(All columns and rows from the Customers table will be displayed here.)
Database Tables
Databases are usually made up of one or more tables. Each table has a name (like "Customers" or "Orders") and stores data in rows (records).
Example Table: Customers
Here's a look at part of the well-known Northwind sample database's "Customers" table:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
This table has five records (one per customer) and seven columns (fields).
Important SQL Commands
Here are some of the most important SQL commands, grouped by function:
Data Definition Language (DDL)
CREATE DATABASE
: Creates a new database.ALTER DATABASE
: Modifies a database.CREATE TABLE
: Creates a new table.ALTER TABLE
: Modifies a table.DROP TABLE
: Deletes a table.CREATE INDEX
: Creates an index (for faster searching).DROP INDEX
: Deletes an index.
Data Manipulation Language (DML)
SELECT
: Retrieves data from a database.UPDATE
: Updates data in a database.DELETE
: Deletes data from a database.INSERT INTO
: Inserts new data into a database.
Data Control Language (DCL)
GRANT
: Gives users database access.REVOKE
: Takes away database access.
Case Sensitivity and Semicolons
SQL keywords are generally not case-sensitive (SELECT
is the same as select
). In this tutorial, we'll use uppercase for SQL keywords. Many database systems require semicolons (;) to separate multiple SQL statements.