Alt sorgu ve CTE ile birleştirmeler
En uygun sorgu yapısı için alt sorguları, Ortak Tablo İfadelerini (CTE'ler) ve birleştirmeleri karşılaştırın.
Alt sorgu ve CTE ile birleştirmeler, CoddyKit'te ücretsiz bir PostgreSQL Performance & Query Optimization dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, PostgreSQL Performance & Query Optimization öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
Welcome to Query Construction
In this lesson, we'll explore three fundamental ways to combine and structure data in PostgreSQL: Subqueries, Common Table Expressions (CTEs), and Joins.
Understanding their differences and optimal use cases is key to writing efficient and readable SQL.
Joins: The Foundation
You're already familiar with JOINs! They are the primary way to combine rows from two or more tables based on a related column between them.
- Purpose: Link related data across tables.
- Readability: Often straightforward for direct relationships.
- Performance: Highly optimized by PostgreSQL for combining large datasets.
What are Subqueries?
A subquery (or inner query) is a query nested inside another SQL query. It can return a single value (scalar), a single row, a single column, or a table.
- Placement: In
SELECT,FROM,WHERE, orHAVINGclauses. - Use Cases: Filtering with
IN/EXISTS, calculating aggregate values for comparison, or providing derived tables.
Subquery in Action
Here's a simple example where a subquery helps find products with prices above the average. Notice how the inner query runs first.
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(50),
price DECIMAL(10, 2)
);
INSERT INTO products (product_name, price) VALUES
('Laptop', 1200.00),
('Mouse', 25.00),
('Keyboard', 75.00),
('Monitor', 300.00),
('Webcam', 50.00);
SELECT product_name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);
DROP TABLE products;What are CTEs?
A Common Table Expression (CTE), defined with the WITH clause, creates a temporary, named result set that you can reference within a single SQL statement.
- Purpose: Improve readability, organize complex queries, and enable recursion.
- Scope: Only available for the query immediately following the
WITHclause. - Readability: Breaks down complex logic into logical, readable steps.
CTE in Action
Let's rewrite the previous example using a CTE. Notice how it defines "average_price" first, making the main query clearer.
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(50),
price DECIMAL(10, 2)
);
INSERT INTO products (product_name, price) VALUES
('Laptop', 1200.00),
('Mouse', 25.00),
('Keyboard', 75.00),
('Monitor', 300.00),
('Webcam', 50.00);
WITH AverageProductPrice AS (
SELECT AVG(price) AS avg_price
FROM products
)
SELECT p.product_name, p.price
FROM products p, AverageProductPrice app
WHERE p.price > app.avg_price;
DROP TABLE products;Choosing Joins
JOINs are your go-to when you need to combine data from different tables that have a direct, logical relationship.
- Direct Relationships: When tables are linked by foreign keys.
- Performance: Highly optimized by the planner for combining large datasets efficiently.
- Result Set: Creates a single, wider result set from matching rows.
They are often the most performant for combining large tables.
Choosing Subqueries
Subqueries are useful for specific filtering or calculating values that depend on the main query's data, often acting as a single value or a list.
- Scalar Values: When you need a single value (e.g.,
WHERE price > (SELECT AVG(price))). - Filtering: With
IN,NOT IN,EXISTS,NOT EXISTSclauses. - Derived Tables: In the
FROMclause for temporary, unnamed result sets.
They can sometimes be less readable for complex logic.
Choosing CTEs
CTEs excel when you need to break down complex queries into logical, readable steps or handle recursive data structures.
- Readability: Improves understanding of multi-step logic.
- Recursion: Essential for querying hierarchical or graph-like data.
- Reusability: A CTE can be referenced multiple times within the same main query.
They are often preferred over complex subqueries for clarity.
Performance: It's Complicated!
Often, a query written with a subquery can be rewritten as a JOIN or a CTE, and vice-versa. PostgreSQL's optimizer is smart!
- Optimizer Role: It often transforms these constructs internally into the most efficient execution plan.
- Readability First: Prioritize clear, maintainable code.
EXPLAIN ANALYZE: Always use it to truly understand the performance impact of your chosen approach, rather than guessing.
Compare & Contrast
Consider the following scenarios. Which SQL construct is generally the most suitable choice for each?
Recap: Constructing Optimal Queries
You've learned to differentiate between JOINs, Subqueries, and CTEs:
- JOINs: Best for direct table relationships and combining large datasets.
- Subqueries: Ideal for scalar values,
IN/EXISTSfiltering, and derived tables. - CTEs: Shine for readability, multi-step logic, and recursive queries.
Remember to prioritize readability and use EXPLAIN ANALYZE to confirm performance!
Sıkça Sorulan Sorular
“Alt sorgu ve CTE ile birleştirmeler” dersi ücretsiz mi?
Evet — “Alt sorgu ve CTE ile birleştirmeler” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve PostgreSQL Performance & Query Optimization kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.
“Alt sorgu ve CTE ile birleştirmeler” dersinde ne öğreneceğim?
En uygun sorgu yapısı için alt sorguları, Ortak Tablo İfadelerini (CTE'ler) ve birleştirmeleri karşılaştırın. PostgreSQL Performance & Query Optimization ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
PostgreSQL Performance & Query Optimization öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te PostgreSQL Performance & Query Optimization, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.
“Alt sorgu ve CTE ile birleştirmeler” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu PostgreSQL Performance & Query Optimization dersinde kod yazıp çalıştırabilir miyim?
Evet. Her PostgreSQL Performance & Query Optimization dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Birleştirme algoritmalarını anlama
- Karmaşık birleştirmeleri yeniden yazma
- Alt sorgu ve CTE ile birleştirmeler
- LATERAL Birleştirmelerini ve İlişkili Aramaları İyileştirme