Isdate (transact-sql)
Содержание:
Working With SQL Dates
Our “Users” Table:
id | username | first | last | member_since |
---|---|---|---|---|
1 | ohBillNotAgain | Hillary | Clinton | 2011-12-25 |
2 | internetCreator | Al | Gore | 2011-12-8 |
3 | dontMessWithTexas | George | Bush | 2011-7-9 |
Let’s try to get all of our members before December 25, 2011.
Example
SELECT * FROM Users WHERE member_since < '2011-12-25'
Result
id | username | first | last | member_since |
---|---|---|---|---|
2 | internetCreator | Al | Gore | 2011-12-8 |
3 | dontMessWithTexas | George | Bush | 2011-7-9 |
Alright, we said BEFORE December 25, 2011, which means poor Hillary isn’t included because she is on that day. Al barely made the cut, but old George was way before our cut off date. I suppose we should actually talk about what happened. Up to WHERE member_since < ‘2011-12-25’, we know what were doing. We could probably guess what is going on here, but I’ll beat the dead horse. We check our member_since column to see if it is less than, <, our date, which was written in single quotes as ‘2011-12-25’. Often when googling for help with dates, you see this syntax referred to as ‘YYYY-MM-DD’, where Y is for year, M is for month, and D is for day, obviously. Each repetition is a symbol of a blank character space for that element. So, you only want 2 digits for month because that makes sense, and maybe you don’t care about the first 2 characters of year. Instead you just write, YY to get 11. Easy enough, onto the wonderful DATETIMEs
UPDATE несколько записей
Именно предложение WHERE определяет, сколько записей будет обновлено.
Следующая инструкция SQL обновит имя контакта до «Juan» для всех записей, где страна — «Mexico»:
Пример
UPDATE Customers
SET ContactName=’Juan’
WHERE Country=’Mexico’;
Выбор из таблицы «Customers» теперь будет выглядеть следующим образом:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Juan | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
Параметр значений
Параметр | Описание | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
string | Требуемый. Строка, которая будет отформатирована до даты | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
format | Требуемый. Формат для использования. Может быть одно или комбинация следующих значений:
|
Функция DATEPART
DATEPART ( datepart , date )
Эта функция возвращает целое число, представляющее собой указанную аргументом datepart часть заданной вторым аргументом даты (date).
Список допустимых значений аргумента datepart, описанный выше в данном разделе, дополняется еще одним значением
Datepart | Допустимые сокращения |
Weekday — день недели | dw |
DATEPARTSET DATEFIRST
SELECT DATEPART(hh, time_out)*60 + DATEPART(mi, time_out) FROM trip WHERE trip_no=1123 |
SELECT DATEPART(hh, time_in)*60 + DATEPART(mi, time_in) FROM trip WHERE trip_no=1123 |
Теперь мы должны сравнить, превышает ли время прилета время вылета. Если это так, вычесть из первого второе, чтобы получить продолжительность рейса. В противном
случае к разности нужно добавить одни сутки (24*60 = 1440 минут).
SELECT CASE WHEN time_dep>=time_arr THEN time_arr-time_dep+1440 ELSE time_arr-time_dep END dur FROM ( SELECT DATEPART(hh, time_out)*60 + DATEPART(mi, time_out) time_dep, DATEPART(hh, time_in)*60 + DATEPART(mi, time_in) time_arr FROM trip WHERE trip_no=1123 ) tm |
Пример
SELECT pt.trip_no, DATEADD(mi, DATEPART(hh,time_out)*60 + DATEPART(mi,time_out), date) FROM pass_in_trip pt JOIN trip t ON pt.trip_no=t.trip_no WHERE t.trip_no=1123 |
Trip_no | Time |
1123 | 2003-04-05 16:20:00.000 |
1123 | 2003-04-08 16:20:00.000 |
DISTINCT
SQL Server
There are several ways to get the current date in SQL Server, and all of them use functions.
Function | Data Type | Returns |
SYSDATETIME() | datetime2 | Server date time to 7 fractional seconds |
SYSDATETIMEOFFSET() | datetimeoffset | Server date time with time zone to 7 fractional seconds |
SYSUTCDATETIME() | datetime2 | Server date time in UTC to 7 fractional seconds |
CURRENT_TIMESTAMP | datetime | Server date time to 3 fractional seconds |
GETDATE() | datetime | Server date time to 3 fractional seconds |
GETUTCDATE() | datetime | Server date time in UTC to 3 fractional seconds |
These six functions all return the date and time to different amounts of fractional seconds or based on time zones. Notice that CURRENT_TIMESTAMP does not need any opening or closing brackets.
(You can read more about MySQL date data types and functions in this guide)
Let’s see an example of this.
The results are below (translated to rows to make it easier to compare):
Function | Result |
SYSDATETIME() | 2020-07-15 16:24:38.7750094 |
SYSDATETIMEOFFSET() | 2020-07-15 16:24:38.7750094 +00:00 |
SYSUTCDATETIME() | 2020-07-15 06:24:38.7750094 |
CURRENT_TIMESTAMP | 2020-07-15 16:24:38.773 |
GETDATE() | 2020-07-15 16:24:38.773 |
GETUTCDATE() | 2020-07-15 06:24:38.773 |
You can see some differences here:
- The first three functions show fractional seconds to 7 places.
- The two UTC time functions show the current time in the UTC time zone. I ran these functions in Melbourne, Australia, which is UTC +10.
You can also see that CURRENT_TIMESTAMP and GETDATE() show the same values.
CURRENT_TIMESTAMP vs GETDATE
What’s the difference between CURRENT_TIMESTAMP and GETDATE() in SQL Server?
CURRENT_TIMESTAMP is an ANSI SQL compliant function, meaning it complies with the standards (and is likely to exist in other database vendors). GETDATE() is the T-SQL version of that function.
How to Get Just the Current Date in SQL Server
The functions above show the current date and time.
But what if you only want to get the current date, and not the time?
There are two ways you can do that: use CAST or use CONVERT.
I’ve written about this method in a recent post: How to Convert DATETIME to DATE in SQL Server.
Here’s an example:
Result:
date_cast | date_convert |
2020-07-15 | 2020-07-15 |
Both methods return the same value.
ADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days)
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD().
mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY); +---------------------------------------------------------+ | ADDDATE('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr.
mysql> SELECT ADDDATE('1998-01-02', 31); +---------------------------------------------------------+ | DATE_ADD('1998-01-02', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 1998-02-02 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
PostgreSQL
To get the current date in PostgreSQL, we can use one of several functions:
Function | Returns |
CURRENT_DATE | Current date and time |
CURRENT_TIMESTAMP | Current date and time with timezone |
LOCALTIMESTAMP | Current date and time |
NOW | Current date and time, same as CURRENT_TIMESTAMP |
The return values of these functions look like this:
Results:
Function | Result |
CURRENT_DATE | 2020-07-16 |
CURRENT_TIMESTAMP | 2020-07-16 05:19:32.201578 EDT |
LOCALTIMESTAMP | 2020-07-16 05:19:32 |
NOW | 2020-07-16 05:19:32.201578 EDT |
We can see that CURRENT_DATE shows only the date, but CURRENT_TIMESTAMP and LOCALTIMESTAMP show the date and time.
What’s the Difference Between CURRENT_TIMESTAMP and LOCALTIMESTAMP in PostgreSQL?
The difference is that LOCALTIMESTAMP returns a timestamp without a timezone, and CURRENT_TIMESTAMP returns a timestamp with a timezone.
Создание полей даты и времени
Таблица, содержащая типы данных DATE и DATETIME, создается так же, как и другие столбцы. Например, мы можем создать новую таблицу под названием orders, которая содержит столбцы номера заказа, заказанного товара, даты заказа и даты доставки заказа:
CREATE TABLE `MySampleDB`.`orders` ( `order_no` INT NOT NULL AUTO_INCREMENT, `order_item` TEXT NOT NULL, `order_date` DATETIME NOT NULL, `order_delivery` DATE NOT NULL, PRIMARY KEY (`order_no`) ) ENGINE = InnoDB;
Столбец ORDER_DATE — это поле типа MySQL DATE TIME, в которое мы записываем дату и время, когда был сделан заказ. Для даты доставки невозможно предсказать точное время, поэтому мы записываем только дату.
SQL Справочник
SQL Ключевые слова
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE
MySQL Функции
Функции строк
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Функции дат
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Функции расширений
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION
SQL Server функции
Функции строк
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Функции дат
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Функции расширений
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME
MS Access функции
Функции строк
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Функции чисел
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Функции дат
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Другие функции
CurrentUser
Environ
IsDate
IsNull
IsNumeric
SQL ОператорыSQL Типы данныхSQL Краткий справочник
Извлечение данных по дате и времени
В MySQL мы можем отфильтровать извлеченные данные в зависимости от даты и времени. Например, мы можем извлечь только те заказы, доставка которых запланирована на ноябрь:
mysql> SELECT * FROM orders WHERE MONTHNAME(order_delivery) = 'November'; +----------+------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+------------+---------------------+----------------+ | 1 | iPhone 8Gb | 2007-10-23 11:37:55 | 2007-11-06 | +----------+------------+---------------------+----------------+ 1 row in set (0.00 sec)
Точно так же мы можем использовать BETWEEN, чтобы выбрать товары, доставка которых произойдет между двумя указанными датами. Например:
mysql> SELECT * FROM orders WHERE order_delivery BETWEEN '2007-12-01' AND '2008-01-01'; +----------+----------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+----------------+---------------------+----------------+ | 2 | ipod Touch 4Gb | 2007-10-23 11:51:09 | 2007-12-23 | +----------+----------------+---------------------+----------------+ 1 row in set (0.03 sec)
CURTIME()
Returns the current time as a value in ‘HH:MM:SS’ or HHMMSS format, depending on whether the function is used in a string or in a numeric context. The value is expressed in the current time zone.
mysql> SELECT CURTIME(); +---------------------------------------------------------+ | CURTIME() | +---------------------------------------------------------+ | 23:50:26 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CURTIME() + 0; +---------------------------------------------------------+ | CURTIME() + 0 | +---------------------------------------------------------+ | 235026 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
SQL Справочник
SQL Ключевые слова
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE
MySQL Функции
Функции строк
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Функции дат
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Функции расширений
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION
SQL Server функции
Функции строк
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Функции дат
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Функции расширений
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME
MS Access функции
Функции строк
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Функции чисел
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Функции дат
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Другие функции
CurrentUser
Environ
IsDate
IsNull
IsNumeric
SQL ОператорыSQL Типы данныхSQL Краткий справочник
Oracle
There are a few ways to get the current date in Oracle SQL.
Function | Data Type | Returns |
SYSDATE | date | Current date and time of the server |
CURRENT_DATE | date | Current date and time in the session time zone |
CURRENT_TIMESTAMP | timestamp with time zone | Current date and time with time zone in the session time zone |
LOCALTIMESTAMP | timestamp | Current date and time in the session time zone |
SYSTIMESTAMP | timestamp with time zone | Current date and time of the server |
The method you use depends on which data type you want and whether you want the server or session time zone.
Let’s see some examples of these functions.
The results are below (translated to rows to make it easier to compare):
Function | Result |
SYSDATE | 15-JUL-20 |
CURRENT_DATE | 15-JUL-20 |
CURRENT_TIMESTAMP | 15-JUL-20 12.08.25.095819 AM US/PACIFIC |
LOCALTIMESTAMP | 15-JUL-20 12.08.25.095819 AM |
SYSTIMESTAMP | 15-JUL-20 07.08.25.095818 AM +00:00 |
We can see a few things here:
- SYSDATE and CURRENT_DATE show a similar output.
- CURRENT_TIMESTAMP and LOCALTIMESTAMP show the same value but one is with the timezone and one is without.
One thing to be aware of is that even though SYSDATE and CURRENT_DATE display the date here, they actually include the time.
To see the time component, we can use TO_CHAR, which shows the difference between the two functions:
Operation | Result |
SYSDATE | 15-JUL-20 |
SYSDATE_FULL | 2020-07-15 06:51:58 |
CURRENT_DATE | 15-JUL-20 |
CURRENT_DATE_FULL | 2020-07-15 11:51:58 |
We can see that both dates are the same, but the times are different.
What’s the Difference Between SYSDATE and CURRENT_DATE in Oracle?
These two functions look like they show the same thing. So how are they different?
SYSDATE is based on the server, and CURRENT_DATE is based on the user’s session.
This means if the user is based in New York and the database server is in London, the SYSDATE function will return the London date and time, and the CURRENT_DATE function will return the New York date and time.
SQL References
SQL Keywords
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE
MySQL Functions
String Functions
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Numeric Functions
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Date Functions
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Advanced Functions
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION
SQL Server Functions
String Functions
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Numeric Functions
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Date Functions
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Advanced Functions
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME
MS Access Functions
String Functions
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Numeric Functions
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Date Functions
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Other Functions
CurrentUser
Environ
IsDate
IsNull
IsNumeric
SQL Quick Ref
Пример
Рассмотрим примеры MySQL функции DATE_FORMAT, чтобы понять, как использовать функцию DATE_FORMAT в MySQL.
Например:
MySQL
mysql> SELECT DATE_FORMAT(‘2014-11-28’, ‘%Y’);
#Результат: 2014
mysql> SELECT DATE_FORMAT(‘2014-11-01’, ‘%M %d, %Y’);
#Результат: November 01, 2014
mysql> SELECT DATE_FORMAT(‘2014-11-01’, ‘%M %e %Y’);
#Результат: November 1 2014
mysql> SELECT DATE_FORMAT(‘2014-11-28’, ‘%W, %M %e, %Y’);
#Результат: Friday, November 28, 2014
mysql> SELECT DATE_FORMAT(‘2014-11-28’, ‘%W’);
#Результат: Friday
1 |
mysql>SELECTDATE_FORMAT(‘2014-11-28′,’%Y’); #Результат: 2014 mysql>SELECTDATE_FORMAT(‘2014-11-01′,’%M %d, %Y’); #Результат: November 01, 2014 mysql>SELECTDATE_FORMAT(‘2014-11-01′,’%M %e %Y’); #Результат: November 1 2014 mysql>SELECTDATE_FORMAT(‘2014-11-28′,’%W, %M %e, %Y’); #Результат: Friday, November 28, 2014 mysql>SELECTDATE_FORMAT(‘2014-11-28′,’%W’); #Результат: Friday |