Home Database SQL What are the sql query statements?

What are the sql query statements?

Dec 10, 2020 pm 02:48 PM
sql query statement

sql query statement: 1. View the table structure [SQL>DESC emp]; 2. Query all columns [SQL>SELECT * FROM emp]; 3. Query the specified column; 4. Query the specified row; 5. Use arithmetic expressions; 6. Use logical operation symbols.

What are the sql query statements?

Recommended (free): sql tutorial

sql query statement:

1. Simple query statement

1. View table structure

SQL>DESC emp;
Copy after login

2. Query all columns

SQL>SELECT * FROM emp;
Copy after login

3. Query specified columns

SQL>SELECT empmo, ename, mgr FROM emp;
SQL>SELECT DISTINCT mgr FROM emp; 只显示结果不同的项
Copy after login

4. Query specified rows

SQL>SELECT * FROM emp WHERE job='CLERK';
Copy after login

5. Use arithmetic expressions

SQL>SELECT ename, sal*13+nvl(comm,0)  FROM emp; 
nvl(comm,1)的意思是,如果comm中有值,则nvl(comm,1)=comm; comm中无值,则nvl(comm,1)=0。
SQL>SELECT ename, sal*13+nvl(comm,0) year_sal FROM emp; (year_sal为别名,可按别名排序)
SQL>SELECT * FROM emp WHERE hiredate>'01-1月-82';
Copy after login

6. Use like operator (%,_)

% represents one or more characters, _ represents a character, [charlist] represents any single character in the character column, [^charlist] or [!charlist] represents any single character not in the character column.

SQL>SELECT * FROM emp WHERE ename like 'S__T%';
Copy after login

7. Use In

SQL>SELECT * FROM emp WHERE job IN ('CLERK','ANALYST');
Copy after login

# in the where condition. 8. Query the statement that the field content is empty/non-empty

SQL>SELECT * FROM emp WHERE mgr IS/IS NOT NULL;
Copy after login

9. Use logical operation symbols

SQL>SELECT * FROM emp WHERE (sal>500 or job='MANAGE') and ename like 'J%';
Copy after login

10. Sort query results by field value

SQL>SELECT * FROM emp ORDER BY deptno, sal DESC; (按部门升序,并按薪酬降序)
Copy after login

11 . Use case ... when ... then ... end to process the query results

SQL>SELECT CASE a WHEN "original_a" THEN "新命名Aa" WHEN "original_b" THEN "新命名Bb" END AS XXX;
Copy after login

Select the a field in the table and name it XXX. When the content of a is original_a, the content is displayed as "New name Aa".

Original table

abc
original_a......
original_b......

Query results

XXX
New name Aa
New name Bb

12. Format date data

SQL>SELECT DATE_FORMAT(start_time,"%Y-%m-%d") as "时间";
Copy after login

2. Complex Query

1. Data grouping (max, min, avg, sum, count)

SQL>SELECT MAX(sal),MIN(age),AVG(sal),SUM(sal) from emp;
SQL>SELECT * FROM emp where sal=(SELECT MAX(sal) from emp));
SQL>SELEC COUNT(*) FROM emp;
Copy after login

2. group by (used for query Group statistics of results) and having clause (used to limit group display results)

SQL>SELECT deptno,MAX(sal),AVG(sal) FROM emp GROUP BY deptno;
SQL>SELECT deptno, job, AVG(sal),MIN(sal) FROM emp group by deptno,job having AVG(sal)<2000;
Copy after login

Summary for data grouping:

  • a. The grouping function only Can appear in the select list, having, order by clause (cannot appear in where)

  • b. If the select statement also contains group by, having, order by, then Their order is group by, having, order by.

  • c. If there are columns, expressions and grouping functions in the select column, these columns and expressions must appear in the group by clause, otherwise an error will occur. That is: the column name in the SELECT clause must be a grouping column or column function

3. Multi-table query

