SQL Syntax
SQL has a few simple writing rules. Learn them once and every later lesson will be easier to read.
SQL Statements
A command you send to the database is called a statement. Most actions in a database are done with statements.
Example
SELECT * FROM students;This statement reads every column of every row from the students table.
A statement is made of:
- Keywords, words with a special meaning such as
SELECT,FROMandWHERE - Names of tables and columns, such as
studentsandcity - Values, such as
'Karachi'or20
Keywords Are Not Case Sensitive
SELECT, select and Select all mean the same thing. These two statements give the same result:
Example
SELECT name FROM students;
select name from students;Most developers write keywords in CAPITAL letters and names in lowercase. It makes a query much easier to read, so this tutorial does the same.
Semicolon at the End
The semicolon ; marks the end of a statement. It lets you send several statements one after another:
Example
SELECT name FROM students;
SELECT title FROM courses;Some tools run a single statement without a semicolon, but always adding it is a good habit.
Spaces and New Lines
SQL does not care about extra spaces or line breaks. A long query is easier to read when each part is on its own line:
Example
SELECT name, city, marks
FROM students
WHERE marks > 80;| name | city | marks |
|---|---|---|
| Ayesha Siddiqui | Lahore | 85 |
| Fatima Noor | Islamabad | 92 |
| Sana Iqbal | Lahore | 88 |
Text Values and Numbers
Text values go inside single quotes. Numbers are written without quotes.
Example
SELECT name FROM students WHERE city = 'Lahore';
SELECT name FROM students WHERE age = 22;If a text value itself has a single quote in it, write two single quotes: 'Ali''s laptop'.
Comments
Comments are notes for people. The database ignores them.
Example
-- This is a one-line comment
SELECT name FROM students; -- a comment can also end a line
/* This is a comment
over several lines */
SELECT title FROM courses;The Most Important SQL Commands
| Command | What it does |
|---|---|
SELECT | Reads data from a table |
INSERT INTO | Adds new rows |
UPDATE | Changes existing rows |
DELETE | Removes rows |
CREATE DATABASE | Makes a new database |
CREATE TABLE | Makes a new table |
ALTER TABLE | Changes the columns of a table |
DROP TABLE | Deletes a whole table |
You will learn each of these in the following lessons.
Exercise
Exercise
How should the text value Karachi be written in a SQL statement?
