Skip to content

SQL Basic Syntax

After mastering basic database concepts, now let's learn SQL basic syntax. This chapter introduces core SQL syntax rules, including statement structure, comments, identifiers, etc.

Basic Structure of SQL Statements

Standard Format

SQL statements typically consist of the following parts:

sql
SELECT column1, column2  -- Select columns to query
FROM table_name           -- Specify table to query
WHERE condition          -- Add filter condition
GROUP BY column          -- Group
HAVING condition         -- Filter after grouping
ORDER BY column          -- Sort
LIMIT number;            -- Limit number of results

Statement Features

  • Case Insensitive: SELECT and select are the same
  • Ends with Semicolon: Each SQL statement ends with ;
  • Multi-line: SQL statements can be written across multiple lines
  • Indentation: Proper indentation improves readability

SQL Statement Categories

1. DDL (Data Definition Language)

Used to define database structure:

sql
-- Create database
CREATE DATABASE mydb;

-- Create table
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

-- Modify table
ALTER TABLE users ADD COLUMN age INT;

-- Delete table
DROP TABLE users;

2. DML (Data Manipulation Language)

Used to manipulate data in tables:

sql
-- Query data
SELECT * FROM users;

-- Insert data
INSERT INTO users (id, name) VALUES (1, 'Zhang San');

-- Update data
UPDATE users SET name = 'Li Si' WHERE id = 1;

-- Delete data
DELETE FROM users WHERE id = 1;

3. DCL (Data Control Language)

Used to control access permissions:

sql
-- Grant permission
GRANT SELECT ON users TO 'user1'@'localhost';

-- Revoke permission
REVOKE SELECT ON users FROM 'user1'@'localhost';

4. TCL (Transaction Control Language)

Used to manage transactions:

sql
-- Start transaction
START TRANSACTION;

-- Commit transaction
COMMIT;

-- Rollback transaction
ROLLBACK;

SQL Comments

Single-line Comments

Use -- or #:

sql
-- This is a single-line comment
SELECT * FROM users;

# This is also a single-line comment
SELECT name FROM users;

Multi-line Comments

Use /* ... */:

sql
/*
This is a multi-line comment
Can contain multiple lines of text
Used to explain complex SQL statements
*/
SELECT id, name, age
FROM users
WHERE age > 18;

Comment Best Practices

sql
-- Query all users over 18 years old
SELECT
    id,           -- User ID
    name,         -- Username
    age,          -- Age
    city          -- City
FROM users
WHERE age > 18;  -- Filter condition

SQL Identifiers

Identifier Rules

Identifiers are names of database objects (table names, column names, etc.) and must follow these rules:

  • Can contain letters, numbers, and underscores
  • Must start with a letter or underscore
  • Cannot use reserved words
  • Case sensitive (depends on database configuration)

Naming Recommendations

sql
-- Good naming
user_id
order_date
product_name
total_amount

-- Not recommended naming
userId          -- Camel case
order-date       -- Using hyphens
123_column       -- Starts with number
table            -- Reserved word

Using Quotes for Special Names

If you need to use reserved words or names containing special characters, use quotes:

sql
-- MySQL uses backticks
SELECT `order` FROM `table`;

-- SQL Server uses square brackets
SELECT [order] FROM [table];

-- PostgreSQL uses double quotes
SELECT "order" FROM "table";

Common Keywords

KeywordDescriptionExample
SELECTSelect dataSELECT * FROM users
FROMSpecify tableFROM users
WHEREFilter conditionWHERE age > 18
GROUP BYGroupGROUP BY city
HAVINGFilter groupsHAVING COUNT(*) > 10
ORDER BYSortORDER BY name
LIMITLimit resultsLIMIT 10
KeywordDescriptionExample
CREATECreateCREATE TABLE users
ALTERModifyALTER TABLE users
DROPDeleteDROP TABLE users
TRUNCATEClear tableTRUNCATE TABLE users
KeywordDescriptionExample
INSERTInsertINSERT INTO users VALUES
UPDATEUpdateUPDATE users SET name = '...'
DELETEDeleteDELETE FROM users
KeywordDescriptionExample
PRIMARY KEYPrimary keyid INT PRIMARY KEY
FOREIGN KEYForeign keyFOREIGN KEY (user_id)
UNIQUEUniqueemail VARCHAR(100) UNIQUE
NOT NULLNot nullname VARCHAR(50) NOT NULL
DEFAULTDefault valueage INT DEFAULT 0

SQL Statement Execution Order

Logical Execution Order

The logical execution order of SQL statements is different from the writing order:

sql
SELECT  -- 5. Select columns
FROM    -- 1. Specify table
WHERE   -- 2. Filter rows
GROUP BY -- 3. Group
HAVING  -- 4. Filter groups
ORDER BY -- 6. Sort
LIMIT   -- 7. Limit count

Example

sql
-- Execution order
SELECT city, COUNT(*) as user_count  -- 5. Calculate user count per city
FROM users                         -- 1. From users table
WHERE age >= 18                     -- 2. Filter 18 and above
GROUP BY city                       -- 3. Group by city
HAVING user_count > 5               -- 4. Only show cities with more than 5 users
ORDER BY user_count DESC            -- 6. Sort by user count descending
LIMIT 5;                            -- 7. Only show first 5

SQL Operators

Arithmetic Operators

