목차
2. Common Date Functions
Extract parts of a date
Get current date and time
Format dates
3. Date Arithmetic and Comparisons
Add or subtract days/months
Filter by date ranges
Days between two dates
4. Handling Time Zones (Advanced)
Key Tips:
데이터 베이스 SQL SQL의 날짜와 함께 일하는 방법?

SQL의 날짜와 함께 일하는 방법?

Aug 18, 2025 am 10:01 AM

<p>使用标准日期类型(如DATE、DATETIME)存储日期,确保格式为YYYY-MM-DD以避免歧义;2. 常用日期函数包括提取年月日(YEAR/MONTH/DAY或EXTRACT)、获取当前时间(NOW/CURRENT_DATE)和格式化输出(DATE_FORMAT/TO_CHAR/FORMAT);3. 通过DATE_ADD/DATE_SUB、日期加减 INTERVAL 或 DATEADD 进行日期运算,使用 >= 与 < 或 BETWEEN 过滤日期范围,利用 DATEDIFF 或日期相减计算天数差;4. 处理时区时应使用带时区的数据类型(如TIMESTAMP WITH TIME ZONE),并通过 AT TIME ZONE 或等效函数转换时区,确保跨时区比较时标准化时间。始终在日期列上建立索引并验证输入以保证查询效率和数据准确。</p> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175548248444420.jpeg" class="lazy" alt="How to work with dates in SQL?"></p> <p>Working with dates in SQL is essential for querying and analyzing time-based data. Different databases (like MySQL, PostgreSQL, SQL Server, etc.) have slightly different syntax, but the core concepts are similar. Here’s a practical guide to help you handle dates effectively.</p> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175548248539757.jpeg" class="lazy" alt="How to work with dates in SQL?"><hr> <h3>1. <strong>Storing and Formatting Dates</strong> </h3> <p>Most databases support common date/time data types:</p> <ul> <li> <code>DATE</code> – stores date only (e.g., <code>2024-05-20</code>)</li> <li> <code>DATETIME</code> or <code>TIMESTAMP</code> – stores date and time (e.g., <code>2024-05-20 14:30:00</code>)</li> <li> <code>TIME</code> – stores time only</li> <li> <code>YEAR</code> – stores year (in MySQL)</li> </ul> <p>Always store dates in standard formats (preferably ISO: <code>YYYY-MM-DD</code>) to avoid ambiguity.</p> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175548248628588.jpeg" class="lazy" alt="How to work with dates in SQL?"><p><strong>Example:</strong></p><pre class='brush:php;toolbar:false;'>CREATE TABLE events ( id INT, event_name VARCHAR(100), event_date DATE );</pre><p>Insert a date:</p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175548248725337.jpeg" class="lazy" alt="How to work with dates in SQL?" /><pre class='brush:php;toolbar:false;'>INSERT INTO events VALUES (1, 'Meeting', '2024-05-20');</pre><hr /><h3 id="strong-Common-Date-Functions-strong">2. <strong>Common Date Functions</strong></h3><p>Here are widely used functions across databases (with slight variations):</p><h4 id="Extract-parts-of-a-date">Extract parts of a date</h4><p>Get year, month, day, etc., from a date.</p><pre class='brush:php;toolbar:false;'>-- MySQL / PostgreSQL SELECT YEAR(event_date) AS year, MONTH(event_date) AS month, DAY(event_date) AS day FROM events;</pre><p>In PostgreSQL, use <code>EXTRACT</code>:</p><pre class='brush:php;toolbar:false;'>SELECT EXTRACT(YEAR FROM event_date) AS year, EXTRACT(MONTH FROM event_date) AS month FROM events;</pre><h4 id="Get-current-date-and-time">Get current date and time</h4><pre class='brush:php;toolbar:false;'>-- MySQL SELECT NOW(); -- date and time SELECT CURDATE(); -- date only -- PostgreSQL SELECT NOW(); -- date and time SELECT CURRENT_DATE; -- date only -- SQL Server SELECT GETDATE(); -- date and time SELECT CAST(GETDATE() AS DATE); -- date only</pre><h4 id="Format-dates">Format dates</h4><p>Convert a date to a custom string format.</p><pre class='brush:php;toolbar:false;'>-- MySQL SELECT DATE_FORMAT(event_date, '%M %d, %Y') FROM events; -- Result: May 20, 2024 -- PostgreSQL SELECT TO_CHAR(event_date, 'FMMonth DD, YYYY') FROM events; -- SQL Server SELECT FORMAT(event_date, 'MMMM dd, yyyy') FROM events;</pre><hr /><h3 id="strong-Date-Arithmetic-and-Comparisons-strong">3. <strong>Date Arithmetic and Comparisons</strong></h3><p>You’ll often need to add or subtract time, or filter by date ranges.</p><h4 id="Add-or-subtract-days-months">Add or subtract days/months</h4><pre class='brush:php;toolbar:false;'>-- MySQL SELECT DATE_ADD(event_date, INTERVAL 7 DAY) FROM events; SELECT DATE_SUB(event_date, INTERVAL 1 MONTH) FROM events; -- PostgreSQL SELECT event_date + INTERVAL '7 days' FROM events; SELECT event_date - INTERVAL '1 month' FROM events; -- SQL Server SELECT DATEADD(day, 7, event_date) FROM events; SELECT DATEADD(month, -1, event_date) FROM events;</pre><h4 id="Filter-by-date-ranges">Filter by date ranges</h4><pre class='brush:php;toolbar:false;'>-- Events in May 2024 SELECT * FROM events WHERE event_date >= '2024-05-01' AND event_date < '2024-06-01'; -- Or using BETWEEN (inclusive) SELECT * FROM events WHERE event_date BETWEEN '2024-05-01' AND '2024-05-31';</pre><p>Use <code>>=</code> and <code><</code> for time precision when including timestamps.</p><h4 id="Days-between-two-dates">Days between two dates</h4><pre class='brush:php;toolbar:false;'>-- MySQL SELECT DATEDIFF('2024-05-30', '2024-05-20'); -- 10 days -- PostgreSQL SELECT ('2024-05-30'::date - '2024-05-20'::date); -- 10 -- SQL Server SELECT DATEDIFF(day, '2024-05-20', '2024-05-30');</pre><hr /><h3 id="strong-Handling-Time-Zones-Advanced-strong">4. <strong>Handling Time Zones (Advanced)</strong></h3><p>Some databases support time zone-aware types like <code>TIMESTAMP WITH TIME ZONE</code> (PostgreSQL) or <code>DATETIMEOFFSET</code> (SQL Server).</p><pre class='brush:php;toolbar:false;'>-- PostgreSQL SELECT NOW() AT TIME ZONE 'UTC'; SELECT NOW() AT TIME ZONE 'America/New_York';</pre><p>Be cautious when comparing timestamps across time zones—always standardize if needed.</p> <hr> <h3 id="Key-Tips">Key Tips:</h3> <ul> <li>Always use proper date types instead of strings.</li> <li>Be consistent with time zones in applications.</li> <li>Use indexes on date columns for faster queries.</li> <li>Validate input dates to avoid errors.</li> </ul> <hr> <p>Working with dates doesn’t have to be hard—once you know the right functions and patterns, filtering, formatting, and calculating time intervals becomes straightforward. Just remember to check your specific database’s documentation for syntax differences.</p>

위 내용은 SQL의 날짜와 함께 일하는 방법?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Stock Market GPT

Stock Market GPT

더 현명한 결정을 위한 AI 기반 투자 연구

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제

열을 SQL의 여러 값과 비교하는 방법은 무엇입니까? 열을 SQL의 여러 값과 비교하는 방법은 무엇입니까? Sep 16, 2025 am 02:12 AM

IN 연산자를 사용하여 열을 선택*Fromployeeswheredepartment_idin (1,2,3)과 같은 여러 값과 효율적으로 비교하십시오. 여러 값이 제외되면 NOTIN을 사용하지만 결과에 영향을 미치는 NULL에주의하십시오.

SQL의 서브 쿼리와 CTE의 차이점은 무엇입니까? SQL의 서브 쿼리와 CTE의 차이점은 무엇입니까? Sep 16, 2025 am 07:47 AM

하위 쿼리는 다른 쿼리에 중첩 된 쿼리입니다. 그들은 간단한 일회성 계산에 적합하며, 선택,에서 또는 시점에 위치 할 수 있습니다. 2. CTE는 복잡한 쿼리의 가독성을 향상시키고 재귀 및 다중 참조를 지원하기 위해 조항으로 정의됩니다. 3. 하위 쿼리는 단일 사용에 적합하며 CTE는 명확한 구조, 재사용 또는 재귀가 필요한 시나리오에 더 적합합니다.

SQL에서 음성 검색에 Soundex 기능을 사용하는 방법은 무엇입니까? SQL에서 음성 검색에 Soundex 기능을 사용하는 방법은 무엇입니까? Sep 21, 2025 am 01:54 AM

SoundEx 함수는 텍스트를 발음을 나타내는 4 자리 코드로 변환하고 첫 번째 문자에 3 자리를 추가하고 모음과 특정 문자를 무시하며, 유사한 발음을 가진 자음을 동일한 숫자로 맵핑하여 발음 기반 검색을 실현합니다. 예를 들어, Smith와 Smythe는 모두 S530을 생성하고 유사한 발음을 가진 이름은 Wheresoundex (last_name) = soundex ( 'Smith')를 통해 찾을 수 있습니다. 차이 함수와 결합하여 유사성 점수 0에서 4의 유사성 점수를 반환하고, 발음 닫기 결과를 필터링 할 수 있으며, 이는 철자 차이를 다루는 데 적합하지만 영어 이외의 이름에 영향을 미치며 성능 최적화에주의를 기울여야합니다.

SQL의 테이블 또는 열에 주석을 추가하는 방법은 무엇입니까? SQL의 테이블 또는 열에 주석을 추가하는 방법은 무엇입니까? Sep 21, 2025 am 05:22 AM

UseCommentOncolumnoraltertablewithCommentTodocumentTables 및 ColumnsInsql; syntaxvariesBydbms - postgresqlandoracleUsecommenton, mysqlusescommentincreate/alterstatements 및 andcommentscanbeviewedviasystemtablikedinformation_schema, rantsuppport.

SQL에서 마지막 삽입 ID를 얻는 방법은 무엇입니까? SQL에서 마지막 삽입 ID를 얻는 방법은 무엇입니까? Sep 20, 2025 am 04:40 AM

TogetThelastInsertedid, usedatabase-specificftions : mysqluseslast_insert_id (), postgresqlusesreturningclause, sqlserverusesscope_identity () oroutput, andsqliteuseslast_insert_rowid (); 항상 callcrightrightterafttoccuracy.

SQL 테이블에서 고아 기록을 찾는 방법은 무엇입니까? SQL 테이블에서 고아 기록을 찾는 방법은 무엇입니까? Sep 17, 2025 am 04:51 AM

tofindorphaneDrecords, usealeftjoinornoTexoTexistStoIndItifyHildRecordsWithOutmatchingParentRecords.forexample, selecto, formorderSoleftJoincustomerscono.customer_id = c.customer_idwherec.customer_idullesturnsorderdonon-allinternon-allernon-allernon-allernon-allernon-allistomer

SQL에서 데이터베이스의 이름을 바꾸는 방법 SQL에서 데이터베이스의 이름을 바꾸는 방법 Sep 17, 2025 am 06:11 AM

insqlserver, insqlserver, usealterdatabasewithmodifynifyjectingsingsetingsingsingsingsingsingsingsingsingsingsingsingsingsingsingsingsingle-usermode; inmysql, nodirectrenameisavailable, socreateanewdatabase, copydataviamysqldumporrenametable, thendroptheoldone; Inpostgresgresgresgresgresgresgresgresgresgresgresggresgresgresgresgresgres

SQL에서 비 equi 조인을 수행하는 방법은 무엇입니까? SQL에서 비 equi 조인을 수행하는 방법은 무엇입니까? Sep 16, 2025 am 07:37 AM

anon-equijoinusescopisonoperators winder ween, or! =, 또는! = tomatchrowsbetweentables.2.plisuseFulforRangeComparisonSsuchassalaryordateranges.3.syntaxinvolvesspecifingConditionSintheonTheconconditionSinTheonConconconditionSinTheonConconConditionSinTheonforSalargrades.4

See all articles