SQL Syntax

Writing SQL statements

SQL statements are English-like database queries.

Keywords include SELECT, UPDATE, WHERE, ORDER BY, etc.

ANSI Standard SQL is the lingua franca for relational databases.

Example

#

List all suppliers in Italy.

SELECT FirstName, LastName, Country
  FROM Customer
 WHERE Country = 'Italy'

Usage

SQL was originally designed to be entered on a console and results would display back to a screen. In reality this never happened because by mistyping a query the operator can potentially do great damage to a database.

Today, SQL is mostly used by programmers who use SQL embedded in their programs to build applications that require data from a database.


CRUD

SQL supports four fundamental operations, collectively known as CRUD (Create, Read, Update, Delete). They are:

  1. SELECT  -- Read the data
  2. INSERT  -- Insert new data
  3. UPDATE  -- Update existing data
  4. DELETE  -- Remove data

CRUD is an important concept because it gives users full control over their data. It allows them to retrieve, add, update, and remove any data item.

Below are some SQL syntax and code examples.


SQL SELECT Syntax

The general form of a SELECT statement.

SELECT column-names
  FROM table-name
 WHERE condition
 ORDER BY sort-order

Example

List all customers in Paris sorted by last name.

SELECT FirstName, LastName, City, Country 
  FROM Customer
 WHERE City = 'Paris'
 ORDER BY LastName


SQL INSERT Syntax

The general form of an INSERT statement.

INSERT table-name (column-names)
VALUES (column-values)

Example

Add Oxford Trading to the list of suppliers.

INSERT Supplier (CompanyName, ContactName, City, Country)
VALUES ('Oxford Trading', 'Ian Smith', 'Oxford', 'UK')


SQL UPDATE Syntax

The general form of an UPDATE statement.

UPDATE table-name
   SET column-name = column-value
 WHERE condition

Example

Change the order item with Id = 388 and set the quantity to 2.

UPDATE OrderItem
   SET Quantity = 2
 WHERE Id = 388


SQL DELETE Syntax

The general form of a DELETE statement.

DELETE table-name
 WHERE condition

Example

Remove orderitems that have an orderId of 117.

DELETE OrderItem
 WHERE OrderId = 117


You may also like



Guides