markdown
SQL の基本md eb2aeb2
lecture/information/database/sql-basics.lecture.n.md
Download PDF

SQL の基本きほん

date2026-07-14document_iddoc_d0ef3cd6db05369d421cd6e8e99cef4fdescriptionSQLの宣言的な問い合わせ、NULLと三値論理、結合、更新、制約、トランザクション、安全なパラメータ処理を説明する。prerequisitesデータベースの基本type講義statusactiverelateddata/lecture/information/database/database-portal.lecture.n.md / data/lecture/information/database/database-basics.lecture.n.md / data/lecture/information/software-engineering/software-engineering-portal.lecture.n.md
informationdatabaseundergraduatelecture
data/lecture/information/database/database-basics.lecture.n.md

1導入どうにゅう

この講義こうぎでは、関係かんけいデータベースに対たいする問とい合あわせと更新こうしんを宣言的せんげんてきに記述きじゅつする SQLStructured Query Language の基本きほんを説明せつめいする。前講義ぜんこうぎで導入どうにゅうした表ひょう、行ぎょう、列れつ、主しゅキー、外部がいぶキーを、SQL の構文こうぶんと対応たいおうさせる。

SQL は、データへ到達とうたつする手順てじゅんではなく、必要ひつような結果けっかの条件じょうけんを記述きじゅつする。索引さくいんの利用りようや結合順序けつごうじゅんじょなどの実行計画じっこうけいかくは、通常つうじょう、データベース管理かんりシステムが決定けっていする。この宣言性せんげんせいにより、論理的ろんりてきな問とい合あわせと物理的ぶつりてきな実行方法じっこうほうほうを分離ぶんりできる。

2SELECT、FROM、WHERE

基本的きほんてきな問とい合あわせは、SELECT、FROM、WHERE の三要素さんようそから構成こうせいされる。

  • FROM は、問とい合あわせの対象たいしょうとなる表ひょうを指定していする。
  • WHERE は、各行かくぎょうを条件式じょうけんしきによって選択せんたくする。この操作そうさを選択せんたくSelectionまたはフィルタリングという。
  • SELECT は、結果けっかに含ふくめる列れつまたは式しきを指定していし、概おおむね射影しゃえいProjectionに対応たいおうする。ただし、SQLは既定きていで重複行ちょうふくぎょうを保持ほじし、SELECT DISTINCTを指定していした場合ばあいに重複ちょうふくを除去じょきょする。これは関係代数かんけいだいすうの集合しゅうごうとしての射影しゃえいとの相違そういである。

論理的ろんりてきには FROM で対象たいしょうを定さだめ、WHERE で行ぎょうを選択せんたくし、SELECT で列れつを射影しゃえいすると解釈かいしゃくできる。これは概念上がいねんじょうの役割やくわりであり、データベース管理かんりシステムがこの順序じゅんじょで物理的ぶつりてきに処理しょりするとは限かぎらない。

sql
SELECT student_id, name
FROM students
WHERE department = 'Computer Science';

この問とい合あわせは、students 表ひょうから所属しょぞくが Computer Science である行ぎょうを選択せんたくし、その student_id と name を結果列けっかれつとして指定していする。重複行ちょうふくぎょうはDISTINCTを指定していしない限かぎり保持ほじされる。

3結果けっかの順序じゅんじょ

SQL の問とい合あわせ結果けっかには、ORDER BY を指定していしない限かぎり順序じゅんじょの保証ほしょうがない。同一どういつの問とい合あわせでも、実行計画じっこうけいかくやデータの配置はいちによって表示順ひょうじじゅんが変化へんかし得うる。

sql
SELECT student_id, name
FROM students
ORDER BY student_id ASC;

再現可能さいげんかのうな順序じゅんじょが必要ひつような場合ばあいは、同順位どうじゅんいを解消かいしょうできる列れつまで ORDER BY に指定していする。

4NULL と三値論理さんちろんり

NULL は、値あたいが存在そんざいしない、または不明ふめいであることを表あらわす標識ひょうしきであり、空文字列からもじれつや数値すうちの 0 ではない。NULL を含ふくむ通常つうじょうの比較ひかくは、TRUE または FALSE ではなく UNKNOWN となる。SQL の条件式じょうけんしきは、この三値論理さんちろんりThree-valued logicに従したがう。

WHERE が結果けっかに残のこすのは、条件式じょうけんしきが TRUE となる行ぎょうだけである。FALSE と UNKNOWN の行ぎょうは除外じょがいされる。したがって、NULL の検査けんさには = NULL ではなく IS NULL または IS NOT NULL を使用しようする。

sql
SELECT student_id, name
FROM students
WHERE email IS NULL;

5JOIN とキー

