Introduction
SELECT statement, one of the most commonly used statements in SQL, is used to select data in a table. This lab will learn SELECT and how to apply it to real practices.
Learning Objective
- SELECT Basic syntax
- Mathematical symbol conditions
- AND OR IN
- Wildcards
- Sort
- SQL built-in functions and calculations
- Subqueries and joins queries
Preparation
Before we start, download relevant data tables and create a database named mysql_labex (3 tables: department, employee, project).
Start MySQL service and log in as root.
cd ~/project sudo service mysql start mysql -u root
There are two files create-database.sql and insert-data.sql, which are located in ~/project/.
Load data in the file. You need to enter the command in the MySQL console to build the database:
source ~/project/create-database.sql source ~/project/insert-data.sql
In the database operating statements, the most frequently used, also considered the most important is the SELECT query. In previous labs, we've used SELECT * FROM table_name; statements in many places to see everything in a table. SELECT can be used with keywords of a variety of constraints, which encompass a variety of features. This lab will introduce these uses in detail.
Basic SELECT statement
The basic format of SELECT statement:
SELECT row name FROM table name WHERE constraint;
If you want to query all contents of the table, then query the name of the column with an asterisk *, which represents all columns in the table will be queried. In most cases, we only need to see the specified column of a table, such as to see the name and age of the employee table:
USE mysql_labex; SELECT name,age FROM employee;
MariaDB [mysql_labex]> SELECT name,age FROM employee; +------+------+ | name | age | +------+------+ | Tom | 26 | | Jack | 24 | | Rose | 22 | | Jim | 35 | | Mary | 21 | | Alex | 26 | | Ken | 27 | | Rick | 24 | | Joe | 31 | | Mike | 23 | | Jobs | NULL | | Tony | NULL | +------+------+ 12 rows in set (0.000 sec)
Mathmatical symbol conditions
SELECT statements often have WHERE constraints, used to achieve more accurate queries. WHERE constraints can have mathematical notation (=, ,>=,
SELECT name,age FROM employee WHERE age>25;
Filter results with age over 25:
MariaDB [mysql_labex]> SELECT name,age FROM employee WHERE age>25; +------+------+ | name | age | +------+------+ | Tom | 26 | | Jim | 35 | | Alex | 26 | | Ken | 27 | | Joe | 31 | +------+------+ 5 rows in set (0.000 sec)
Or find the name, age, and phone of an employee named Mary:
SELECT name,age,phone FROM employee WHERE name='Mary';
Result:
MariaDB [mysql_labex]> SELECT name,age,phone FROM employee WHERE name='Mary'; +------+------+--------+ | name | age | phone | +------+------+--------+ | Mary | 21 | 100101 | +------+------+--------+ 1 row in set (0.000 sec)
"AND" & "OR"
We can have more than one constraints after WHERE, and based on the logical relationship of these conditions, we can use OR and AND to connect:
Filter - age is less than 25, or age is greater than 30
SELECT name,age FROM employee WHERE age30;
MariaDB [mysql_labex]> SELECT name,age FROM employee WHERE age30; +------+------+ | name | age | +------+------+ | Jack | 24 | | Rose | 22 | | Jim | 35 | | Mary | 21 | | Rick | 24 | | Joe | 31 | | Mike | 23 | +------+------+ 7 rows in set (0.000 sec)
Filter - age is greater than 25, and age is less than 30
SELECT name,age FROM employee WHERE age>25 AND age <p>If we need to include age 25 and 30, use <strong>age BETWEEN 25 AND 30</strong> :<br> </p> <pre class="brush:php;toolbar:false">MariaDB [mysql_labex]> SELECT name,age FROM employee WHERE age>25 AND age SELECT name,age FROM employee WHERE age BETWEEN 25 AND 30; +------+------+ | name | age | +------+------+ | Tom | 26 | | Alex | 26 | | Ken | 27 | +------+------+ 3 rows in set (0.000 sec)
IN & NOT IN
Keywords IN and NOT IN are used to filter results in a certain range. For instance, we want to find people in dpt3 or dpt4:
SELECT name,age,phone,in_dpt FROM employee WHERE in_dpt IN ('dpt3','dpt4');
For NOT IN, such as in the following command, we will get people not in dpt1 nor dpt3:
SELECT name,age,phone,in_dpt FROM employee WHERE in_dpt NOT IN ('dpt1','dpt3');
MariaDB [mysql_labex]> SELECT name,age,phone,in_dpt FROM employee WHERE in_dpt IN ('dpt3','dpt4'); +------+------+--------+--------+ | name | age | phone | in_dpt | +------+------+--------+--------+ | Tom | 26 | 119119 | dpt4 | | Rose | 22 | 114114 | dpt3 | | Rick | 24 | 987654 | dpt3 | | Mike | 23 | 110110 | dpt4 | | Tony | NULL | 102938 | dpt3 | +------+------+--------+--------+ 5 rows in set (0.000 sec) MariaDB [mysql_labex]> SELECT name,age,phone,in_dpt FROM employee WHERE in_dpt NOT IN ('dpt1','dpt3'); +------+------+--------+--------+ | name | age | phone | in_dpt | +------+------+--------+--------+ | Tom | 26 | 119119 | dpt4 | | Jack | 24 | 120120 | dpt2 | | Mary | 21 | 100101 | dpt2 | | Joe | 31 | 110129 | dpt2 | | Mike | 23 | 110110 | dpt4 | | Jobs | NULL | 19283 | dpt2 | +------+------+--------+--------+ 6 rows in set (0.000 sec)
Wildcards
The keyword LIKE is used with wildcards in SQL statements, with wildcards representing unknown characters. Wildcards in SQL are _ and %. Which _ represents an unspecified character, %represents indefinite unspecified characters.
For example, if you only remember that the first four digits of the phone number are 1101 and the last two digits are forgotten, you can replace them with two _ wildcards:
SELECT name,age,phone FROM employee WHERE phone LIKE '1101__';
and here we have phone numbers starting with 1101:
MariaDB [mysql_labex]> SELECT name,age,phone FROM employee WHERE phone LIKE '1101__'; +------+------+--------+ | name | age | phone | +------+------+--------+ | Joe | 31 | 110129 | | Mike | 23 | 110110 | +------+------+--------+ 2 rows in set (0.000 sec)
In another case, such as when you only remember the first letter of the name, and you do not know the length of the name, then use % wildcard instead of indefinite characters:
SELECT name,age,phone FROM employee WHERE name LIKE 'J%';
Here we have names starting with J:
MariaDB [mysql_labex]> SELECT name,age,phone FROM employee WHERE name LIKE 'J%'; +------+------+--------+ | name | age | phone | +------+------+--------+ | Jack | 24 | 120120 | | Jim | 35 | 100861 | | Joe | 31 | 110129 | | Jobs | NULL | 19283 | +------+------+--------+ 4 rows in set (0.000 sec)
Sort your results
In order to make queried results more organized and easy to follow, we might need to sort them by certain rules. ORDER BY comes in handy. By default, ORDER BY is in ascending arrangement, and by using ASC and DESC, we can also get results in ascending and descending order.
For example, we sort salary in a descending order, SQL statement:
SELECT name,age,salary,phone FROM employee ORDER BY salary DESC;
MariaDB [mysql_labex]> SELECT name,age,salary,phone FROM employee ORDER BY salary DESC; +------+------+--------+--------+ | name | age | salary | phone | +------+------+--------+--------+ | Jobs | NULL | 3600 | 19283 | | Joe | 31 | 3600 | 110129 | | Ken | 27 | 3500 | 654321 | | Rick | 24 | 3500 | 987654 | | Mike | 23 | 3400 | 110110 | | Tony | NULL | 3400 | 102938 | | Alex | 26 | 3000 | 123456 | | Mary | 21 | 3000 | 100101 | | Jim | 35 | 3000 | 100861 | | Rose | 22 | 2800 | 114114 | | Jack | 24 | 2500 | 120120 | | Tom | 26 | 2500 | 119119 | +------+------+--------+--------+ 12 rows in set (0.000 sec)
SQL built-in functions and calculations
SQL allows the calculation of the data in the table. In this regard, SQL has five built-in functions that do the result of SELECT:
Function: | COUNT | SUM | AVG | MAX | MIN |
---|---|---|---|---|---|
For: | count numbers | sum up | average | maximum value | minimum value |
The COUNT function can be used for any data type (because it is only a count), while SUM and AVG functions can only calculate numeric data types. MAX and MIN can be used for numeric, string, or datetime data types.
For example, when we want to calculate the maximum and minimum value of salary, we use a statement like this:
SELECT MAX(salary) AS max_salary,MIN(salary) FROM employee;
You may have noticed a tiny detail. Use AS keyword can rename value. E.g. Max value is renamed into max_salary:
MariaDB [mysql_labex]> SELECT MAX(salary) AS max_salary,MIN(salary) FROM employee; +------------+-------------+ | max_salary | MIN(salary) | +------------+-------------+ | 3600 | 2500 | +------------+-------------+ 1 row in set (0.000 sec)
Subqueries
The SELECT statements discussed above all involve data in only one table, but sometimes you have to process multiple tables to get the information you need. For example, you want to know a few projects done by the department where the employee named "Tom" is located. Employee information is stored in the employee table, but the project information is stored in the project table.
We can use subqueries to deal with such situations:
SELECT of_dpt,COUNT(proj_name) AS count_project FROM project WHERE of_dpt IN (SELECT in_dpt FROM employee WHERE name='Tom');
MariaDB [mysql_labex]> SELECT of_dpt,COUNT(proj_name) AS count_project FROM project -> WHERE of_dpt IN -> (SELECT in_dpt FROM employee WHERE name='Tom'); +--------+---------------+ | of_dpt | count_project | +--------+---------------+ | dpt4 | 2 | +--------+---------------+ 1 row in set (0.000 sec)
Subqueries can also be extended to three, four or more layers.
Join
When dealing with multiple tables, the subquery is only useful when the results are from the same table. However, if you need to display data in two or more tables, you must use the join operation.
The basic idea is to connect two or more tables as a new table to operate, as follows:
SELECT id,name,people_num FROM employee,department WHERE employee.in_dpt = department.dpt_name ORDER BY id;
This result is the number of employees in each department, where employee id and name from the employee table, people_num from the department table:
MariaDB [mysql_labex]> SELECT id,name,people_num -> FROM employee,department -> WHERE employee.in_dpt = department.dpt_name -> ORDER BY id; +----+------+------------+ | id | name | people_num | +----+------+------------+ | 1 | Tom | 15 | | 2 | Jack | 12 | | 3 | Rose | 10 | | 4 | Jim | 11 | | 5 | Mary | 12 | | 6 | Alex | 11 | | 7 | Ken | 11 | | 8 | Rick | 10 | | 9 | Joe | 12 | | 10 | Mike | 15 | | 11 | Jobs | 12 | | 12 | Tony | 10 | +----+------+------------+ 12 rows in set (0.000 sec)
Another connection statement format is to use the JOIN ON syntax. The statement is the same as:
SELECT id,name,people_num FROM employee JOIN department ON employee.in_dpt = department.dpt_name ORDER BY id;
Result is the same.
Summary
In this lab we learned the basic use of SELECT statement:
- Basic syntax
- Mathmatical symbol conditions
- AND OR IN
- Wildcards
- Sort
- SQL built-in functions and calculations
- Sunqueries and connection queries
? Practice Now: SQL's SELECT Statement
Want to Learn More?
- ? Learn the latest MySQL Skill Trees
- ? Read More MySQL Tutorials
- ? Join our Discord or tweet us @WeAreLabEx
The above is the detailed content of SQL Fundamentals | SELECT Statement | Database Management. For more information, please follow other related articles on the PHP Chinese website!

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

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.