🗄️ Databases

Query

Query

A command that requests information from a database. SQL SELECT is the best-known example. Query optimization is key to performance.

📖 Detailed Explanation

A query is a command that requests information from a database. Using SQL (Structured Query Language), you can retrieve (SELECT), insert (INSERT), update (UPDATE), and delete (DELETE) data. Writing efficient queries is key to application performance.

The SELECT query is the most commonly used type and consists of the FROM, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT clauses. Each clause is executed in a set order, and understanding this lets you analyze even complex queries logically.

Query optimization starts with analyzing the Execution Plan (EXPLAIN). Check whether indexes are used, the join method, the estimated number of rows, and so on, and if necessary, improve performance by adding indexes or rewriting the query. In general, avoid Full Table Scan and make use of indexes.

A parameterized query (Prepared Statement) prevents SQL injection and enables query caching. Even when generating queries dynamically, you must always use parameter binding.

💻 Code Example

-- 기본 SELECT
SELECT id, name, email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 10;

-- 집계 함수와 GROUP BY
SELECT category, COUNT(*) as count, AVG(price) as avg_price
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

-- CTE (Common Table Expression)
WITH monthly_sales AS (
    SELECT DATE_TRUNC('month', order_date) as month,
           SUM(total) as revenue
    FROM orders
    GROUP BY 1
)
SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) as growth
FROM monthly_sales;

-- 서브쿼리
SELECT * FROM products
WHERE price > (SELECT AVG(price) FROM products);

-- UPSERT (있으면 업데이트, 없으면 삽입)
INSERT INTO users (email, name)
VALUES ('test@example.com', 'Test')
ON DUPLICATE KEY UPDATE name = VALUES(name);

-- Python에서 파라미터화된 쿼리
cursor.execute(
    "SELECT * FROM users WHERE email = %s AND status = %s",
    (email, 'active')  # SQL 인젝션 방지
)

🗣️ Examples of Practical Conversations

Senior: This query takes 3 seconds in production. Was it fast locally?

Junior: Yes, it was fast because there was little data. How do I optimize it?

Senior: Check the actual execution time with EXPLAIN ANALYZE. You can find the join order or missing indexes.

Interviewer: Please explain the execution order of a SELECT query.

Candidate: FROM and JOIN are executed first to determine the data source, and WHERE filters it. Next, GROUP BY groups the rows and HAVING filters the groups. SELECT chooses the columns, ORDER BY sorts them, and then LIMIT restricts the number of rows.

Interviewer: What are the advantages of a parameterized query?

Candidate: It fundamentally blocks SQL injection attacks, and performance improves because the DB can cache the query plan. You must not build queries by string concatenation.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer: It's better to avoid SELECT *. Specify only the columns you need.

Author: I used * for convenience, so why is it a problem?

Reviewer: It causes unnecessary data transfer, makes it impossible to use a covering index, and has unexpected effects when the schema changes.

⚠️ Cautions

🔗 Related Terms

📚 Learn More