diff --git a/CompositeKeys.md b/CompositeKeys.md new file mode 100644 index 0000000..5e4fe93 --- /dev/null +++ b/CompositeKeys.md @@ -0,0 +1,303 @@ +# Composite Keys in SQL + +## Overview + +A **composite key** (also known as a compound key) is a primary key composed of two or more columns that together uniquely identify each row in a table. Unlike a simple primary key which uses a single column, composite keys leverage multiple columns to establish uniqueness. + +## When to Use Composite Keys + +Composite keys are particularly useful when: + +1. **No Single Natural Key Exists**: When no single column can uniquely identify a record +2. **Natural Relationships**: When multiple attributes naturally combine to form a unique identifier +3. **Junction Tables**: In many-to-many relationships where the combination of foreign keys forms the primary key +4. **Historical Data**: When tracking changes over time (e.g., employee + date combination) +5. **Hierarchical Data**: When representing parent-child relationships with multiple levels + +## Syntax + +### Creating a Table with Composite Key + +```sql +CREATE TABLE TableName ( + Column1 DataType NOT NULL, + Column2 DataType NOT NULL, + Column3 DataType, + CONSTRAINT PK_TableName PRIMARY KEY (Column1, Column2) +); +``` + +### Adding Composite Key to Existing Table + +```sql +ALTER TABLE TableName +ADD CONSTRAINT PK_TableName PRIMARY KEY (Column1, Column2); +``` + +## Id-Ego-Superego Example + +The file `T-Sql/id-ego-superego-composite-key.tsql` demonstrates composite keys using Freudian psychology concepts where `id`, `ego`, and `superego` together form a unique identifier for psychological states. + +### Why This Example? + +This creative example illustrates several key concepts: + +1. **Multiple Component Identity**: Just as Freud's psyche model requires all three components (id, ego, superego) to describe a complete psychological state, the composite key requires all three columns to uniquely identify a record. + +2. **Natural Relationship**: The strength or level of each component (represented by integer values) combines to create a unique psychological profile. + +3. **Referential Integrity**: Child tables (PsychologicalConflict, BehavioralOutcome, PsycheMetrics) reference the parent table using all three components of the composite key. + +### Table Structure + +```sql +CREATE TABLE PsychologicalState ( + id INT NOT NULL, -- Primitive desires + ego INT NOT NULL, -- Realistic mediator + superego INT NOT NULL, -- Moral standards + stateName VARCHAR(100), + description VARCHAR(500), + conflictLevel DECIMAL(3,2), + resolutionStrategy VARCHAR(200), + CONSTRAINT PK_PsychologicalState PRIMARY KEY (id, ego, superego) +); +``` + +### Foreign Key References + +Child tables must reference all components: + +```sql +CREATE TABLE PsychologicalConflict ( + conflictId INT PRIMARY KEY IDENTITY(1,1), + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + conflictType VARCHAR(50), + -- Foreign key must include all composite key columns + CONSTRAINT FK_Conflict_State FOREIGN KEY (id, ego, superego) + REFERENCES PsychologicalState(id, ego, superego) +); +``` + +## Advantages of Composite Keys + +### 1. Natural Representation +- Reflects real-world relationships more accurately +- No need for artificial surrogate keys +- Self-documenting (meaningful column names) + +### 2. Data Integrity +- Enforces uniqueness across multiple dimensions +- Prevents duplicate combinations +- Maintains referential integrity across related tables + +### 3. Query Optimization +- Can improve query performance when filtering on key columns +- Supports efficient joins on multiple columns + +### 4. Semantic Clarity +- Makes the unique identifier meaningful +- Easier to understand data relationships + +## Disadvantages and Considerations + +### 1. Complexity +- More complex to write JOIN statements +- Foreign key definitions are longer +- More columns to manage in relationships + +### 2. Performance +- Larger index size (multiple columns) +- Potentially slower than single-column keys +- More data to transfer in joins + +### 3. Updates +- Updating any part of the key affects all referencing tables +- Requires cascading updates if key values change +- More difficult to maintain if business rules change + +### 4. Application Code +- More complex in ORM frameworks +- Requires multiple parameters for lookups +- Can complicate API design + +## Best Practices + +### 1. Choose Immutable Columns +```sql +-- Good: Status codes and dates rarely change +CREATE TABLE OrderStatus ( + orderId INT NOT NULL, + statusDate DATE NOT NULL, + status VARCHAR(20), + PRIMARY KEY (orderId, statusDate) +); + +-- Avoid: Email addresses can change +CREATE TABLE UserProfile ( + email VARCHAR(100) NOT NULL, + profileDate DATE NOT NULL, + -- Not ideal as composite key + PRIMARY KEY (email, profileDate) +); +``` + +### 2. Keep Keys Reasonably Small +```sql +-- Good: 2-3 columns +PRIMARY KEY (customerId, orderDate) + +-- Potentially problematic: Too many columns +PRIMARY KEY (region, country, state, city, zipCode) +-- Consider a surrogate key instead +``` + +### 3. Consider Adding a Surrogate Key +```sql +-- Option: Composite key + surrogate key for easier referencing +CREATE TABLE OrderItem ( + orderItemId INT IDENTITY(1,1) PRIMARY KEY, -- Surrogate + orderId INT NOT NULL, + productId INT NOT NULL, + quantity INT, + CONSTRAINT UK_OrderItem UNIQUE (orderId, productId) -- Natural key +); +``` + +### 4. Document the Business Logic +Always document why the specific columns form a composite key: + +```sql +-- The combination of studentId and courseId uniquely identifies +-- a student's enrollment in a specific course +CREATE TABLE Enrollment ( + studentId INT NOT NULL, + courseId INT NOT NULL, + enrollmentDate DATE, + grade VARCHAR(2), + PRIMARY KEY (studentId, courseId) +); +``` + +## Common Use Cases + +### 1. Many-to-Many Relationships + +```sql +-- Student-Course enrollment +CREATE TABLE StudentCourse ( + studentId INT NOT NULL, + courseId INT NOT NULL, + semester VARCHAR(20), + grade DECIMAL(3,2), + PRIMARY KEY (studentId, courseId), + FOREIGN KEY (studentId) REFERENCES Students(studentId), + FOREIGN KEY (courseId) REFERENCES Courses(courseId) +); +``` + +### 2. Time-Series Data + +```sql +-- Stock prices over time +CREATE TABLE StockPrice ( + symbol VARCHAR(10) NOT NULL, + priceDate DATETIME NOT NULL, + openPrice DECIMAL(10,2), + closePrice DECIMAL(10,2), + volume BIGINT, + PRIMARY KEY (symbol, priceDate) +); +``` + +### 3. Hierarchical Structures + +```sql +-- Organization hierarchy +CREATE TABLE OrganizationUnit ( + companyId INT NOT NULL, + departmentId INT NOT NULL, + unitId INT NOT NULL, + unitName VARCHAR(100), + PRIMARY KEY (companyId, departmentId, unitId) +); +``` + +### 4. Versioned Records + +```sql +-- Product versions +CREATE TABLE ProductVersion ( + productId INT NOT NULL, + versionNumber INT NOT NULL, + releaseDate DATE, + features VARCHAR(1000), + PRIMARY KEY (productId, versionNumber) +); +``` + +## Querying with Composite Keys + +### Exact Match Query +```sql +SELECT * +FROM PsychologicalState +WHERE id = 1 AND ego = 2 AND superego = 1; +``` + +### Join with Composite Keys +```sql +SELECT ps.stateName, pc.conflictType +FROM PsychologicalState ps +JOIN PsychologicalConflict pc + ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego; +``` + +### Partial Key Search +```sql +-- Find all states where id = 2 (partial key) +SELECT * +FROM PsychologicalState +WHERE id = 2; +``` + +## Composite Keys vs. Surrogate Keys + +| Aspect | Composite Key | Surrogate Key | +|--------|--------------|---------------| +| **Meaning** | Business-meaningful columns | System-generated, no business meaning | +| **Stability** | Can change if business rules change | Stable, never changes | +| **Complexity** | More complex joins and foreign keys | Simpler references | +| **Performance** | Larger indexes, more join overhead | Smaller indexes, faster joins | +| **Clarity** | Self-documenting | Requires additional context | +| **Best For** | Natural relationships, junction tables | Arbitrary records, frequently updated keys | + +## Conclusion + +Composite keys are a powerful database design tool when used appropriately. They provide natural representation of complex relationships and enforce data integrity across multiple dimensions. However, they come with added complexity and should be chosen carefully based on: + +- Business requirements +- Data stability +- Query patterns +- Performance needs +- Maintenance considerations + +The id-ego-superego example in this repository demonstrates how composite keys can elegantly model complex, multi-dimensional concepts while maintaining referential integrity throughout the database schema. + +## References + +- [Normalization Forms](Normalization%20Forms.md) +- [Entity Relational Mapping](ERM.md) +- [T-SQL Example: id-ego-superego-composite-key.tsql](T-Sql/id-ego-superego-composite-key.tsql) + +## Related Concepts + +- **Primary Keys**: Unique identifiers for table rows +- **Foreign Keys**: References to primary keys in other tables +- **Candidate Keys**: Potential primary keys +- **Natural Keys**: Keys derived from real-world attributes +- **Surrogate Keys**: Artificial keys with no business meaning +- **Unique Constraints**: Ensure uniqueness without being primary keys diff --git a/README.md b/README.md index 74f1c64..8658815 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,12 @@ This repository contains various SQL scripts, T-SQL scripts, and documentation f - `.Net/quick_setup.tsql`: SQL scripts for creating and managing a database named `MySchool`. - `ADONET/SqlInjectionPrevention.cs`: C# class for preventing SQL injection using parameterized queries. +- `CompositeKeys.md`: Comprehensive guide to composite keys in SQL with best practices and examples. - `README.md`: Provides links to various resources related to SQL, ORM, and SQL linters/parsers. +- `T-Sql/company.tsql`: Comprehensive company database with complex queries and CTEs. - `T-Sql/gg.tsql`: Script for dropping all user databases in SQL Server. - `T-Sql/gg2.tsql`: Script for dropping all user databases in SQL Server. +- `T-Sql/id-ego-superego-composite-key.tsql`: Demonstrates composite key concepts using Freudian psychology model. - `T-Sql/OPENROWSET_example.tsql`: Examples of using the `OPENROWSET` function in SQL Server. ## Setting Up and Using SQL Scripts @@ -89,6 +92,46 @@ public class SqlInjectionPrevention } ``` +## Composite Keys in SQL + +Composite keys (also known as compound keys) are primary keys composed of two or more columns that together uniquely identify each row in a table. This repository includes a comprehensive example demonstrating composite key concepts. + +### Id-Ego-Superego Composite Key Example + +The `T-Sql/id-ego-superego-composite-key.tsql` file provides a creative demonstration of composite keys using Freudian psychology concepts. In this example: + +- **id**: Represents the instinctive, primitive desires (integer value) +- **ego**: Represents the realistic, mediating part (integer value) +- **superego**: Represents the moral, idealistic part (integer value) + +Together, these three columns form a composite primary key that uniquely identifies different psychological states. The example includes: + +1. **Main Table**: `PsychologicalState` with composite key (id, ego, superego) +2. **Related Tables**: `PsychologicalConflict`, `BehavioralOutcome`, `PsycheMetrics` +3. **Complex Queries**: Demonstrating joins, CTEs, and analysis using composite keys +4. **Referential Integrity**: Shows how foreign keys reference composite keys + +```sql +CREATE TABLE PsychologicalState ( + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + stateName VARCHAR(100), + description VARCHAR(500), + conflictLevel DECIMAL(3,2), + CONSTRAINT PK_PsychologicalState PRIMARY KEY (id, ego, superego) +); +``` + +### Key Benefits Demonstrated + +- **Natural Representation**: Models complex multi-dimensional concepts +- **Data Integrity**: Ensures uniqueness across multiple attributes +- **Referential Integrity**: Maintains consistency across related tables +- **Real-World Modeling**: Reflects actual relationships in the domain + +For a complete guide on composite keys, including when to use them, best practices, advantages, and disadvantages, see the [CompositeKeys.md](CompositeKeys.md) documentation. + ## Using TSqlParser for Parsing and Analyzing SQL Scripts The `T-Sql/TSqlParser.md` file provides a detailed explanation of the `TSqlParser` class and its usage. The `TSqlParser` class from the Microsoft.Data.Tools.Schema.Sql library is used to parse T-SQL scripts. This can be useful for analyzing SQL scripts, including detecting potential SQL injection vulnerabilities by examining the structure and content of the queries. diff --git a/T-Sql/id-ego-superego-composite-key-QUICK-REFERENCE.md b/T-Sql/id-ego-superego-composite-key-QUICK-REFERENCE.md new file mode 100644 index 0000000..4631b02 --- /dev/null +++ b/T-Sql/id-ego-superego-composite-key-QUICK-REFERENCE.md @@ -0,0 +1,204 @@ +# Id-Ego-Superego Composite Key Example + +## Quick Reference + +This is a practical demonstration of **composite keys** in SQL using Freudian psychology concepts. + +## Tables Overview + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PsychologicalState (Parent Table) │ +│ PRIMARY KEY: (id, ego, superego) - COMPOSITE KEY │ +├─────────────────────────────────────────────────────────────┤ +│ id (INT) - Primitive desires level │ +│ ego (INT) - Rational mediator level │ +│ superego (INT) - Moral standards level │ +│ stateName (VARCHAR) - Name of the state │ +│ description (VARCHAR) - Description │ +│ conflictLevel (DEC) - How much internal conflict (0-5) │ +│ resolutionStrategy - Strategy to resolve conflicts │ +└─────────────────────────────────────────────────────────────┘ + │ + │ Referenced by (Foreign Keys) + │ + ┌─────────────────┼─────────────────┬───────────────────┐ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ +│Psychological │ │ Behavioral │ │ Psyche │ │ │ +│ Conflict │ │ Outcome │ │ Metrics │ │ ... │ +├──────────────┤ ├──────────────┤ ├──────────────┤ ├──────────────┤ +│ FK: (id, ego,│ │ FK: (id, ego,│ │ FK: (id, ego,│ │ │ +│ superego) │ │ superego) │ │ superego) │ │ │ +│ │ │ │ │ │ │ │ +│ Tracks │ │ Records │ │ Measures │ │ │ +│ conflicts │ │ behaviors │ │ strengths │ │ │ +└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ +``` + +## Example Data + +### Sample Psychological State +``` +id=2, ego=2, superego=2 +├─ State Name: "High-Intensity Conflict" +├─ Conflict Level: 4.50 +└─ Description: All components strong, creating intense struggle +``` + +### What Makes This a Composite Key? + +Each component alone is **NOT unique**: +- id=1 appears in multiple rows +- ego=2 appears in multiple rows +- superego=1 appears in multiple rows + +But the **combination** (id, ego, superego) is **UNIQUE**: +- (1, 1, 1) ✓ Unique +- (1, 2, 1) ✓ Unique +- (2, 1, 1) ✓ Unique +- (1, 1, 2) ✓ Unique + +## Key SQL Operations + +### Creating the Table +```sql +CREATE TABLE PsychologicalState ( + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + stateName VARCHAR(100), + -- Composite primary key + CONSTRAINT PK_PsychologicalState PRIMARY KEY (id, ego, superego) +); +``` + +### Inserting Data +```sql +INSERT INTO PsychologicalState (id, ego, superego, stateName, conflictLevel) +VALUES (1, 1, 1, 'Balanced Harmony', 1.00); +``` + +### Querying with Composite Key +```sql +-- Must specify all key columns for exact match +SELECT * +FROM PsychologicalState +WHERE id = 1 AND ego = 1 AND superego = 1; +``` + +### Joining with Composite Key +```sql +-- All columns must be matched in JOIN +SELECT ps.stateName, pc.conflictType +FROM PsychologicalState ps +JOIN PsychologicalConflict pc + ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego; +``` + +### Foreign Key Reference +```sql +CREATE TABLE PsychologicalConflict ( + conflictId INT PRIMARY KEY IDENTITY(1,1), + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + -- Foreign key must reference ALL composite key columns + CONSTRAINT FK_Conflict_State + FOREIGN KEY (id, ego, superego) + REFERENCES PsychologicalState(id, ego, superego) +); +``` + +## Why This Example? + +### 1. Natural Multi-Dimensional Model +Just as Freud's model needs **all three** components to describe personality: +- **Id** alone = incomplete (just desires) +- **Ego** alone = incomplete (just logic) +- **Superego** alone = incomplete (just morals) +- **All three together** = complete psychological state ✓ + +### 2. Real-World Complexity +Different combinations create different states: +- (1,1,1) = Balanced +- (2,1,1) = Id-dominant (impulsive) +- (1,1,2) = Superego-dominant (overly moral) +- (3,2,1) = Extreme desires (critical) + +### 3. Demonstrates Composite Key Benefits +- ✓ Enforces uniqueness across multiple dimensions +- ✓ Maintains referential integrity +- ✓ Self-documenting (meaningful column names) +- ✓ Natural relationship representation + +## Common Queries + +### Find High-Conflict States +```sql +SELECT id, ego, superego, stateName, conflictLevel +FROM PsychologicalState +WHERE conflictLevel >= 4.0 +ORDER BY conflictLevel DESC; +``` + +### Analyze Component Dominance +```sql +SELECT + CASE + WHEN id > ego AND id > superego THEN 'Id-Dominant' + WHEN ego > id AND ego > superego THEN 'Ego-Dominant' + WHEN superego > id AND superego > ego THEN 'Superego-Dominant' + ELSE 'Balanced' + END as DominantComponent, + COUNT(*) as StateCount, + AVG(conflictLevel) as AvgConflict +FROM PsychologicalState +GROUP BY + CASE + WHEN id > ego AND id > superego THEN 'Id-Dominant' + WHEN ego > id AND ego > superego THEN 'Ego-Dominant' + WHEN superego > id AND superego > ego THEN 'Superego-Dominant' + ELSE 'Balanced' + END; +``` + +### Unresolved Conflicts +```sql +SELECT ps.stateName, pc.conflictType, pc.severity +FROM PsychologicalState ps +JOIN PsychologicalConflict pc + ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego +WHERE pc.resolvedDate IS NULL +ORDER BY ps.conflictLevel DESC; +``` + +## Files + +- **[T-Sql/id-ego-superego-composite-key.tsql](T-Sql/id-ego-superego-composite-key.tsql)** - Full SQL implementation +- **[CompositeKeys.md](CompositeKeys.md)** - Comprehensive documentation on composite keys +- **[README.md](README.md)** - Main repository documentation + +## Learning Points + +1. **Composite keys** use multiple columns to ensure uniqueness +2. **Foreign keys** must reference ALL columns in a composite key +3. **JOINs** require matching ALL key columns +4. **Queries** can filter on individual columns or the full combination +5. **Business logic** should determine when composite keys are appropriate + +## Next Steps + +1. Execute the SQL script: `T-Sql/id-ego-superego-composite-key.tsql` +2. Read the documentation: `CompositeKeys.md` +3. Experiment with queries and modifications +4. Consider when composite keys fit your database design needs + +--- + +*For complete details and advanced examples, see the full SQL script and documentation.* diff --git a/T-Sql/id-ego-superego-composite-key.tsql b/T-Sql/id-ego-superego-composite-key.tsql new file mode 100644 index 0000000..cca720c --- /dev/null +++ b/T-Sql/id-ego-superego-composite-key.tsql @@ -0,0 +1,355 @@ +-- ======================================== +-- ID-EGO-SUPEREGO COMPOSITE KEY DEMONSTRATION +-- ======================================== +-- This file demonstrates the use of composite keys using Freudian psychology concepts. +-- The id, ego, and superego together form a unique composite key representing +-- the three parts of the human psyche according to Freudian theory. +-- +-- Composite keys are useful when: +-- 1. No single column can uniquely identify a row +-- 2. Multiple columns together form a natural unique identifier +-- 3. Representing complex relationships between entities + +-- ======================================== +-- CREATE TABLES +-- ======================================== + +-- Main table demonstrating id-ego-superego as composite key +-- This represents psychological states or decision moments +CREATE TABLE PsychologicalState ( + id INT NOT NULL, -- Represents the instinctive, primitive desires + ego INT NOT NULL, -- Represents the realistic, mediating part + superego INT NOT NULL, -- Represents the moral, idealistic part + stateName VARCHAR(100), + description VARCHAR(500), + conflictLevel DECIMAL(3,2), -- 0.00 to 5.00 scale + resolutionStrategy VARCHAR(200), + recordedAt DATETIME DEFAULT GETDATE(), + -- Composite primary key using all three components + CONSTRAINT PK_PsychologicalState PRIMARY KEY (id, ego, superego) +); + +-- Table to track psychological conflicts and their resolutions +CREATE TABLE PsychologicalConflict ( + conflictId INT PRIMARY KEY IDENTITY(1,1), + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + conflictType VARCHAR(50), + severity VARCHAR(20), + resolution VARCHAR(500), + resolvedDate DATETIME, + -- Foreign key referencing the composite key + CONSTRAINT FK_Conflict_State FOREIGN KEY (id, ego, superego) + REFERENCES PsychologicalState(id, ego, superego) +); + +-- Table representing behavioral outcomes based on psyche balance +CREATE TABLE BehavioralOutcome ( + outcomeId INT PRIMARY KEY IDENTITY(1,1), + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + behavior VARCHAR(200), + impact VARCHAR(100), + timestamp DATETIME DEFAULT GETDATE(), + -- Foreign key referencing the composite key + CONSTRAINT FK_Outcome_State FOREIGN KEY (id, ego, superego) + REFERENCES PsychologicalState(id, ego, superego) +); + +-- Table for tracking psyche component strengths over time +CREATE TABLE PsycheMetrics ( + metricId INT PRIMARY KEY IDENTITY(1,1), + id INT NOT NULL, + ego INT NOT NULL, + superego INT NOT NULL, + idStrength DECIMAL(5,2), -- How strong the id impulses are + egoBalance DECIMAL(5,2), -- How well the ego mediates + superegoRigidity DECIMAL(5,2), -- How strict the moral standards + harmonyScore DECIMAL(5,2), -- Overall balance (0-100) + assessmentDate DATETIME DEFAULT GETDATE(), + -- Foreign key referencing the composite key + CONSTRAINT FK_Metrics_State FOREIGN KEY (id, ego, superego) + REFERENCES PsychologicalState(id, ego, superego) +); + +-- ======================================== +-- INSERT SAMPLE DATA +-- ======================================== + +-- Insert various psychological states with different id-ego-superego combinations +INSERT INTO PsychologicalState (id, ego, superego, stateName, description, conflictLevel, resolutionStrategy) +VALUES +(1, 1, 1, 'Balanced Harmony', 'All three components are in perfect balance, leading to healthy decision-making', 1.00, 'Maintain current balance through mindfulness'), +(1, 2, 1, 'Ego-Dominant Pragmatism', 'Ego is stronger, focusing on practical solutions', 2.00, 'Allow more emotional expression'), +(2, 1, 1, 'Id-Driven Impulse', 'Strong desires seeking immediate gratification', 3.50, 'Strengthen rational thinking and moral consideration'), +(1, 1, 2, 'Superego-Controlled Restraint', 'Moral standards dominate, possibly leading to over-restriction', 3.00, 'Allow more flexibility and self-compassion'), +(2, 2, 2, 'High-Intensity Conflict', 'All components are strong, creating intense internal struggle', 4.50, 'Seek professional guidance for integration'), +(1, 2, 2, 'Ethical Pragmatism', 'Balance between morality and practicality', 1.50, 'Continue current approach'), +(2, 1, 2, 'Desire vs. Morality', 'Strong conflict between wants and moral standards', 4.00, 'Ego mediation needed to find compromise'), +(3, 2, 1, 'Extreme Id Pressure', 'Very strong primitive desires challenging control', 4.80, 'Crisis intervention required'), +(1, 3, 1, 'Hyper-Rational Control', 'Ego is extremely dominant, suppressing other aspects', 3.20, 'Reconnect with emotions and values'), +(1, 1, 3, 'Rigid Moral Standards', 'Extremely strict superego causing guilt and anxiety', 4.20, 'Work on self-acceptance and flexibility'); + +-- Insert psychological conflicts +INSERT INTO PsychologicalConflict (id, ego, superego, conflictType, severity, resolution, resolvedDate) +VALUES +(1, 1, 1, 'Decision-Making', 'Low', 'Balanced approach led to satisfactory outcome', '2024-01-15'), +(2, 1, 1, 'Impulse Control', 'High', 'Required significant ego intervention to manage desires', '2024-01-20'), +(1, 1, 2, 'Moral Dilemma', 'Medium', 'Found middle ground between strictness and practicality', '2024-02-01'), +(2, 2, 2, 'Identity Crisis', 'Critical', 'Ongoing therapeutic intervention', NULL), +(2, 1, 2, 'Values Conflict', 'High', 'Gradual integration through conscious awareness', '2024-02-15'), +(3, 2, 1, 'Addiction Pattern', 'Critical', 'Intensive treatment program initiated', NULL), +(1, 3, 1, 'Emotional Suppression', 'Medium', 'Learning to accept emotional experiences', '2024-03-01'), +(1, 1, 3, 'Perfectionism', 'High', 'Working on realistic standards and self-compassion', NULL); + +-- Insert behavioral outcomes +INSERT INTO BehavioralOutcome (id, ego, superego, behavior, impact, timestamp) +VALUES +(1, 1, 1, 'Thoughtful communication with others', 'Positive relationship building', '2024-01-10 10:00:00'), +(2, 1, 1, 'Impulsive purchase decision', 'Short-term regret, learning opportunity', '2024-01-12 15:30:00'), +(1, 1, 2, 'Declining social invitation due to perceived obligations', 'Increased isolation', '2024-01-18 19:00:00'), +(2, 2, 2, 'Procrastination on important task', 'Internal conflict and stress', '2024-01-25 14:00:00'), +(1, 2, 1, 'Efficient problem-solving at work', 'Professional success', '2024-02-05 11:00:00'), +(2, 1, 2, 'Resisting temptation through willpower', 'Sense of accomplishment but fatigue', '2024-02-10 16:00:00'), +(3, 2, 1, 'Engaging in risky behavior', 'Immediate pleasure, long-term consequences', '2024-02-14 22:00:00'), +(1, 3, 1, 'Over-analyzing simple decision', 'Paralysis by analysis', '2024-02-20 09:00:00'), +(1, 1, 3, 'Excessive self-criticism', 'Decreased self-esteem', '2024-03-01 12:00:00'), +(1, 2, 2, 'Balanced life choice', 'Sustainable wellbeing', '2024-03-05 10:00:00'); + +-- Insert psyche metrics +INSERT INTO PsycheMetrics (id, ego, superego, idStrength, egoBalance, superegoRigidity, harmonyScore) +VALUES +(1, 1, 1, 50.00, 90.00, 50.00, 85.00), +(1, 2, 1, 45.00, 95.00, 48.00, 88.00), +(2, 1, 1, 85.00, 60.00, 45.00, 55.00), +(1, 1, 2, 40.00, 75.00, 88.00, 60.00), +(2, 2, 2, 80.00, 85.00, 82.00, 50.00), +(1, 2, 2, 48.00, 92.00, 75.00, 78.00), +(2, 1, 2, 88.00, 55.00, 90.00, 45.00), +(3, 2, 1, 95.00, 70.00, 40.00, 35.00), +(1, 3, 1, 35.00, 98.00, 42.00, 70.00), +(1, 1, 3, 38.00, 72.00, 95.00, 52.00); + +-- ======================================== +-- QUERY EXAMPLES +-- ======================================== + +-- 1. Retrieve all psychological states ordered by conflict level +SELECT id, ego, superego, stateName, conflictLevel, resolutionStrategy +FROM PsychologicalState +ORDER BY conflictLevel DESC; + +-- 2. Find states with high conflict (above 4.0) +SELECT id, ego, superego, stateName, description, conflictLevel +FROM PsychologicalState +WHERE conflictLevel >= 4.0; + +-- 3. Get all conflicts for a specific psychological state +SELECT ps.stateName, pc.conflictType, pc.severity, pc.resolution, pc.resolvedDate +FROM PsychologicalState ps +JOIN PsychologicalConflict pc ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego +WHERE ps.id = 2 AND ps.ego = 2 AND ps.superego = 2; + +-- 4. Find behavioral outcomes grouped by psychological state +SELECT ps.stateName, COUNT(bo.outcomeId) as outcomeCount, + STRING_AGG(bo.behavior, '; ') as behaviors +FROM PsychologicalState ps +LEFT JOIN BehavioralOutcome bo ON ps.id = bo.id + AND ps.ego = bo.ego + AND ps.superego = bo.superego +GROUP BY ps.id, ps.ego, ps.superego, ps.stateName +ORDER BY outcomeCount DESC; + +-- 5. Analyze psyche metrics with harmony scores +SELECT ps.stateName, pm.idStrength, pm.egoBalance, pm.superegoRigidity, pm.harmonyScore, + CASE + WHEN pm.harmonyScore >= 80 THEN 'Excellent Balance' + WHEN pm.harmonyScore >= 60 THEN 'Good Balance' + WHEN pm.harmonyScore >= 40 THEN 'Moderate Imbalance' + ELSE 'Significant Imbalance' + END as BalanceAssessment +FROM PsychologicalState ps +JOIN PsycheMetrics pm ON ps.id = pm.id + AND ps.ego = pm.ego + AND ps.superego = pm.superego +ORDER BY pm.harmonyScore DESC; + +-- 6. Identify unresolved conflicts requiring attention +SELECT ps.stateName, pc.conflictType, pc.severity, ps.conflictLevel, + DATEDIFF(day, pc.resolvedDate, GETDATE()) as daysUnresolved +FROM PsychologicalState ps +JOIN PsychologicalConflict pc ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego +WHERE pc.resolvedDate IS NULL +ORDER BY ps.conflictLevel DESC, pc.severity DESC; + +-- ======================================== +-- COMPLEX QUERIES WITH CTEs +-- ======================================== + +-- 7. Comprehensive analysis of each psyche component dominance +WITH ComponentAnalysis AS ( + SELECT id, ego, superego, stateName, conflictLevel, + CASE + WHEN id > ego AND id > superego THEN 'Id-Dominant' + WHEN ego > id AND ego > superego THEN 'Ego-Dominant' + WHEN superego > id AND superego > ego THEN 'Superego-Dominant' + ELSE 'Balanced' + END as DominantComponent, + (id + ego + superego) as TotalPsycheScore + FROM PsychologicalState +) +SELECT DominantComponent, + COUNT(*) as StateCount, + AVG(conflictLevel) as AvgConflictLevel, + AVG(TotalPsycheScore) as AvgTotalScore +FROM ComponentAnalysis +GROUP BY DominantComponent +ORDER BY AvgConflictLevel DESC; + +-- 8. Track conflict resolution success rate by state type +WITH ConflictSummary AS ( + SELECT ps.id, ps.ego, ps.superego, ps.stateName, + COUNT(pc.conflictId) as TotalConflicts, + SUM(CASE WHEN pc.resolvedDate IS NOT NULL THEN 1 ELSE 0 END) as ResolvedConflicts + FROM PsychologicalState ps + LEFT JOIN PsychologicalConflict pc ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego + GROUP BY ps.id, ps.ego, ps.superego, ps.stateName +) +SELECT stateName, TotalConflicts, ResolvedConflicts, + CASE + WHEN TotalConflicts > 0 THEN + CAST(ResolvedConflicts * 100.0 / TotalConflicts AS DECIMAL(5,2)) + ELSE 0 + END as ResolutionRate +FROM ConflictSummary +WHERE TotalConflicts > 0 +ORDER BY ResolutionRate ASC; + +-- 9. Behavioral pattern analysis over time +WITH BehaviorTimeline AS ( + SELECT bo.id, bo.ego, bo.superego, bo.behavior, bo.impact, bo.timestamp, + ROW_NUMBER() OVER (PARTITION BY bo.id, bo.ego, bo.superego ORDER BY bo.timestamp) as BehaviorSequence + FROM BehavioralOutcome bo +) +SELECT ps.stateName, bt.behavior, bt.impact, bt.timestamp, bt.BehaviorSequence +FROM BehaviorTimeline bt +JOIN PsychologicalState ps ON bt.id = ps.id + AND bt.ego = ps.ego + AND bt.superego = ps.superego +ORDER BY bt.id, bt.ego, bt.superego, bt.BehaviorSequence; + +-- 10. Identify critical states requiring immediate attention +WITH CriticalAssessment AS ( + SELECT ps.id, ps.ego, ps.superego, ps.stateName, ps.conflictLevel, + pm.harmonyScore, + COUNT(DISTINCT pc.conflictId) as UnresolvedConflicts + FROM PsychologicalState ps + JOIN PsycheMetrics pm ON ps.id = pm.id + AND ps.ego = pm.ego + AND ps.superego = pm.superego + LEFT JOIN PsychologicalConflict pc ON ps.id = pc.id + AND ps.ego = pc.ego + AND ps.superego = pc.superego + AND pc.resolvedDate IS NULL + GROUP BY ps.id, ps.ego, ps.superego, ps.stateName, ps.conflictLevel, pm.harmonyScore +) +SELECT stateName, conflictLevel, harmonyScore, UnresolvedConflicts, + CASE + WHEN conflictLevel >= 4.5 OR harmonyScore < 40 OR UnresolvedConflicts >= 2 THEN 'CRITICAL - Immediate Intervention' + WHEN conflictLevel >= 3.5 OR harmonyScore < 60 OR UnresolvedConflicts = 1 THEN 'HIGH PRIORITY - Schedule Assessment' + WHEN conflictLevel >= 2.5 OR harmonyScore < 75 THEN 'MODERATE - Monitor Closely' + ELSE 'STABLE - Routine Check-ins' + END as InterventionLevel +FROM CriticalAssessment +ORDER BY + CASE + WHEN conflictLevel >= 4.5 THEN 1 + WHEN harmonyScore < 40 THEN 2 + WHEN UnresolvedConflicts >= 2 THEN 3 + ELSE 4 + END, + conflictLevel DESC; + +-- 11. Psyche component correlation analysis +WITH ComponentMetrics AS ( + SELECT pm.id, pm.ego, pm.superego, + pm.idStrength, pm.egoBalance, pm.superegoRigidity, + ps.conflictLevel + FROM PsycheMetrics pm + JOIN PsychologicalState ps ON pm.id = ps.id + AND pm.ego = ps.ego + AND pm.superego = ps.superego +) +SELECT + AVG(idStrength) as AvgIdStrength, + AVG(egoBalance) as AvgEgoBalance, + AVG(superegoRigidity) as AvgSuperegoRigidity, + AVG(conflictLevel) as AvgConflictLevel, + STDEV(idStrength) as IdVariability, + STDEV(egoBalance) as EgoVariability, + STDEV(superegoRigidity) as SuperegoVariability +FROM ComponentMetrics; + +-- ======================================== +-- DEMONSTRATION OF COMPOSITE KEY BENEFITS +-- ======================================== + +-- Example 1: Cannot insert duplicate composite keys +-- This would fail: +-- INSERT INTO PsychologicalState (id, ego, superego, stateName, conflictLevel) +-- VALUES (1, 1, 1, 'Duplicate State', 2.0); +-- Error: Violation of PRIMARY KEY constraint + +-- Example 2: Can have same individual values, but different combinations +INSERT INTO PsychologicalState (id, ego, superego, stateName, description, conflictLevel, resolutionStrategy) +VALUES (1, 2, 3, 'Unique Combination', 'All individual values exist separately but this combination is new', 2.50, 'Standard approach'); + +-- Example 3: Referential integrity with composite foreign keys +-- This ensures all related records maintain consistency +-- Try to insert a conflict for non-existent state (would fail): +-- INSERT INTO PsychologicalConflict (id, ego, superego, conflictType) +-- VALUES (99, 99, 99, 'Invalid Reference'); +-- Error: Foreign key constraint violation + +-- ======================================== +-- COMPOSITE KEY ADVANTAGES DEMONSTRATION +-- ======================================== + +-- Query showing how composite keys maintain data integrity +SELECT + 'Total Psychological States' as Category, + COUNT(*) as Count +FROM PsychologicalState +UNION ALL +SELECT + 'States with Conflicts', + COUNT(DISTINCT CONCAT(id, '-', ego, '-', superego)) +FROM PsychologicalConflict +UNION ALL +SELECT + 'States with Behavioral Outcomes', + COUNT(DISTINCT CONCAT(id, '-', ego, '-', superego)) +FROM BehavioralOutcome +UNION ALL +SELECT + 'States with Metrics', + COUNT(DISTINCT CONCAT(id, '-', ego, '-', superego)) +FROM PsycheMetrics; + +-- ======================================== +-- CLEANUP (Optional - uncomment to drop tables) +-- ======================================== +/* +DROP TABLE IF EXISTS PsycheMetrics; +DROP TABLE IF EXISTS BehavioralOutcome; +DROP TABLE IF EXISTS PsychologicalConflict; +DROP TABLE IF EXISTS PsychologicalState; +*/