SQL>SELECT e.name,e.sal,d.dname FROM emp e, dept d WHERE e.deptno=d.deptno order by d.deptno;
SQL>SELECT e.ename,e.sal,s.grade FROM emp e,salgrade s WHER e.sal BETWEEN s.losal AND s.hisal;
Select a.*, b.x, c.y from a
  left outer join (Select * from tablex where condition1)b
  on a.id=b.id
  left outer join (Select * from tabley where condition2)c
  on a.id=c.id
where condition3;
Copy after login

4. Self-join (referring to the connection query of the same table)

SQL>SELECT er.ename, ee.ename mgr_name from emp er, emp ee where er.mgr=ee.empno;
Copy after login

5. Subquery (select statement embedded in other sql statements, also called nested query)

5.1 Single row subquery

SQL>SELECT ename FROM emp WHERE deptno=(SELECT deptno FROM emp where ename=&#39;SMITH&#39;);
Copy after login

Query the names of people in the same department as smith in the query table. Because the return result is only one row, use "=" to connect the subquery statement

5.2 Multi-row subquery

SQL>SELECT ename,job,sal,deptno from emp WHERE job IN (SELECT DISTINCT job FROM emp WHERE deptno=10);
Copy after login

Query the names and jobs of employees with the same job as department number 10 in the table , salary, department number. Because there are multiple rows in the returned result, "IN" is used to connect the subquery statements.

5.3 Use ALL

SQL>SELECT ename,sal,deptno FROM emp WHERE sal> ALL (SELECT sal FROM emp WHERE deptno=30);或SQL>SELECT ename,sal,deptno FROM emp WHERE sal> (SELECT MAX(sal) FROM emp WHERE deptno=30);
Copy after login

to query the name, salary and department number of employees whose salary is higher than that of all employees with department number 30. The above two statements are functionally the same, but in terms of execution efficiency, the function will be much higher.

5.4 Use ANY

SQL>SELECT ename,sal,deptno FROM emp WHERE sal> ANY (SELECT sal FROM emp WHERE deptno=30);或SQL>SELECT ename,sal,deptno FROM emp WHERE sal> (SELECT MIN(sal) FROM emp WHERE deptno=30);
Copy after login

to query the name, salary and department number of the employee whose salary is higher than that of any employee with department number 30 (as long as the salary is higher than a certain employee) . The above two statements are functionally the same, but in terms of execution efficiency, the function will be much higher.

5.5 Multi-column subquery

SQL>SELECT * FROM emp WHERE (job, deptno)=(SELECT job, deptno FROM emp WHERE ename=&#39;SMITH&#39;);
Copy after login

5.6 Using subquery in the from clause

 SQL>SELECT emp.deptno,emp.ename,emp.sal,t_avgsal.avgsal FROM emp,(SELECT emp.deptno,avg(emp.sal) avgsal FROM emp GROUP BY emp.deptno) t_avgsal where emp.deptno=t_avgsal.deptno AND emp.sal>t_avgsal.avgsal ORDER BY emp.deptno;
Copy after login

5.7 Paging query

Each row of data in the database has a The corresponding row number is called rownum.

SQL>SELECT a2.* FROM (SELECT a1.*, ROWNUM rn FROM (SELECT * FROM emp ORDER BY sal) a1 WHERE ROWNUM<=10) a2 WHERE rn>=6;
Copy after login

To specify the query column, sort the query results, etc., you only need to modify the innermost subquery.

5.8 Create a new table with query results

SQL>CREATE TABLE mytable (id,name,sal,job,deptno) AS SELECT empno,ename,sal,job,deptno FROM emp;
Copy after login

5.9 Merge query (union union, intersect intersection, union all union intersection, minus difference set)

SQL>SELECT ename, sal, job FROM emp WHERE sal>2500 UNION(INTERSECT/UNION ALL/MINUS) SELECT ename, sal, job FROM emp WHERE job=&#39;MANAGER&#39;;
Copy after login

Merge query The execution efficiency is much higher than logical queries such as and and or.

5.10 Use subqueries to insert data

SQL>CREATE TABLE myEmp(empID number(4), name varchar2(20), sal number(6), job varchar2(10), dept number(2));
Copy after login

First create an empty table;

SQL>INSERT INTO myEmp(empID, name, sal, job, dept) SELECT empno, ename, sal, job, deptno FROM emp WHERE deptno=10;
Copy after login

Then insert the data with department number 10 in the emp table into the new table myEmp to achieve Batch query of data.

5.11 Using a query to update the data in the table

SQL>UPDATE emp SET(job, sal, comm)=(SELECT job, sal, comm FROM emp where ename=&#39;SMITH&#39;) WHERE ename=&#39;SCOTT&#39;;
Copy after login

Related free learning recommendations: php programming (video)

The above is the detailed content of What are the sql query statements?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use sql datetime How to use sql datetime Apr 09, 2025 pm 06:09 PM

The DATETIME data type is used to store high-precision date and time information, ranging from 0001-01-01 00:00:00 to 9999-12-31 23:59:59.99999999, and the syntax is DATETIME(precision), where precision specifies the accuracy after the decimal point (0-7), and the default is 3. It supports sorting, calculation, and time zone conversion functions, but needs to be aware of potential issues when converting precision, range and time zones.

How to create tables with sql server using sql statement How to create tables with sql server using sql statement Apr 09, 2025 pm 03:48 PM

How to create tables using SQL statements in SQL Server: Open SQL Server Management Studio and connect to the database server. Select the database to create the table. Enter the CREATE TABLE statement to specify the table name, column name, data type, and constraints. Click the Execute button to create the table.

How to use sql if statement How to use sql if statement Apr 09, 2025 pm 06:12 PM

SQL IF statements are used to conditionally execute SQL statements, with the syntax as: IF (condition) THEN {statement} ELSE {statement} END IF;. The condition can be any valid SQL expression, and if the condition is true, execute the THEN clause; if the condition is false, execute the ELSE clause. IF statements can be nested, allowing for more complex conditional checks.

What does sql foreign key constraint mean? What does sql foreign key constraint mean? Apr 09, 2025 pm 06:03 PM

Foreign key constraints specify that there must be a reference relationship between tables to ensure data integrity, consistency, and reference integrity. Specific functions include: data integrity: foreign key values ​​must exist in the main table to prevent the insertion or update of illegal data. Data consistency: When the main table data changes, foreign key constraints automatically update or delete related data to keep them synchronized. Data reference: Establish relationships between tables, maintain reference integrity, and facilitate tracking and obtaining related data.

How to use SQL deduplication and distinct How to use SQL deduplication and distinct Apr 09, 2025 pm 06:21 PM

There are two ways to deduplicate using DISTINCT in SQL: SELECT DISTINCT: Only the unique values ​​of the specified columns are preserved, and the original table order is maintained. GROUP BY: Keep the unique value of the grouping key and reorder the rows in the table.

Several common methods for SQL optimization Several common methods for SQL optimization Apr 09, 2025 pm 04:42 PM

Common SQL optimization methods include: Index optimization: Create appropriate index-accelerated queries. Query optimization: Use the correct query type, appropriate JOIN conditions, and subqueries instead of multi-table joins. Data structure optimization: Select the appropriate table structure, field type and try to avoid using NULL values. Query Cache: Enable query cache to store frequently executed query results. Connection pool optimization: Use connection pools to multiplex database connections. Transaction optimization: Avoid nested transactions, use appropriate isolation levels, and batch operations. Hardware optimization: Upgrade hardware and use SSD or NVMe storage. Database maintenance: run index maintenance tasks regularly, optimize statistics, and clean unused objects. Query

How to use the sql round field How to use the sql round field Apr 09, 2025 pm 06:06 PM

The SQL ROUND() function rounds the number to the specified number of digits. It has two uses: 1. num_digits&gt;0: rounded to decimal places; 2. num_digits&lt;0: rounded to integer places.

How to write a tutorial on how to connect three tables in SQL statements How to write a tutorial on how to connect three tables in SQL statements Apr 09, 2025 pm 02:03 PM

This article introduces a detailed tutorial on joining three tables using SQL statements to guide readers step by step how to effectively correlate data in different tables. With examples and detailed syntax explanations, this article will help you master the joining techniques of tables in SQL, so that you can efficiently retrieve associated information from the database.

See all articles