別々べつべつの表ひょうに格納かくのうされた関連かんれんデータは、JOIN によって結合けつごうできる。例れいとして、students.student_id を主しゅキー、enrollments.student_id をそれを参照さんしょうする外部がいぶキーとする。

sql
SELECT s.student_id, s.name, e.course_id
FROM students AS s
JOIN enrollments AS e
  ON e.student_id = s.student_id
WHERE e.status = 'enrolled';

ON は二ふたつの表ひょうの行ぎょうを対応たいおうさせる結合条件けつごうじょうけんを指定していする。主しゅキーの一意性いちいせいと外部がいぶキーの参照整合性さんしょうせいごうせいにより、この対応関係たいおうかんけいをデータベース側がわで検証けんしょうできる。ただし、JOIN 自体じたいは外部がいぶキーが宣言せんげんされていなくても実行可能じっこうかのうである。

6更新こうしん、制約せいやく、トランザクション

SQL は、INSERT で行ぎょうを追加ついかし、UPDATE で既存行きそんぎょうを変更へんこうし、DELETE で行ぎょうを削除さくじょする。

sql
INSERT INTO enrollments (student_id, course_id, status)
VALUES (1001, 'CS101', 'enrolled');

UPDATE enrollments
SET status = 'completed'
WHERE student_id = 1001 AND course_id = 'CS101';

DELETE FROM enrollments
WHERE student_id = 1001 AND course_id = 'CS101';

PRIMARY KEY、FOREIGN KEY、UNIQUE、NOT NULL、CHECK などの制約せいやくConstraintは、許容きょようされるデータの条件じょうけんをスキーマに記録きろくし、不正ふせいな更新こうしんを拒否きょひする。ただし、制約せいやくの具体的ぐたいてきな機能きのうや構文こうぶんにはデータベース製品せいひんによる差異さいがある。

複数ふくすうの文ぶんを一体いったいの処理しょりとして扱あつかう場合ばあいは、トランザクションTransactionを使用しようする。COMMIT はトランザクションの変更へんこうを確定かくていし、ROLLBACK は未確定みかくていの変更へんこうを取消とりけす。これにより、処理しょりの途中とちゅうだけが反映はんえいされた状態じょうたいを回避かいひできる。ただし、トランザクションの分離ぶんりレベルや自動確定じどうかくていの既定値きていちは実装じっそうによって異ことなる。

7パラメータ化かと安全性あんぜんせい

利用者りようしゃの入力にゅうりょくを SQL 文字列もじれつへ直接連結ちょくせつれんけつすると、入力にゅうりょくが SQL の構文こうぶんとして解釈かいしゃくされる SQL インジェクションを招まねき得うる。値あたいは、使用しようするドライバが提供ていきょうするパラメータ化かされた問とい合あわせへ別途べっと渡わたす。

sql
SELECT student_id, name
FROM students
WHERE email = ?;

? はパラメータの概念例がいねんれいであり、実際じっさいのプレースホルダ構文こうぶんはドライバやデータベース製品せいひんによって異ことなる。パラメータ化かは値あたいと SQL 構文こうぶんを分離ぶんりするが、表名ひょうめいや列名れつめいなどの識別子しきべつしを任意にんいに安全化あんぜんかするものではない。識別子しきべつしを動的どうてきに選択せんたくする場合ばあいは、許可きょかリストによる検証けんしょうなどが必要ひつようである。また、認可にんか、最小権限さいしょうけんげん、機密情報きみつじょうほうの保護ほごも別途必要べっとひつようとなる。

8要点ようてん

  • SQL は、必要ひつような結果けっかを宣言せんげんし、その物理的ぶつりてきな実行方法じっこうほうほうをデータベース管理かんりシステムへ委ゆだねる。
  • WHERE は行ぎょうを選択せんたくし、SELECT は結果けっかの列れつや式しきを指定していする。SQLは既定きていで重複行ちょうふくぎょうを保持ほじする。NULL を含ふくむ条件じょうけんには三値論理さんちろんりが適用てきようされる。
  • JOIN は複数ふくすうの表ひょうを関連付かんれんづけ、キーと制約せいやくはデータの整合性せいごうせいを支ささえる。
  • 更新こうしんはトランザクションによって一体いったいとして管理かんりでき、外部入力がいぶにゅうりょくはパラメータ化かして SQL 構文こうぶんから分離ぶんりする。
  • ORDER BY のない結果けっかに順序じゅんじょの保証ほしょうはない。

9次つぎに進すすむ講義こうぎ

data/lecture/information/software-engineering/software-engineering-portal.lecture.n.md

SQL Fundamentals

data/lecture/information/database/database-basics.lecture.n.md

1Introduction

This lecture explains the fundamentals of SQLStructured Query Language, which declaratively expresses queries and updates over relational databases. It connects tables, rows, columns, primary keys, and foreign keys from the preceding lecture to SQL syntax.