sql
-- Basic operations
SELECT price * quantity  -- Multiplication
SELECT price + discount  -- Addition
SELECT price - discount  -- Subtraction
SELECT price / quantity  -- Division
SELECT price % 2         -- Modulo

Comparison Operators

sql
-- Comparison operations
WHERE age = 18           -- Equal to
WHERE age != 18          -- Not equal to
WHERE age > 18           -- Greater than
WHERE age < 18           -- Less than
WHERE age >= 18          -- Greater than or equal to
WHERE age <= 18          -- Less than or equal to

Logical Operators

sql
-- Logical operations
WHERE age > 18 AND city = 'Beijing'   -- Logical AND
WHERE age > 18 OR city = 'Beijing'    -- Logical OR
WHERE NOT (age > 18)                  -- Logical NOT

Range and Set Operators

sql
-- Range operations
WHERE age BETWEEN 18 AND 30           -- Range query
WHERE city IN ('Beijing', 'Shanghai')  -- Set query
WHERE name LIKE 'Zhang%'              -- Fuzzy matching
WHERE email IS NULL                   -- Check for null
WHERE email IS NOT NULL               -- Check for not null

String Processing

String Concatenation

sql
-- MySQL uses CONCAT
SELECT CONCAT(name, ' - ', city) FROM users;

-- PostgreSQL uses ||
SELECT name || ' - ' || city FROM users;

-- SQL Server uses +
SELECT name + ' - ' + city FROM users;

String Case

sql
-- Convert to uppercase
SELECT UPPER(name) FROM users;

-- Convert to lowercase
SELECT LOWER(name) FROM users;

String Length

sql
-- Get string length
SELECT LENGTH(name) FROM users;

String Substring

sql
-- Substring
SELECT SUBSTRING(name, 1, 3) FROM users;  -- Start from 1st character, take 3 characters

Date/Time Processing

Current Date/Time

sql
-- Get current date/time
SELECT NOW();           -- MySQL
SELECT CURRENT_TIMESTAMP; -- PostgreSQL
SELECT GETDATE();       -- SQL Server

Date Calculation

sql
-- MySQL
SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);     -- 7 days later
SELECT DATE_SUB(NOW(), INTERVAL 7 DAY);     -- 7 days earlier

-- PostgreSQL
SELECT NOW() + INTERVAL '7 days';           -- 7 days later
SELECT NOW() - INTERVAL '7 days';           -- 7 days earlier

Date Formatting

sql
-- MySQL
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d');     -- 2024-01-15

-- PostgreSQL
SELECT TO_CHAR(NOW(), 'YYYY-MM-DD');      -- 2024-01-15

NULL Value Handling

NULL Characteristics

  • NULL represents "unknown" or "does not exist"
  • NULL is not equal to any value, including NULL
  • In mathematical operations, NULL + any value = NULL

NULL Checking

sql
-- Check for NULL
WHERE email IS NULL

-- Check for NOT NULL
WHERE email IS NOT NULL

NULL Operations

sql
-- COALESCE function: returns first non-NULL value
SELECT COALESCE(email, 'Not filled') FROM users;

-- NULLIF function: returns NULL if two parameters are equal
SELECT NULLIF(price, 0) FROM products;

-- Handle NULL in mathematical operations
SELECT price * quantity * COALESCE(discount, 1) FROM orders;

Data Type Conversion

CAST Function

sql
-- Convert data types
SELECT CAST('123' AS INT);           -- String to integer
SELECT CAST(123 AS VARCHAR(10));     -- Integer to string
SELECT CAST('2024-01-15' AS DATE);  -- String to date

Type Conversion Functions

sql
-- MySQL
SELECT CONVERT('123', INT);

-- PostgreSQL
SELECT '123'::INT;

-- SQL Server
SELECT CONVERT(INT, '123');

SQL Statement Best Practices

1. Use Meaningful Aliases

sql
-- Good
SELECT
    u.name AS user_name,
    o.order_date,
    COUNT(o.id) AS order_count
FROM users u
JOIN orders o ON u.id = o.user_id;

-- Not good
SELECT
    a.name,
    b.order_date,
    COUNT(b.id)
FROM users a
JOIN orders b ON a.id = b.user_id;

2. Use Indentation Appropriately

sql
-- Good formatting
SELECT
    name,
    age,
    city
FROM users
WHERE age > 18
ORDER BY name;

-- Not good formatting
SELECT name, age, city FROM users WHERE age > 18 ORDER BY name;

3. Add Comments

sql
-- Query order information for active users
SELECT
    u.username,
    o.order_id,
    o.total_amount
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.status = 'active'
  AND o.order_date > '2024-01-01';

Summary

This chapter introduced SQL basic syntax:

  • Statement Structure: SELECT, FROM, WHERE and other basic structures
  • Statement Categories: DDL, DML, DCL, TCL
  • Comment Syntax: Single-line and multi-line comments
  • Identifier Rules: Naming rules and quote usage
  • Common Keywords: Query, definition, operation, constraint
  • Execution Order: Logical execution order of SQL statements
  • Operators: Arithmetic, comparison, logical operators
  • NULL Handling: NULL characteristics and handling methods

Mastering these basic syntaxes is the foundation for writing SQL statements. In the following chapters, we will learn in depth how to use these syntaxes to query and manipulate data.

Next Step: Learn SELECT Query to start retrieving data from databases.

Content is for learning and research only.