SQL concepts and usage

1. Basic concepts

SQL (Structured Query Language), that is, Structured Query Language, is a standard interactive language for relational database management systems. It is widely used in the fields of database design, data query, data manipulation and data management.

SQL is mainly divided into the following parts:

  • Data Definition Language (DDL): Used to define database structures, such as creating, modifying, deleting databases, tables, views, and indexes.
  • Data Manipulation Language (DML): Used to manipulate data in the database, such as querying, inserting, updating, and deleting data.
  • Data Control Language (DCL): Used to control database access rights, such as authorization and revoking rights.

2. Database structure

In a relational database, data is stored in tables, and each table contains several rows and several columns. Each row represents a data record, and each column represents a data field.

2.1 Create a table

New tables can be created using SQL statements. The syntax is as follows:

CREATE TABLE table_name (
  column1 datatype,
  column2 datatype,
  column3 datatype,
  ...
);

Where table_name is the table name, columncolumn name, datatypeand data type.

For example, the following SQL statement creates a customerstable named :

CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  email VARCHAR(255)
);

2.2 Insert data

Use SQL statements to insert new data records into the table. The syntax is as follows:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Where table_nameis the table name, columnis the column name, valueand is the data value to be inserted.

For example, the following SQL statement customersinserts a new data record into the table named :

INSERT INTO customers (id, name, email)
VALUES (1, 'John', '[email protected]');

2.3 Query data

Data records can be queried from tables using SQL statements. The syntax is as follows:

SELECT column1, column2, column3, ...
FROM table_name
WHERE condition;

Where columnis the column name, table_nameis the table name, and conditionis the query condition.

For example, the following SQL statement customersqueries all data records from the table named :

SELECT * FROM customers;

2.4 Update data

Data records in the table can be updated using SQL statements. The syntax is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Where table_name is the name of the table, columnthe column name, valuethe data value to be updated, conditionand the update condition.

For example, the following SQL statement updates customersthe data record with id 1 in the table named:

UPDATE customers
SET name = 'Jane'
WHERE id = 1;

2.5 Add data

Use SQL statements to add data records to the table. The syntax is as follows:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

Among them table_name, is the table name, column1, column2, ...are the column names to be inserted in the table, value1and , value2, ...are the values ​​of the corresponding columns.

For example, the following SQL statement customers inserts a data record into the table named:

INSERT INTO customers (name, email)
VALUES ('John', '[email protected]');

2.6 Delete data

Use SQL statements to delete data records in the table. The syntax is as follows:

DELETE FROM table_name
WHERE condition;

Where table_nameis the name of the table and conditionis the deletion condition.

For example, the following SQL statement deletes the data record with 1 customersin the table named :id

DELETE FROM customers
WHERE id = 1;

2.7 Constraints

In database design, constraints can be used to restrict data entry and modification to ensure data integrity and consistency.

2.7.1 Primary key

The primary key is a unique identifier used to uniquely identify each data record in the table. A table can have only one primary key.

In SQL, PRIMARY KEYconstraints are used to define primary keys. For example, the following SQL statement creates a table with a primary key customers:

CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  email VARCHAR(255)
);

2.7.2 Foreign keys

A foreign key is a column that points to a primary key in another table, and is used to establish a relationship between tables. A table can have multiple foreign keys.

In SQL, FOREIGN KEYforeign keys can be defined using constraints. ordersFor example, the following SQL statement creates a table with foreign keys :

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  amount DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id)
);

where customer_idcolumn is a foreign key referencing customersthe id column of the table.

Unique Constraints
Unique constraints are used to ensure that data records in a table are not duplicated. A table can have multiple unique constraints.

In SQL, UNIQUEunique constraints can be defined using constraints. For example, the following SQL statement creates a table with a unique constraint users:

CREATE TABLE users (
  id INT PRIMARY KEY,
  username VARCHAR(255) UNIQUE,
  password VARCHAR(255)
);

where usernamethe column has a unique constraint to ensure that each user's username is not duplicated.

3. Database Management

Database management includes aspects such as database backup, recovery, and performance optimization.

3.1 Database Backup and Recovery

Taking regular backups of your database is a good form of data protection so that you can restore data in the event of data loss or corruption.

The MySQL database can be mysqldumpbacked up using the command as follows:

mysqldump -u username -p database_name > backup.sql

Among them username, is the database user name, database_nameis the name of the database to be backed up, and backup.sql is the name of the backup file.

The backed up database can be mysqlrestored using the command as follows:

mysql -u username -p database_name < backup.sql

Among them username, is the database user name, database_nameis the name of the database to be restored, and backup.sql is the name of the backup file.

3.2 Database performance optimization

In order to improve the performance of the database, the following measures can be taken:

  • Design a reasonable database structure, including using appropriate data types, table relationships, etc.
  • Use indexes to speed up data query operations.
  • Use stored procedures and triggers to optimize data manipulation.
  • Cache frequently used data, such as using a cache system or using an in-memory database.

4. Client link

Various client tools can be used to connect to SQL databases, such as MySQL, Oracle, SQL Server, etc. The following takes the MySQL client as an example to introduce how to connect to the database.

4.1 Install MySQL

To install MySQL on Mac, you can use the Homebrew package manager. Enter the following command in the terminal:

brew install mysql

4.2 Connect to MySQL

To connect to MySQL, you can use the mysql command line tool. Enter the following command in the terminal:

mysql -u username -p

Among them username, is the database user name, and a password will be prompted after entering the command.

4.3 Execute SQL statement

In the MySQL client, SQL statements can be executed directly. For example, the following SQL statement queries all data records in the table named customers:

SELECT * FROM customers;

After execution, the query result will be output.

4.4 Commonly used commands of MySQL client:

  • SHOW DATABASES: Displays a list of all databases.
  • USE database_name: Select the database to use.
  • SHOW TABLES: Displays a list of all tables in the current database.
  • DESC table_name: Display the structure and column information of the table.
  • SELECT * FROM table_name: Query all data records in the table.
  • EXIT 或 QUIT: Exit the MySQL client.

For example, the following SQL statement inserts a new data record in the customers table:

INSERT INTO customers (name, email) VALUES ('John', '[email protected]');

4.5 Administrator user

In a SQL database, the administrator user has the highest privileges and can create and manage other users and control access to the database. Admin users can perform the following actions:

  • Create and delete users.
  • Grant and revoke permissions from users.
  • Create and drop databases and tables.
  • Backup and restore databases.
  • Monitor the performance and status of the database.

The username and password of the admin user are kept strictly confidential and changed periodically to increase the security of the database.

In a MySQL database, you can use the root user as the administrator user. For example, the following SQL statement creates a newuseruser named and grants that user mydatabaseaccess to the database named :

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

Among them, 'newuser'@'localhost' indicates the user name newuser, which can only be accessed locally, 'password' is the password of the user, and mydatabase is the database name. GRANT ALL PRIVILEGESstatement grants the user mydatabaseall privileges on the database.

5. SQL functions

SQL functions are predefined operations for manipulating data or performing calculations. The following are commonly used functions in SQL:

5.1 Aggregate functions

Aggregate functions are used for statistics and analysis of data. The following are commonly used aggregate functions in SQL:

  • COUNT: Count the number of rows in the table or the number of non-null values ​​in the specified column.
  • SUM: Calculates the sum of the specified column.
  • AVG: Calculates the average value of the specified column.
  • MAX: Find the maximum value of the specified column.
  • MIN: Find the minimum value of the specified column.

For example, the following SQL statement queries the sum of the amount column in the table named orders:

SELECT SUM(amount) FROM orders;

5.2 String functions

String functions are used to operate on string data. The following are commonly used string functions in SQL:

  • UPPER: Converts a string to uppercase letters.
  • LOWER: Convert a string to lowercase letters.
  • LENGTH: Returns the length of the string.
  • SUBSTRING: Returns a substring of a string.

For example, the following SQL statement queries the length of the column customersin the table named name:

SELECT LENGTH(name) FROM customers;

5.3 Time function

Time functions are used to operate on date and time data. The following are commonly used time functions in SQL:

  • NOW: Returns the current date and time.
  • YEAR: Returns the year of the date.
  • MONTH: Returns the month of the date.
  • DAY: Returns the number of days in a date.
  • HOUR: Returns the hour of the time.
  • MINUTE: Returns the minutes of the time.
  • SECOND: Returns the seconds of the time.

For example, the following SQL statement queries the year ordersin the column of the table named order_date:

SELECT YEAR(order_date) FROM orders;

6. Summary

This article introduces the basic concept, structure, installation and client connection method of SQL database on Mac. In addition, it also introduces the addition, deletion, modification and query operations of SQL, common functions and administrator users. Mastering these SQL knowledge points can help developers better manage and operate databases.

Guess you like

Origin blog.csdn.net/weixin_47884711/article/details/129980879