SQL describes conditions on a required result rather than a procedure for reaching the data. A database management system normally chooses the execution plan, including index use and join order. This declarative approach separates a logical query from its physical execution method.

2SELECT, FROM, and WHERE

A basic query consists of three elements: SELECT, FROM, and WHERE.

  • FROM specifies the tables that form the query's input.
  • WHERE tests each row against a condition. This operation is called selectionSelection, or filtering.
  • SELECT specifies the columns or expressions included in the result and broadly corresponds to projectionProjection. SQL retains duplicate rows by default; SELECT DISTINCT removes duplicates. This differs from projection under the set semantics of relational algebra.

Conceptually, FROM establishes the input, WHERE selects rows, and SELECT projects columns. These are logical roles; a database management system need not perform the physical operations in this order.

sql
SELECT student_id, name
FROM students
WHERE department = 'Computer Science';

This query selects rows whose department is Computer Science from students and specifies student_id and name as result columns. Duplicate rows remain unless DISTINCT is specified.

3Result Ordering

A SQL query result has no guaranteed order unless the query specifies ORDER BY. The displayed order of the same query can change with the execution plan or physical data layout.

sql
SELECT student_id, name
FROM students
ORDER BY student_id ASC;

When reproducible ordering is required, ORDER BY must include enough columns to resolve ties.

4NULL and Three-Valued Logic

NULL is a marker for a value that is absent or unknown; it is neither an empty string nor the number zero. An ordinary comparison involving NULL yields UNKNOWN rather than TRUE or FALSE. SQL conditions therefore follow three-valued logicThree-valued logic.

WHERE retains only rows for which its condition is TRUE; it excludes rows for which the condition is FALSE or UNKNOWN. A query must consequently test nullity with IS NULL or IS NOT NULL, not with = NULL.

sql
SELECT student_id, name
FROM students
WHERE email IS NULL;

5JOIN and Keys

JOIN combines related data stored in separate tables. Suppose that students.student_id is a primary key and enrollments.student_id is a foreign key that references it.

sql
SELECT s.student_id, s.name, e.course_id
FROM students AS s
JOIN enrollments AS e
  ON e.student_id = s.student_id
WHERE e.status = 'enrolled';

ON specifies the join condition that matches rows from the two tables. The uniqueness of the primary key and the referential integrity of the foreign key allow the database to validate this relationship. A JOIN can nevertheless execute even when no foreign-key constraint has been declared.

6Updates, Constraints, and Transactions

SQL uses INSERT to add rows, UPDATE to modify existing rows, and DELETE to remove rows.

sql
INSERT INTO enrollments (student_id, course_id, status)
VALUES (1001, 'CS101', 'enrolled');

UPDATE enrollments
SET status = 'completed'
WHERE student_id = 1001 AND course_id = 'CS101';

DELETE FROM enrollments
WHERE student_id = 1001 AND course_id = 'CS101';

ConstraintsConstraint such as PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, and CHECK record conditions on admissible data in the schema and reject invalid updates. Specific constraint features and syntax vary among database products.

A transactionTransaction treats multiple statements as one unit of work. COMMIT makes a transaction's changes permanent, whereas ROLLBACK cancels uncommitted changes. Transactions can thereby prevent the database from retaining only an intermediate portion of an operation. Isolation levels and default autocommit behavior vary among implementations.

7Parameterization and Security

Directly concatenating user input into a SQL string can cause SQL injection, in which input is interpreted as SQL syntax. Values must instead be supplied separately through the parameterized-query facility of the relevant database driver.

sql
SELECT student_id, name
FROM students
WHERE email = ?;

Here, ? is a conceptual parameter marker; actual placeholder syntax varies among drivers and database products. Parameterization separates values from SQL syntax, but it does not automatically make arbitrary identifiers such as table or column names safe. Dynamically selected identifiers require validation such as an allowlist. Authorization, least privilege, and protection of confidential data remain separate requirements.

8Key Points

  • SQL declares a required result and delegates its physical execution method to the database management system.
  • WHERE selects rows, and SELECT specifies result columns or expressions. SQL retains duplicate rows by default. Three-valued logic applies to conditions involving NULL.
  • JOIN relates multiple tables, while keys and constraints support data integrity.
  • Transactions can manage updates as one unit, and external values must be parameterized to separate them from SQL syntax.
  • A result has no guaranteed order without ORDER BY.

9Next Lecture

data/lecture/information/software-engineering/software-engineering-portal.lecture.n.md
raw .n.md をコピー
loc をコピー (filepath:line ~ line)
copy share link
copy encoded share link
path をコピー
copy share link
copy encoded share link
copy share link
copy encoded share link
タブを全て閉じる