当前位置:网站首页>100 important knowledge points that SQL must master: using functions to process data
100 important knowledge points that SQL must master: using functions to process data
2022-06-27 21:33:00 【Guge academic】
8.1 function
Like most other computer languages ,SQL You can also use functions to process data . Function one
Is performed on data , It provides convenience for data conversion and processing .
Used in the previous lesson to remove spaces at the end of a string RTRIM() It's just a function .
The problem with functions
Before learning this lesson and practicing it , You should know how to use SQL Function exists
problem .
With almost all DBMS Both equally support SQL sentence ( Such as SELECT ) Different , every last
DBMS All have specific functions . in fact , Only a few functions are used by all the main DBMS
Equally support . Although all types of functions can generally be used in every DBMS Use in , but
The names and syntax of each function can be extremely different . To illustrate possible problems , surface 8-1
Lists 3 A common function and its application in various DBMS Chinese grammar :

You can see , And SQL Statements are different ,SQL Functions are not portable . This means for the special
set SQL The code written by the implementation may not be used in other implementations .
portable (portable)
The code written can run on multiple systems .
For code portability , many SQL Programmers disapprove of using implementation specific functions . though
But it's good to do so , But sometimes it's not good for the performance of the application . If not used
These functions , Writing some application code can be difficult . Other methods must be used to achieve
DBMS Work that can be done very effectively .
Tips : Whether the function should be used ?
Now? , You face the choice of whether you should use functions . It's up to you , Use or not to make
There is no right or wrong to use . If you decide to use a function , You should make sure that you annotate the code ,
So that you can ( Or someone else ) Can know these exactly SQL The meaning of the code .
8.2 Using functions
majority SQL The implementation supports the following types of functions .
Used to process text strings ( Such as deleting or filling in values , Convert values to uppercase or lowercase ) The article of
This function .
Used for arithmetic operations on numeric data ( If return absolute value , Do algebra ) Of
Numerical function .
Used to process date and time values and extract specific components from these values ( If two dates are returned
The difference between the , Check the validity of the date ) The date and time functions of .
Formatting function for generating beautiful and understandable output content ( Such as expressing the day in language
period , The amount is expressed in currency symbols and thousandths ).
return DBMS Special information being used ( Such as returning user login information ) The system function of .
We saw in the last lesson that functions are used for SELECT The following column names , But functions do more than just
this . It can also be used as SELECT Other components of the statement , If in WHERE Used in clauses ,
Among others SQL Statement, etc , More will be introduced later .
8.2.1 Text processing function
In the last lesson , We have seen an example of a text processing function , It uses RTRIM()
Function to remove the space to the right of the column value . Here's another example , This time, I used UPPER()
function :
Input ▼
SELECT vend_name, UPPER(vend_name) AS vend_name_upcase
FROM Vendors
ORDER BY vend_name;
Output ▼
vend_name vend_name_upcase
--------------------------- ----------------------------
Bear Emporium BEAR EMPORIUM
Bears R Us BEARS R US
Doll House Inc. DOLL HOUSE INC.
Fun and Games FUN AND GAMES
Furball Inc. FURBALL INC.
Jouets et ours JOUETS ET OURS
You can see , UPPER() Convert text to uppercase , Therefore, each supplier in this example lists
Twice , For the first time Vendors Values stored in the table , The second time as a column vend_name_
upcase Convert to uppercase .
Tips : Capitalization , A lowercase letter , Mixed case
By this time you should already know SQL Functions are not case sensitive , therefore upper(), UPPER(),
Upper() Fine , substr(), SUBSTR(), SubStr() Either way . Whatever you want
like , But pay attention to keeping the style consistent , Don't change , Otherwise you write the program code
It's not easy to read .
surface 8-2 Lists some common text processing functions .
surface 8-2 Medium SOUNDEX Further explanation is needed . SOUNDEX Is a will any text
This string is converted into an algorithm that describes the alphanumeric pattern of its voice representation . SOUNDEX Considering
Similar pronunciation characters and syllables , Makes it possible to make phonetic comparisons of strings rather than letter ratios
a . although SOUNDEX No SQL Concept , But most DBMS Are provided for SOUNDEX
Support for .
explain : SOUNDEX Support
PostgreSQL I won't support it SOUNDEX() , So the following example does not apply to this DBMS.
in addition , If you're creating SQLite When used SQLITE_SOUNDEX Compile time options , that
Well SOUNDEX() stay SQLite Available in . because SQLITE_SOUNDEX Not by default
Compile time options for , So most SQLite Implementation does not support SOUNDEX() .
Here is an example of how to use SOUNDEX() Examples of functions . Customers There is a customer in the table
Kids Place , Its contact name is Michelle Green . If this is wrong ,
This contact name should actually be Michael Green , What to do ? obviously , Press the correct
Contact name search will not return data , As shown below :
Input ▼
SELECT cust_name, cust_contact
FROM Customers
WHERE cust_contact = 'Michael Green';
Output ▼
cust_name cust_contact
-------------------------- ----------------------------
Now try using SOUNDEX() Function to search , It matches all sounds, similar to Michael
Green The contact name of :
Input ▼
SELECT cust_name, cust_contact
FROM Customers
WHERE SOUNDEX(cust_contact) = SOUNDEX('Michael Green');
Output ▼
cust_name cust_contact
-------------------------- ----------------------------
Kids Place Michelle Green
analysis ▼
In this case , WHERE Clause use SOUNDEX() Function cust_contact The column value
And search strings into their SOUNDEX value . because Michael Green and
Michelle Green Sound alike , So their SOUNDEX Values match , therefore WHERE
Clause correctly filters out the required data .
8.2.2 Date and time processing functions
The date and time are stored in the table with corresponding data types , Each of these DBMS They all have their own characteristics
Special form . Date and time values are stored in a special format , In order to sort or
Filter , And save physical storage space .
Applications generally do not use date and time storage formats , So the date and time functions are always
For reading 、 Count and process these values . For this reason , The date and time functions are in SQL
Plays an important role in . Unfortunately , They are very inconsistent , The worst portability .
Let's give a simple example , To illustrate the usage of date processing function . Orders The table contains
All orders have an order date . To retrieve all orders for a year , Need to find by order date ,
But you don't need a full date , Just the year .
For in SQL Server To retrieve the 2020 All orders for the year , It can be done as follows :
Input ▼
SELECT order_num
FROM Orders
WHERE DATEPART(yy, order_date) = 2020;
Output ▼
order_num
-----------
20005
20006
20007
20008
20009
analysis ▼
This example uses DATEPART() function , seeing the name of a thing one thinks of its function , This function returns a part of the date
branch . DATEPART() Function has two arguments , They are the returned components and the returned components
The date of the minute . In this example , DATEPART() Only from order_date Return year in column .
Through and with 2020 Compare , WHERE Clause only filters out orders in this year .
The following is the use of the name DATE_PART() Similar to the function of PostgreSQL edition :
Input ▼
SELECT order_num
FROM Orders
WHERE DATE_PART('year', order_date) = 2020;
Oracle No, DATEPART() function , However, there are several dates that can be used to complete the same search
Rational function . for example :
Input ▼
SELECT order_num
FROM Orders
WHERE EXTRACT(year FROM order_date) = 2020;
analysis ▼
In this case , EXTRACT() Function is used to extract the component of the date , year Indicates where to extract
Parts of , The return value and 2020 Compare .
Tips :PostgreSQL Support Extract()
In addition to the above DatePart() ,PostgreSQL Also support Extract() function ,
So it can be used in this way .
Another way to do the same is to use BETWEEN The operator :
Input ▼
SELECT order_num
FROM Orders
WHERE order_date BETWEEN to_date('2020-01-01', 'yyyy-mm-dd')
AND to_date('2020-12-31', 'yyyy-mm-dd');
analysis ▼
In this example ,Oracle Of to_date() The date() function converts two strings to a date .
A contain 2020 year 1 month 1 Japan , The other contains 2020 year 12 month 31 Japan . BETWEEN
The operator is used to find all orders between two dates . It is worth noting that , Same code
stay SQL Server neutralize , Because it doesn't support to_date() function . however , If
use DATEPART() Replace to_date() , Of course, you can use this type of statement .
DB2,MySQL and MariaDB With various date processing functions , But there is no DATEPART() .
DB2,MySQL and MariaDB Users can use the name YEAR() Function to extract from the date
year :
Input ▼
SELECT order_num
FROM Orders
WHERE YEAR(order_date) = 2020;
stay SQLite There's a little trick in this :
Input ▼
SELECT order_num
FROM Orders
WHERE strftime('%Y', order_date) = '2020';
The examples given here extract and use date components ( year ). Filter by month , It is possible to carry out phase
Same treatment , Use AND Operators can compare years and months .
DBMS The function provided is far more than simple date component extraction . majority DBMS Have comparative
date 、 Perform date calculation 、 Select functions such as date format . however , You can see , No
Same as DBMS Date − The time processing function may be different . About you DBMS Specifically supported by
date − Time processing functions , Please refer to the corresponding documentation .
8.2.3 Numerical processing function
Numeric processing functions process only numeric data . These functions are generally mainly used in algebra 、 Triangle or a few
How to calculate , So unlike strings or dates − Time processing functions are used so frequently .
Here's the irony , In the main DBMS The function of , Numerical functions are the most consistent 、 Most unified
A function of one . surface 8-3 List some common numerical processing functions .
About the details DBMS Supported arithmetic processing functions , Please refer to the corresponding documentation .
8.3 Summary
This lesson introduces how to use SQL Data processing function . Although these functions are formatting 、
It is very useful in processing and filtering data , But they are in all kinds of SQL The implementation is very inconsistent .
边栏推荐
- KDD 2022 | 图“预训练、提示、微调”范式下的图神经网络泛化框架
- 于文文、胡夏等明星带你玩转派对 皮皮APP点燃你的夏日
- Dictionary tree (review)
- Implementation string mystring
- Tutorial | fNIRS data processing toolkit homer2 download and installation
- GoLand永久激活
- Modify large online games through CE modifier
- 释放开源数据库创新力量 | 【甘肃】openGauss Meetup圆满结束
- How to do a good job of gateway high availability protection in the big promotion scenario
- 农产品期货怎么做怎么开户,期货开户手续费多少,找谁能优惠手续费?
猜你喜欢

