switch·Esc back

SQL

You might say

How do I write a query for users who placed an order in the last seven days?

Ask a relational database to read or change structured recordsSQL can select, filter, join, insert, update, and delete data in relational databases. Parameterize user values instead of building query strings, and inspect indexes and execution plans when a query becomes slow. A correct query still needs authorization around it.
Know first
SELECT name, city FROM users WHERE city = 'Shenzhen'
idnamecity
1XiaoliShenzhen
2AjiHangzhou
3Xiao LinShanghai

When to use it

  • Filter and sort records
  • Join related tables
  • Aggregate totals and counts
  • Update data inside a transaction

When NOT to use it

  • Concatenate untrusted input into a query
  • Select every column when only a few are needed
  • Run an unbounded update or delete
  • Assume a database permission replaces application authorization
Anatomy
SELECT name FROM users WHERE city = ?
idnamecity
1MiaShenzhen
SELECT, INSERT, UPDATE or DELETE, decide whether to read or modify
Relational data collection to be operated; first confirm the table name and field structure
WHERE limits the scope of influence; placeholders such as question marks are safely passed by parameterized queries.
Variants
SELECT
SELECTRead matching rows
Read records without changing them.
INSERT
INSERTAdd a new row
Create a new record.
UPDATE
UPDATEChange the row hit by WHERE
Update selected records; check the WHERE clause.
DELETE
DELETEDelete the row hit by WHERE
Remove selected records after checking recovery.
Typical use cases
Order query
Query usersSELECT to find records that meet the conditions
SELECT id, name, planFROM usersWHERE plan = 'pro';
Result: u_23 · Alex Chen · pro
User lookup
New taskINSERT creates a record
ExecuteINSERT INTO tasks ... Returnid = task_8842
Analytics total
Update dataUPDATE only modifies the specified user
UPDATE usersSET city = 'Shenzhen'WHERE id = 'u_23';
Affects 1 row · Modification successful
Data update
Delete recordConfirm WHERE before DELETE
SELECT WHERE id=t_42Confirm 1 lineDELETE
Avoid accidentally deleting the entire table
Further reading