search
HomeDatabaseMysql TutorialSQL Quick Reference: Simplify Database Management

SQL Quick Reference: Simplify Database Management

Apr 08, 2025 pm 06:21 PM
aiaggregate function

sql cheat sheet

This blog provides comprehensive guidance on the most important SQL commands and operations. It covers basic queries, connections, subqueries, indexes, and more advanced concepts.

Table of contents

  1. Basics of SQL
  2. Data definition language (ddl)
  3. Data operation language (dml)
  4. Data query language (dql)
  5. Data Control Language (dcl)
  6. join in
  7. Subquery
  8. index
  9. Aggregation function
  10. Grouping and sorting
  11. trade
  12. Advanced sql
  13. Best Practices

Basics of SQL

Structure of SQL query

 select column1, column2
from table_name
Where condition
order by column
limit n;

Comment in SQL

  • Single comment : -- This is a comment
  • Multiple comments :
 /* this is a 
     multi-line comment */

Data definition language (ddl)

Create a table

 create table table_name (
    column1 datatype [constraints],
    column2 datatype [constraints],
    ...
);

Example:

 create table employees (
    id int primary key,
    name varchar(100),
    age int,
    hire_date date
);

Modify the form

Add column

 alter table table_name
add column_name datatype;

Delete a column

 alter table table_name
drop column column_name;

Modify columns

 alter table table_name
modify column column_name datatype;

Rename table

 alter table old_table_name
rename to new_table_name;

Delete a table

 drop table table_name;

Create an index

 create index index_name
on table_name (column_name);

Delete the index

 drop index index_name;

Data operation language (dml)

Insert data into table

 insert into table_name (column1, column2, ...)
values ​​(value1, value2, ...);

Example:

 insert into employees (id, name, age, hire_date)
values ​​(1, 'john doe', 30, '2022-01-01');

Update data in table

 update table_name
set column1 = value1, column2 = value2, ...
where condition;

Example:

 update employees
set age = 31
where id = 1;

Delete data from table

 delete from table_name
where condition;

Example:

 delete from employees
where id = 1;

Data query language (dql)

Select data from the table

 select column1, column2, ...
from table_name
Where condition
order by column
limit n;

Example:

 select * from employees;
select name, age from employees where age > 30;

Wildcard

  • *: Select all columns
  • %: a wildcard with zero or more characters (in the like clause)
  • _: Wildcards representing only one character (in the like clause)

Example:

 select * from employees where name like 'j%';

Data Control Language (dcl)

Grant permissions

 grant permission on object to user;

Example:

 grant select, insert on employees to 'user1';

Revoke permissions

 revoke permission on object from user;

Example:

 revoke select on employees from 'user1';

join in

Inner connection

Returns rows when there are matches in both tables.

 Select columns
from table1
inner join table2
on table1.column = table2.column;

Left connection (or left outer connection)

Returns all rows in the left table and matched rows in the right table. If it does not match, the columns in the right table will display a null value.

 Select columns
from table1
left join table2
on table1.column = table2.column;

Right connection (or right external connection)

Returns all rows in the right table and matched rows in the left table. If it does not match, the columns in the left table will display a null value.

 Select columns
from table1
right join table2
on table1.column = table2.column;

Fully external connection

Returns rows when there is a match in one of the tables.

 Select columns
from table1
full outer join table2
on table1.column = table2.column;

Subquery

Subquery in select

 select column1, (select column2 from table2 where condition) as alias
from table1;

Subquery in where

 select column1
from table1
where column2 in (select column2 from table2 where condition);

Subquery in from

 select alias.column1
from (select column1 from table2 where condition) as alias;

index

Create an index

 create index index_name
on table_name (column1, column2);

Delete the index

 drop index index_name;

Unique index

Make sure that all values ​​in one column (or a group of columns) are unique.

 create unique index index_name
on table_name (column_name);

Aggregation function

Count

Calculate the number of rows that meet certain criteria.

 select count(*) from table_name where condition;

and

Returns the sum of the values ​​in the column.

 select sum(column_name) from table_name;

Average voltage

Returns the average value of the values ​​in the column.

 select avg(column_name) from table_name;

Minimum and maximum values

Returns the minimum and maximum values ​​in the column.

 select min(column_name), max(column_name) from table_name;

Grouping and sorting

Grouping basis

Group rows with the same value into summary rows.

 select column1, count(*)
from table_name
group by column1;

have

Apply group by to filter the group.

 select column1, count(*)
from table_name
group by column1
having count(*) > 5;

Order basis

Sort the result set in ascending or descending order.

 select column1, column2
from table_name
order by column1 desc;

trade

Start trading

 begin transaction;

Conduct a transaction

 commit;

Roll back transactions

 rollback;

Advanced sql

Case when

Conditional logic in the query.

 select column1,
       case
           When condition then 'result 1'
           When condition then 'result 2'
           else 'default'
       end as alias
from table_name;

United and United All

  • union : merges the result sets of two or more queries (delete duplicates).
  • union all : merge result sets (retain duplicates).
 select column from table1
union
select column from table2;

select column from table1
union all
select column from table2;

Best Practices

  • Use join instead of subquery when possible for better performance.
  • Index frequently searched columns to speed up queries.
  • Avoid select * and specify only the columns you need.
  • Use limit on the number of rows returned for large result sets .
  • Standardize your data to avoid redundancy and improve consistency.
  • Use the where clause instead of filtering the data before aggregation.
  • Test query performance, especially for large data sets.
  • Use transactions to ensure data consistency, especially operations involving multiple dml statements.

in conclusion

This sql cheat sheet covers all the basic sql commands and techniques required to use a relational database. Whether you are querying, inserting, updating, or connecting data, this guide will help you use SQL more effectively.


The above is the detailed content of SQL Quick Reference: Simplify Database Management. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor