🧚 주목! Beekeeper Studio는 빠르고 현대적이며 오픈 소스 데이터베이스 GUI입니다 다운로드
February 19, 2024 작성자: Matthew Rathbone

Introduction

When working with SQL databases, including PostgreSQL, manipulating and querying date and time data is a fundamental skill. Often, applications require analysis or reporting that focuses on weekdays, excluding weekends. This tutorial will dive into how to select records based on weekdays only, utilizing PostgreSQL’s date and time functions.

Understanding Date and Time in PostgreSQL

PostgreSQL offers a comprehensive set of functions and operators to work with dates and times, making it straightforward to perform complex queries, such as selecting rows based on weekdays.

Date/Time Data Types

Before diving into querying weekdays, it’s helpful to understand the primary date/time data types in PostgreSQL:

  • DATE: For dates (year, month, day).
  • TIMESTAMP: For date and time, without time zone.
  • TIMESTAMPTZ: For date and time, with time zone.
  • TIME: For time only, without time zone.
  • TIMETZ: For time only, with time zone.

The EXTRACT Function

One key function for working with weekdays is EXTRACT. It allows you to extract parts of a date/time value, such as the day of the week.

Querying Weekdays Only

To select records that fall on weekdays (Monday to Friday), you can use the EXTRACT function to get the day of the week from a date, where Sunday is 0 and Saturday is 6.

Basic Weekday Selection

Here’s how you can filter rows to include only weekdays:

-- Assuming a table 'events' with a 'date' column
SELECT *
FROM events
WHERE EXTRACT(DOW FROM date) BETWEEN 1 AND 5;

This query selects rows from the events table where the day of the week of the date column is between 1 (Monday) and 5 (Friday), inclusive.

Output:

id date event_name
1 2024-03-04 Project Launch
2 2024-03-05 Team Meeting

Complex Scenarios: Joining Tables and Filtering by Weekdays

Let’s consider a more complex example where you need to join tables and still filter by weekdays.

-- Assuming another table 'event_details' that references 'events'
SELECT e.*, ed.detail
FROM events e
JOIN event_details ed ON e.id = ed.event_id
WHERE EXTRACT(DOW FROM e.date) BETWEEN 1 AND 5;

This query not only filters the events by weekdays but also joins with the event_details table to fetch related data.

Output:

id date event_name detail
1 2024-03-04 Project Launch Kick-off meeting
2 2024-03-05 Team Meeting Monthly review

Use Cases

Analyzing Work Hours

For businesses tracking work hours, filtering out weekends can provide insights into productivity and labor costs.

-- Assuming a table 'work_hours' with 'employee_id', 'date', and 'hours_worked'
SELECT employee_id, SUM(hours_worked) AS total_hours
FROM work_hours
WHERE EXTRACT(DOW FROM date) BETWEEN 1 AND 5
GROUP BY employee_id;

This query calculates the total hours worked by each employee during weekdays.

Output:

employee_id total_hours
101 40
102 38

Event Planning

For event planners, focusing on weekdays can help in organizing and scheduling events more efficiently.

-- Finding available event dates during weekdays
SELECT date
FROM events
WHERE EXTRACT(DOW FROM date) BETWEEN 1 AND 5
AND date > CURRENT_DATE
ORDER BY date;

This helps in identifying upcoming weekday dates for planning future events.

Output:

date
2024-03-06
2024-03-07

Conclusion

Selecting records based on weekdays in PostgreSQL is a useful technique for data analysis and application logic. By leveraging PostgreSQL’s date and time functions, especially EXTRACT, you can easily filter data to meet your specific requirements. Whether you’re analyzing business operations, planning events, or simply managing schedules, understanding how to query weekdays will enhance your database skill set.

Practice with these examples, explore PostgreSQL’s documentation for more date/time functions, and get more insights from your data.

Happy querying!

Beekeeper Studio는 무료 & 오픈 소스 데이터베이스 GUI입니다

제가 사용해 본 최고의 SQL 쿼리 & 편집기 도구입니다. 데이터베이스 관리에 필요한 모든 것을 제공합니다. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio는 빠르고 직관적이며 사용하기 쉽습니다. Beekeeper는 많은 데이터베이스를 지원하며 Windows, Mac, Linux에서 훌륭하게 작동합니다.

Beekeeper의 Linux 버전은 100% 완전한 기능을 갖추고 있으며, 기능 타협이 없습니다.

사용자들이 Beekeeper Studio에 대해 말하는 것

★★★★★
"Beekeeper Studio는 제 예전 SQL 워크플로를 완전히 대체했습니다. 빠르고 직관적이며 데이터베이스 작업을 다시 즐겁게 만들어 줍니다."
— Alex K., 데이터베이스 개발자
★★★★★
"많은 데이터베이스 GUI를 사용해 봤지만, Beekeeper는 기능과 단순함 사이의 완벽한 균형을 찾았습니다. 그냥 작동합니다."
— Sarah M., 풀스택 엔지니어

SQL 워크플로를 개선할 준비가 되셨나요?

download 무료 다운로드