Skip to content

SQL 基础

SQL language: 语句, clauses, 数据类型, and 如何 读取 and 编写查询.

你将学到

  • 什么 SQL 是 and 哪里它 comes 从
  • 主要分类的 SQL 语句: DDL, DML, DQL, DCL
  • 常见数据类型: INTEGER, TEXT, DATE, BOOLEAN, DECIMAL
  • 如何 编写你的首先 SELECT, INSERT, UPDATE, and DELETE

概念讲解

什么是 SQL?

SQL (Structured Query Language) is the standard language for interacting with relational databases. It was developed in the 1970s at IBM and has been standardized by ANSI/ISO. Despite minor dialect differences between PostgreSQL, MySQL, and SQLite, the core syntax is the same across all of them — learn it once and it transfers everywhere.

Statement Categories

SQL statements fall into four groups:

  • DDL (Data Definition Language) — CREATE, ALTER, DROP — defines the schema
  • DML (Data Manipulation Language) — INSERT, UPDATE, DELETE — modifies data
  • DQL (Data Query Language) — SELECT — reads data
  • DCL (Data Control Language) — GRANT, REVOKE — manages permissions

Common Data Types

| Type | Example | Use case | |------|---------|----------| | INTEGER / SERIAL | 42 | Whole numbers, IDs | | VARCHAR(n) / TEXT | 'hello' | Strings | | DECIMAL(p,s) | 19.99 | Money, precise decimals | | DATE / TIMESTAMP | 2025-01-15 | Dates and times | | BOOLEAN | TRUE | True/false flags |

Your First Statements

A SELECT reads rows, an INSERT adds a row, an UPDATE changes existing rows, and a DELETE removes rows. Every SQL statement ends with a semicolon. Keywords are conventionally written in uppercase for readability, though SQL is case-insensitive for keywords.

示例代码

              -- DQL: read all columns from the products table
SELECT * FROM products;

-- DML: insert a new product
INSERT INTO products (name, price, in_stock)
VALUES ('Wireless Mouse', 29.99, TRUE);

-- DML: update a product's price
UPDATE products SET price = 24.99 WHERE name = 'Wireless Mouse';

-- DML: delete a product
DELETE FROM products WHERE name = 'Wireless Mouse';
            

这些 four 语句 cover 核心的 day-到-day SQL. 总是 use WHERE clause 使用 UPDATE and DELETE 到 avoid affecting 每个行.

动手试一试

  • SQL Formatter

    粘贴 SQL 到 auto-格式 and 验证语法.

  • SQL Escaper

    Escape 特殊 characters in SQL 字符串 literals.

常见错误

错误写法

运行 UPDATE or DELETE 不使用 WHERE clause

正确做法

不使用 WHERE, 每个行 是 affected. 总是包含 WHERE clause, and 测试使用 SELECT 首先到 preview affected 行.

错误写法

Forgetting semicolon at 端的 语句

正确做法

一些 tools 需要它, 一些做 不. 总是端 语句使用 semicolon 到 avoid ambiguity, 特别是 in scripts 使用多个语句.

练习 SQL 基础

5 个练习

练习 SQL 基础

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误