GoLand永久激活

What is a low code development platform? Why is it so hot now?

行业案例|从零售之王看银行数字化转型的运营之道

mysql使用笔记一

Unity3d button adapts the size according to the text content

白嫖红队goby&POC,叫你如何白嫖?

MySQL performance optimization index function, hidden, prefix, hash index usage (2)

Covering access to 2w+ traffic monitoring equipment, EMQ creates a new digital engine for all elements of traffic in Shenzhen

It took me 6 months to complete the excellent graduation project of undergraduate course. What have I done?

How dbeaver restores and backs up databases
随机推荐
No wonder people chose apifox instead of postman
爱数课实验 | 第五期-基于机器学习方法的商品评论情感判定
Unity3D Button根据文本内容自适应大小
Very comprehensive dolphin scheduler installation and use documents
Share how I take notes
Openharmony hisysevent dotting and calling practice of # Summer Challenge (L2)
It took me 6 months to complete the excellent graduation project of undergraduate course. What have I done?
Shuttle hides the return button of the AppBar
分享一次自己定位 + 解决问题的经历
SQL Server for循环用法
互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?
安装gatewayworker之后启动start.php
于文文、胡夏等明星带你玩转派对 皮皮APP点燃你的夏日
Experience Navicat premium 16, unlimited reset, 14 day trial method (with source code)
麒麟V10安装字体
分享|智慧环保-生态文明信息化解决方案(附PDF)
SQL必需掌握的100个重要知识点:用通配符进行过滤
Model reasoning acceleration based on tensorrt
Share an experience of self positioning + problem solving
Serveur mandataire SQUID