Database.What is clustered index ?

📘 What is a Clustered Index?

A clustered index is a special type of index that determines the physical order of rows in a table.

In other words: the table’s data is stored in the order of the clustered index.


🔑 Key Characteristics:

  1. ✅ Only one per table
    Because the data can be physically ordered only one way.
  2. ✅ Data is stored with the index
    The clustered index contains the actual table data — there is no separate storage.
  3. ✅ Primary Key = Clustered Index (by default)
    In many databases (e.g., MySQL InnoDB, SQL Server), the primary key automatically becomes the clustered index unless you specify otherwise.

📊 Example:

CREATE TABLE Users (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

id is the clustered index

Rows in the Users table are physically stored sorted by id

So:

SELECT * FROM Users WHERE id = 5;

➡️ The database can go directly to the row, without any extra lookup.

🧠 Think of it Like:

A clustered index is like a phonebook where the pages are sorted by last name.
You flip directly to the page you need — no extra lookup required.


🔄 Clustered vs Non-Clustered:

FeatureClustered IndexNon-Clustered Index
Data in index?✅ Yes, contains table data❌ No, points to data
Affects row order?✅ Yes❌ No
Number per tableOnly 1Many allowed
Lookup speed🔥 Very fast for indexed columnGood, but needs extra lookup

🛠 When to Use a Clustered Index:

Use a clustered index on:

  • Columns frequently used in WHERE, JOIN, ORDER BY
  • Columns with high selectivity (many unique values)
  • Primary keys (almost always clustered)
Posted in Без рубрики | Comments Off on Database.What is clustered index ?

Datasource.What is the difference between clustered and non-clustered indexes?

🗃️ 1. Clustered Index

A clustered index determines the physical order of rows in a table.

  • ✅ There can be only one clustered index per table.
  • ✅ The data is stored directly in the index.
  • ✅ The table is the index.

Example:

In a table with a clustered index on id, the rows are physically sorted by id.
Accessing a row via this index goes directly to the data — no lookup needed.

📂 2. Non-Clustered Index

A non-clustered index is a separate structure that points to the actual data rows.

  • ✅ You can create multiple non-clustered indexes per table.
  • ❌ Does not change the physical order of the data.
  • 📎 Contains pointers (row IDs or clustered index keys) to access the actual data.

Example:

A non-clustered index on email will contain sorted email values with pointers to the actual row location (which is elsewhere).


🔍 Visual Analogy:

TypeAnalogy
ClusteredA phonebook sorted by last name — the data is in the index
Non-ClusteredA book’s index — points you to a page where data lives

🧱 Example (SQL Server or MySQL InnoDB):

-- Clustered index (by default on PRIMARY KEY)
CREATE TABLE Users (
    id INT PRIMARY KEY,      -- clustered index
    email VARCHAR(100),
    name VARCHAR(100)
);

-- Non-clustered index on email
CREATE INDEX idx_email ON Users(email);

⚖️ Comparison Table

FeatureClustered IndexNon-Clustered Index
Physical row order✅ Yes (matches index order)❌ No (separate structure)
Data stored in index✅ Yes❌ No (index points to data)
Number per tableOnly 1Many allowed
Speed (lookup)✅ Fastest for range/equality on keySlightly slower (requires extra lookup)
SizeUsually smallerSlightly larger (includes pointers)

✅ When to Use:

ScenarioUse This Index Type
Primary key, sorting, fast retrievalClustered Index
Frequently searched non-key columnsNon-Clustered Index
Multiple searchable fieldsMultiple Non-Clustered
Posted in Без рубрики | Comments Off on Datasource.What is the difference between clustered and non-clustered indexes?

Database.How EXPLAIN shows B-tree vs. hash usage in query plans ?

EXPLAIN (or EXPLAIN ANALYZE) is a command that shows how the database plans to execute a query, including:

  • Whether it uses an index
  • What type of index
  • How many rows it expects to scan
  • The access type (index, range, ref, etc.)

🧱 Sample Table:

CREATE TABLE Users (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    INDEX idx_name_email (name, email)
);

🧪 Run EXPLAIN on a Query:

EXPLAIN SELECT * FROM Users WHERE name = 'Alice';

You might see output like this (MySQL-style):

idselect_typetabletypekeyrowsExtra
1SIMPLEUsersrefidx_name_email10Using index

type: ref → index used for equality match

key: idx_name_email → composite B-tree index used

Using index → index contains all needed columns (covering index)

🔍 Want to Check a Hash Index?

In MySQL, hash indexes are used only in the MEMORY engine:

CREATE TABLE HashExample (
    id INT,
    name VARCHAR(50),
    INDEX USING HASH (name)
) ENGINE = MEMORY;

Then:

EXPLAIN SELECT * FROM HashExample WHERE name = 'Bob';

You’ll see key: name

But you won’t see USING HASH directly — MySQL doesn’t display the internal index type in EXPLAIN, but uses hash internally for MEMORY tables if specified.

🧠 PostgreSQL?

In PostgreSQL, use:

EXPLAIN ANALYZE SELECT * FROM users WHERE name = 'Alice';

Or see index details with:

SELECT * FROM pg_indexes WHERE tablename = 'users';

Summary:

What to Look ForMeaning
keyWhich index is used
type = indexFull index scan
type = refIndex used for equality search
Using indexNo need to access table — fast
rangeIndex used for range queries (<, >)
Posted in Без рубрики | Comments Off on Database.How EXPLAIN shows B-tree vs. hash usage in query plans ?

Database.I was sure that Composite Index (Multi-column) is b-tree

✅ Yes — a Composite Index is usually a B-tree index too.

Let’s clarify:


📘 Composite Index vs. B-tree:

  • B-tree is the data structure used to implement the index.
  • Composite index refers to the fact that the index is built over multiple columns, like (A, B, C).

So:

A composite index is just a B-tree that stores tuples of multiple columns.


🔍 Example:

CREATE INDEX idx_name_email ON Users(name, email);

This creates a B-tree index ordered like:

(name, email)

That means it’s sorted first by name, and within that, by email.

✅ So it’s both:

  • A composite index (multi-column)
  • Implemented as a B-tree

🧠 Analogy:

Think of a composite B-tree index as a multi-key phonebook:

  • First sorted by last name
  • Then by first name
  • Then by city

You can search:

  • All Smiths ✅
  • All “John Smiths” ✅
  • Just “people from Chicago”? ❌ (not helpful unless city is the first column)

✅ Summary:

TermWhat it means
B-tree IndexIndex structure used by most RDBMS
Composite IndexB-tree over multiple columns

You nailed it — the confusion is often in naming, but technically, composite ≠ different type, it’s just a B-tree with multiple fields.

Posted in Без рубрики | Comments Off on Database.I was sure that Composite Index (Multi-column) is b-tree

Database.What types of indexes exist?

🧱 1. B-tree Index (Balanced Tree)

  • 🔹 Most common index type (used by MySQL, PostgreSQL, Oracle, etc.)
  • 🔹 Efficient for equality (=) and range queries (<, >, BETWEEN, etc.)

✅ Good for:

WHERE age = 30
WHERE name BETWEEN 'A' AND 'F'

🪜 2. Composite Index (Multi-column)

  • 🔹 Index on two or more columns: (A, B)
  • 🔹 Useful when queries filter or sort on multiple columns
  • 🔹 Only works well when filtering starts with the left-most column

✅ Supports:
WHERE A = ?
WHERE A = ? AND B = ?
❌ Not efficient for WHERE B = ? alone

🔑 3. Unique Index

  • 🔹 Enforces uniqueness of values in one or more columns
  • 🔹 Automatically created for primary keys and unique constraints

✅ Ensures no duplicates in:

email, username, passport_number, etc.

⚙️ 4. Hash Index

  • 🔹 Fast for exact match lookups (=)
  • ❌ Not useful for range queries
  • 🔹 Used internally in some engines like MySQL MEMORY table

✅ Good for:

WHERE user_id = 123

❌ Not for:

WHERE user_id > 100

🔍 5. Full-Text Index

  • 🔹 Designed for searching large text fields (e.g., blog posts, comments)
  • 🔹 Supports natural language search (MATCH ... AGAINST)
  • 🔹 Available in MySQL, PostgreSQL (with GIN or TSVECTOR)

✅ Example:

SELECT * FROM articles
WHERE MATCH(content) AGAINST ('climate change');

🌐 6. Spatial Index (R-tree / GiST)

  • 🔹 Used for geographic or spatial data (e.g., GPS coordinates)
  • 🔹 Supports queries like “find all restaurants within 5 km”

✅ Example:

WHERE ST_Distance(location, POINT(55.75, 37.62)) < 5000;

🧠 7. Bitmap Index

  • 🔹 Efficient for low-cardinality columns (e.g., gender, status, yes/no)
  • 🔹 Often used in data warehouses for analytics
  • 🔹 Available in Oracle and some column-store DBs

🧪 8. Covering Index

  • 🔹 A composite index that contains all the columns used by a query
  • 🔹 Allows the database to answer the query using only the index, skipping table access

✅ Faster performance, especially for read-heavy workloads

📋 Summary Table:

Index TypeBest ForNot Good For
B-treeRange and equality searchesVery large text or spatial
HashEquality (=) searchesRange queries (<, >)
Full-textText searchStructured field filtering
CompositeMulti-column filteringQueries using only middle columns
UniqueEnforcing uniquenessHigh-insert workloads (may slow inserts)
BitmapLow-cardinality analyticsFrequent writes
SpatialGeolocation / mapsRegular string/number columns
Posted in Без рубрики | Comments Off on Database.What types of indexes exist?

Database.What are “indexes”? What are they used for? What are their advantages and disadvantages?

An index is a special lookup data structure that a database uses to speed up the retrieval of rows based on certain column values.

Think of an index like the index of a book — it helps you find content quickly, without scanning every page.

🎯 What Are Indexes Used For?

  • Speed up queries that use WHERE, JOIN, ORDER BY, GROUP BY
  • Help databases find rows without scanning the entire table
  • Enforce uniqueness in columns (e.g., primary keys, unique constraints)

🧱 Types of Indexes (commonly used)

TypeDescription
B-Tree IndexDefault in most RDBMS; good for range and equality queries
Hash IndexFast for equality (=), not for ranges
Unique IndexEnsures values in the column are unique
Composite IndexIndex over multiple columns ((A, B))
Full-Text IndexUsed for text search in large text fields

✅ Advantages of Indexes

AdvantageBenefit
🚀 Faster SELECT queriesEspecially on large datasets
🔗 Faster JOINsSpeeds up joining related tables
🔍 Quick lookup/searchIdeal for searching by key or common columns
🧱 Enforces constraintsE.g., UNIQUE, PRIMARY KEY
📈 Improves sorting/groupingHelps with ORDER BY, GROUP BY clauses

❌ Disadvantages of Indexes

DisadvantageProblem
🐌 Slower INSERT, UPDATE, DELETEIndexes must be updated along with the data
💾 Extra storageIndexes consume disk space
🧠 Over-indexing hurtsToo many indexes can confuse the query planner or cause overhead
❓ Wrong index choiceMay lead to worse performance than no index

🛠️ Example:

-- Create an index on the email column
CREATE INDEX idx_email ON Users(email);

-- Now this query is fast
SELECT * FROM Users WHERE email = 'alice@example.com';

🧠 Tip: When to Use Indexes

Use indexes when:

  • You frequently query or filter on a column
  • A column is used in joins or sorting
  • The table has many rows (thousands or millions)

Avoid or limit indexes when:

  • You write-heavy tables (frequent updates/inserts)
  • You index columns with low uniqueness (e.g., gender, boolean)
Posted in Без рубрики | Comments Off on Database.What are “indexes”? What are they used for? What are their advantages and disadvantages?

Database.If i define primary key as student_id, course_id, why i use only WHERE student_id = 1, for example, and how index of primary key works here ?

🧱 1. Understanding Composite Primary Key Index

When you define:

PRIMARY KEY (student_id, course_id)

The database creates a composite index on (student_id, course_id) — this is a B-tree index in most databases.

Order matters here:

  • It’s indexed like:
    (student_id → course_id)

That means:

  • The index can be used efficiently if you filter by:
    • student_id
    • or student_id AND course_id
  • But not efficiently if you filter by:
    • only course_id

📊 Visualizing the Index:

Think of the index like a phonebook sorted by:

(student_id, course_id)

📘 Indexed like this:

student_idcourse_id
1101
1102
2101
2103

So:

  • WHERE student_id = 1 → ✅ fast lookup (index helps)
  • WHERE student_id = 1 AND course_id = 101 → ✅ even faster (precise match)
  • WHERE course_id = 101 → ❌ not efficient (index ignored)

🧪 2. Why You Can Use Only student_id in WHERE Clause

Because the index starts with student_id, the database can:

  • Navigate directly to all rows where student_id = 1
  • Then scan the inner values (course_id) if needed

This is called a left-prefix match — using the first column(s) of a composite index.


🧠 Rule of Thumb:

A composite index on (A, B) can be used by queries filtering:

  • A ✅
  • A AND B ✅
  • B alone ❌ (index not used unless a separate index on B exists)

🛠 Recommendation:

If you often query by just course_id, create a separate index:

CREATE INDEX idx_course ON StudentCourses(course_id);
Posted in Без рубрики | Comments Off on Database.If i define primary key as student_id, course_id, why i use only WHERE student_id = 1, for example, and how index of primary key works here ?

Database.Give example of use of composite primary key

🎓 Example Scenario: Student Course Enrollment

You want to track which students are enrolled in which courses, and each student can enroll in many courses, while each course has many students — a many-to-many relationship.

You use a junction table to model this.

🧱 Table: StudentCourses with Composite Primary Key

CREATE TABLE StudentCourses (
    student_id INT,
    course_id INT,
    enrollment_date DATE,
    PRIMARY KEY (student_id, course_id)
);

🔑 Composite primary key: (student_id, course_id)

Ensures a student can’t enroll in the same course twice

Guarantees uniqueness of each student–course pair

📌 Insert Example:

INSERT INTO StudentCourses (student_id, course_id, enrollment_date)
VALUES (1, 101, '2025-04-01');

🔍 Query Example:

Get all courses a student is enrolled in:

SELECT course_id, enrollment_date
FROM StudentCourses
WHERE student_id = 1;

Get all students in a specific course:

SELECT student_id, enrollment_date
FROM StudentCourses
WHERE course_id = 101;

🧠 Why Use a Composite Key Here?

BenefitExplanation
Avoids duplicate enrollmentsEach student-course pair is unique
Models many-to-many cleanlyNo need for an artificial ID column
Enforces data integrityPrevents inconsistent or duplicate data
Posted in Без рубрики | Comments Off on Database.Give example of use of composite primary key

Database.Is primary key always indexed ?

✅ Is a Primary Key Always Indexed?

Yes — in all major relational database systems, a primary key is automatically indexed.


📌 Why?

Because:

  • The primary key must be unique.
  • The database must be able to quickly check for duplicates.
  • Fast access is essential for searching, joining, and enforcing referential integrity.

So when you declare a primary key:

CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100)
);

