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

基本的きほんてきわせは、SELECTFROMWHERE三要素さんようそから構成こうせいされる。

  • 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_idname結果列けっかれつとして指定していする。重複行ちょうふくぎょう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 となるぎょうだけである。FALSEUNKNOWNぎょう除外じょがいされる。したがって、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 KEYFOREIGN KEYUNIQUENOT NULLCHECK などの制約せいやく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
タブを全て閉じる