The database automatically creates a unique index on customer_id.


🧠 Note:

  • You don’t need to manually add an index for a primary key — it’s built-in.
  • If you define a composite primary key, a composite index is also created automatically.

🛠 Example (composite key):

CREATE TABLE StudentCourses (
    student_id INT,
    course_id INT,
    PRIMARY KEY (student_id, course_id)
);

➡️ This will create a composite index on (student_id, course_id).

Posted in Без рубрики | Comments Off on Database.Is primary key always indexed ?

Database.What are the types of relationships in a database? Give examples.

In relational databases, relationships define how data in one table is connected to data in another. There are three main types of relationships:


1. 🔁 One-to-One (1:1)

➡️ One record in Table A is related to only one record in Table B, and vice versa.

✅ Example:

Table: Users

UserIDName
1Alice

Table: UserProfiles

ProfileIDUserIDBio
1011Developer
  • Each user has only one profile
  • UserID in UserProfiles is a foreign key referencing Users(UserID)

2. 🔗 One-to-Many (1:N)

➡️ One record in Table A can be related to many records in Table B,
but each record in Table B is related to only one in Table A.

✅ Example:

Table: Customers

CustomerIDName
1Alice
2Bob

Table: Orders

OrderIDCustomerIDProduct
1011Laptop
1021Phone
1032Monitor
  • One customer can place many orders
  • Each order belongs to one customer

3. 🔄 Many-to-Many (M:N)

➡️ A record in Table A can relate to many records in Table B, and vice versa.

To implement this, we use a junction table.

✅ Example:

Table: Students

StudentIDName
1Alice
2Bob

Table: Courses

CourseIDTitle
101Math
102Physics

Junction Table: StudentCourses

StudentIDCourseID
1101
1102
2101
  • Alice takes Math and Physics
  • Bob takes Math
  • This is a many-to-many relationship

🧠 Summary Table:

RelationshipDescriptionExample
One-to-OneOne row in A ↔ one row in BUser ↔ Profile
One-to-ManyOne row in A ↔ many in BCustomer ↔ Orders
Many-to-ManyMany rows in A ↔ many in B via junctionStudents ↔ Courses
Posted in Без рубрики | Comments Off on Database.What are the types of relationships in a database? Give examples.