├── README.md ├── image-1.png ├── image-2.png ├── image-3.png ├── image-4.png └── image.png /README.md: -------------------------------------------------------------------------------- 1 | # Relational Database 2 | 3 | - [My MySQL playlist](https://www.youtube.com/playlist?list=PLgH5QX0i9K3qLcx9DvVDWmNJ7riPvxzCD) 4 | - [PSQL Tutorial](https://www.postgresqltutorial.com/) 5 | 6 | ## Table of Contents 7 | 8 | 1. [Introduction to Database](#1-introduction-to-database) 9 | 2. [Relational Database](#2-relational-database) 10 | 3. [Postgres, pgAdmin Installation and Basic Commands](#3-postgres-pgadmin-installation-and-basic-commands) 11 | 4. [Query and SQL](#4-query-and-sql) 12 | 5. [DDL - CREATE, DROP, RENAME Database & TABLE](#5-ddl---create-drop-rename-database--table) 13 | 6. [DML - INSERT RECORDS](#6-dml---insert-records) 14 | 7. [DML - FIND / SELECT RECORDS](#7-dml---find--select-records) 15 | 8. [DML - UPDATE STATEMENT](#8-dml---update-statement) 16 | 9. [DML - UPDATE STATEMENT](#8-dml---update-statement) 17 | 10. [Assignment for practcing CRUD](#10-assignment-for-practcing-crud) 18 | 19 | ## 1. introduction to Database 20 | 21 | PostgresSQL is the most advanced open source Database Management System. 22 | 23 | ### Some important terms realted SQL 24 | 25 | - Data: unorganized & meaningless facts are known as data. example - anis, 101, 3.45, name, gpa, roll 26 | - Information: organized, process & meaningful facts are known as Information. 27 | - Database: An organized collection of related Data table or files for accessign and manipulating Data. Example: college db can have student, teacher table etc. 28 | - Database Management System (DBMS) : Databases are managed by Database Management Systems (DBMS), which allow users to create, read, update, and delete data efficiently. 29 | - SQL: Structured Query Language for making and processing requests to Database. 30 | 31 | ### Advantages & Disadvantages of Database 32 | 33 | - Advantages: faster presentation, easily accessible, update is easy, easily storable 34 | - Disadvantage: security issue, required skill to handle database 35 | 36 | ### Types of Database 37 | 38 | - Relational database: Relational Databases (SQL): Store data in tables with predefined schemas. Ideal for transactions and data integrity. Examples: MySQL, PostgresSQL, Oracle. You need ACID (Atomicity, Consistency, Isolation, Durability) compliance to ensure reliable transactions, which is critical for applications where data integrity and consistency are paramount. 39 | Example: E-commerce transactions, banking, and financial systems. 40 | 41 | Usecase: 42 | E-commerce platforms (order processing, customer management). 43 | Financial applications (banking, trading systems). 44 | Content management systems (blog platforms, CMS). 45 | Enterprise resource planning (ERP) systems. 46 | 47 | - NoSQL Database: Schema less, Handle unstructured or semi-structured data, offering flexibility and scalability. Example: MongoDB, DynamoDB. 48 | Usecase: 49 | 50 | - Choosing Relational vs NoSQL 51 | 52 | Choose Relational Databases When: 53 | Data integrity and consistency are critical. 54 | You need complex queries and relationships. 55 | You require multi-step transactions. 56 | The schema is stable and not expected to change often. 57 | 58 | Choose NoSQL Databases When: 59 | You need high scalability and distributed data across servers. 60 | Data is unstructured, semi-structured, or rapidly evolving. 61 | Performance, speed, and low latency are top priorities. 62 | Your application handles big data or real-time analytics. 63 | 64 | - 3 important elements of RD: field=col, key-field, record=row, value 65 | - field vs record 66 | 67 | ## 2. Relational Database 68 | 69 | ### 2.1 Transaction and ACID Properties 70 | 71 | - A transaction in a database is a sequence of one or more operations performed as a single logical unit of work. These operations are executed together to accomplish a specific task, and they must adhere to the ACID principles (Atomicity, Consistency, Isolation, Durability) to ensure data integrity and reliability. 72 | 73 | ![alt text](image-2.png) 74 | 75 | **ACID** is an acronym that stands for **Atomicity, Consistency, Isolation,** and **Durability**. These principles are crucial for maintaining the reliability, accuracy, and integrity of data in databases, especially in systems that handle multiple transactions. 76 | 77 | Let’s explore each ACID principle with an easy-to-understand example of a simple bank transfer scenario: 78 | 79 | #### **Scenario: Bank Transfer Example** 80 | 81 | Imagine you are transferring $100 from your **Savings Account** to your **Checking Account** using an online banking system. This operation involves two main steps: 82 | 83 | 1. **Deduct $100 from the Savings Account.** 84 | 2. **Add $100 to the Checking Account.** 85 | 86 | To ensure that this transaction is handled correctly, the database needs to adhere to the ACID principles: 87 | 88 | #### **1. Atomicity** 89 | 90 | **Definition:** 91 | Atomicity ensures that all parts of a transaction are completed successfully or none of them are. If any part of the transaction fails, the entire transaction is rolled back, and the system returns to its previous state. 92 | 93 | ![alt text](image-3.png) 94 | 95 | **Example:** 96 | 97 | - In our bank transfer example, both steps (deducting from the savings account and adding to the checking account) must either both happen or not happen at all. 98 | - **If Atomicity is maintained:** If the system crashes after deducting $100 from the savings account but before adding it to the checking account, the entire transaction will be rolled back, and no money will be deducted or added. 99 | - **Without Atomicity:** You could end up with $100 missing from your savings without it being added to your checking, leading to data inconsistency. 100 | 101 | #### **2. Consistency** 102 | 103 | **Definition:** 104 | Consistency ensures that a transaction takes the database from one valid state to another, adhering to all predefined rules and constraints. 105 | 106 | **Example:** 107 | 108 | - The rule here is that the total amount of money across both accounts must remain the same before and after the transaction. 109 | - Another rule: user account balance can not be negative. 110 | - Another rule: not allowing overdraw. 111 | - **If Consistency is maintained:** After the transfer, the combined balance of both accounts should still equal the original total amount (no money is created or lost). 112 | - **Without Consistency:** The accounts might show an incorrect balance, such as money disappearing or being duplicated, violating the bank’s rules. 113 | 114 | #### **3. Isolation** 115 | 116 | **Definition:** 117 | Isolation ensures that multiple transactions occurring at the same time do not affect each other’s execution. Each transaction should act as if it is the only one being processed. 118 | 119 | **Example:** 120 | 121 | - Imagine that while you’re transferring $100, someone else is also transferring money between accounts. 122 | - **If Isolation is maintained:** Your transfer of $100 will occur independently of the other transaction. Even if multiple transfers are happening simultaneously, each will be isolated, preventing any overlap or interference. 123 | - **Without Isolation:** If isolation is not maintained, you could encounter problems like one transaction overwriting the changes of another, resulting in incorrect balances. 124 | 125 | #### **4. Durability** 126 | 127 | **Definition:** 128 | Durability ensures that once a transaction is committed, it is permanently recorded in the database, even in the case of a power failure, crash, or other disasters. 129 | 130 | **Example:** 131 | 132 | - After your $100 transfer is completed, the changes are saved permanently. 133 | - **If Durability is maintained:** Even if there’s a sudden power outage right after your transaction completes, the transfer will not be lost; it’s saved securely in the database. 134 | - **Without Durability:** A completed transaction might be lost due to unforeseen system failures, leading to missing records or incomplete data. 135 | 136 | #### **Putting It All Together:** 137 | 138 | When you initiate a transfer of $100 between your accounts, ACID principles ensure: 139 | 140 | - **Atomicity**: Both deduction and addition happen, or neither happens. 141 | - **Consistency**: The total money across accounts remains accurate. 142 | - **Isolation**: Other simultaneous transfers won’t interfere with your transaction. 143 | - **Durability**: Once completed, your transfer is saved permanently, even if there’s a system crash. 144 | 145 | #### **Conclusion** 146 | 147 | ACID principles are critical for ensuring reliable and consistent database operations, especially in systems where transactions must be processed accurately and safely, such as financial systems, booking platforms, and inventory management. By adhering to ACID, databases protect data integrity and provide a reliable user experience, even in complex and high-stakes environments. 148 | 149 | ### 2.2 Types of Key 150 | 151 | - Primary key: unique key. in a table you will have one primary key. 152 | - foreign key: one table's primary key - same other's table general key(foreign key). It is used to make relation between tables. In one table there can be multiple foreign keys. 153 | - composite key: when you need to use 2 or more keys to identify a record 154 | - Priamry key vs Foreign key 155 | 156 | In a relational database, **keys** are crucial for organizing and managing data. They help ensure data integrity and establish relationships between different tables. In the context of an e-commerce database, different types of keys can be used to uniquely identify records, establish connections between tables, and enforce rules. 157 | 158 | ########### **Types of Keys in a Relational Database:** 159 | 160 | 1. **Primary Key** 161 | 2. **Foreign Key** 162 | 3. **Composite Key** 163 | 4. **Unique Key** 164 | 5. **Candidate Key** 165 | 6. **Alternate Key** 166 | 167 | Let's explore each type of key with examples relevant to an e-commerce database: 168 | 169 | ########### **1. Primary Key** 170 | 171 | **Definition:** 172 | A **primary key** is a unique identifier for a record in a table. It ensures that each record in the table is unique and can be referenced unambiguously. 173 | 174 | **Example:** 175 | 176 | - **Table: Customers** 177 | - `CustomerID` (Primary Key): Uniquely identifies each customer in the database. 178 | 179 | - **Table: Products** 180 | - `ProductID` (Primary Key): Uniquely identifies each product in the catalog. 181 | 182 | ```sql 183 | CREATE TABLE Customers ( 184 | CustomerID INT PRIMARY KEY, 185 | Name VARCHAR(255), 186 | Email VARCHAR(255) 187 | ); 188 | 189 | CREATE TABLE Products ( 190 | ProductID INT PRIMARY KEY, 191 | ProductName VARCHAR(255), 192 | Price DECIMAL(10, 2) 193 | ); 194 | ``` 195 | 196 | ########### **2. Foreign Key** 197 | 198 | **Definition:** 199 | A **foreign key** is a field (or collection of fields) in one table that uniquely identifies a row in another table. It creates a relationship between the two tables, enforcing referential integrity. 200 | 201 | **Example:** 202 | 203 | - **Table: Orders** 204 | - `OrderID` (Primary Key) 205 | - `CustomerID` (Foreign Key referencing Customers table): Links each order to the corresponding customer. 206 | 207 | ```sql 208 | CREATE TABLE Orders ( 209 | OrderID INT PRIMARY KEY, 210 | OrderDate DATE, 211 | CustomerID INT, 212 | FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) 213 | ); 214 | ``` 215 | 216 | ########## **3. Composite Key** 217 | 218 | **Definition:** 219 | A **composite key** is a primary key that consists of two or more columns used together to uniquely identify a record in a table. 220 | 221 | **Example:** 222 | 223 | - **Table: OrderDetails** 224 | - `OrderID` + `ProductID` (Composite Key): Together, these two fields uniquely identify each line item in an order. 225 | 226 | ```sql 227 | CREATE TABLE OrderDetails ( 228 | OrderID INT, 229 | ProductID INT, 230 | Quantity INT, 231 | PRIMARY KEY (OrderID, ProductID), 232 | FOREIGN KEY (OrderID) REFERENCES Orders(OrderID), 233 | FOREIGN KEY (ProductID) REFERENCES Products(ProductID) 234 | ); 235 | ``` 236 | 237 | ######### **4. Unique Key** 238 | 239 | **Definition:** 240 | A **unique key** ensures that all values in a column or a group of columns are unique across the entire table. Unlike primary keys, a table can have multiple unique keys, and they can accept a null value (but only one null if it's a single column unique key). 241 | 242 | **Example:** 243 | 244 | - **Table: Customers** 245 | - `Email` (Unique Key): Ensures that no two customers can have the same email address. 246 | 247 | ```sql 248 | CREATE TABLE Customers ( 249 | CustomerID INT PRIMARY KEY, 250 | Name VARCHAR(255), 251 | Email VARCHAR(255) UNIQUE 252 | ); 253 | ``` 254 | 255 | ######## **5. Candidate Key** 256 | 257 | **Definition:** 258 | A **candidate key** is a column, or a set of columns, that can uniquely identify any database record without referring to any other data. Every table can have one or more candidate keys, and out of these, one is selected as the primary key. 259 | 260 | **Example:** 261 | 262 | - **Table: Customers** 263 | - Both `CustomerID` and `Email` could be candidate keys, but typically, one (e.g., `CustomerID`) is chosen as the primary key. 264 | 265 | ####### **6. Alternate Key** 266 | 267 | **Definition:** 268 | An **alternate key** is any candidate key that is not chosen as the primary key. It is an alternative way of uniquely identifying rows in a table. 269 | 270 | **Example:** 271 | 272 | - **Table: Customers** 273 | - If `CustomerID` is chosen as the primary key, `Email` could be an alternate key. 274 | 275 | ###### **Practical Example in an E-commerce Database:** 276 | 277 | ```sql 278 | CREATE TABLE Customers ( 279 | CustomerID INT PRIMARY KEY, 280 | Name VARCHAR(255), 281 | Email VARCHAR(255) UNIQUE 282 | ); 283 | 284 | CREATE TABLE Products ( 285 | ProductID INT PRIMARY KEY, 286 | ProductName VARCHAR(255), 287 | Price DECIMAL(10, 2) 288 | ); 289 | 290 | CREATE TABLE Orders ( 291 | OrderID INT PRIMARY KEY, 292 | OrderDate DATE, 293 | CustomerID INT, 294 | FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) 295 | ); 296 | 297 | CREATE TABLE OrderDetails ( 298 | OrderID INT, 299 | ProductID INT, 300 | Quantity INT, 301 | PRIMARY KEY (OrderID, ProductID), 302 | FOREIGN KEY (OrderID) REFERENCES Orders(OrderID), 303 | FOREIGN KEY (ProductID) REFERENCES Products(ProductID) 304 | ); 305 | ``` 306 | 307 | ##### **Explanation:** 308 | 309 | - **Customers Table**: 310 | - `CustomerID` is the primary key, ensuring each customer is unique. 311 | - `Email` is a unique key, preventing duplicate emails. 312 | 313 | - **Products Table**: 314 | - `ProductID` is the primary key, uniquely identifying each product. 315 | 316 | - **Orders Table**: 317 | - `OrderID` is the primary key, and `CustomerID` is a foreign key, linking each order to a specific customer. 318 | 319 | - **OrderDetails Table**: 320 | - The composite key (`OrderID`, `ProductID`) ensures that each combination of order and product is unique within the table. 321 | - Foreign keys `OrderID` and `ProductID` link to the Orders and Products tables, respectively, establishing relationships. 322 | 323 | #### **Summary:** 324 | 325 | In an e-commerce database: 326 | 327 | - **Primary keys** uniquely identify records. 328 | - **Foreign keys** create relationships between tables, ensuring referential integrity. 329 | - **Composite keys** can uniquely identify records based on multiple columns. 330 | - **Unique keys** ensure that specific columns, like emails, contain unique values. 331 | - **Candidate keys** are potential primary keys, and the one not chosen is an **alternate key**. 332 | 333 | Using these keys effectively helps maintain a well-organized, reliable, and scalable database structure for an e-commerce application. 334 | 335 | ### 2.3 ER Model 336 | 337 | ### **What is an ER Model (Entity-Relationship Model)?** 338 | 339 | The **Entity-Relationship (ER) Model** is a high-level data modeling technique used to visually represent the structure of a database. It helps in designing databases by depicting entities (objects) and the relationships between them. The ER Model provides a clear, graphical way to organize data, making it easier to understand how different data elements relate to each other within a system. 340 | 341 | ### **Key Components of the ER Model:** 342 | 343 | 1. **Entities** 344 | 2. **Attributes** 345 | 3. **Relationships** 346 | 4. **Keys** 347 | 5. **ER Diagram (ERD)** 348 | 349 | ### **1. Entities** 350 | 351 | **Definition:** 352 | An **entity** represents a real-world object or concept that is distinguishable from other objects. In the context of a database, entities are often modeled as tables. 353 | 354 | **Examples:** 355 | 356 | - **Customer**: Represents people who make purchases. 357 | - **Product**: Represents items available for sale. 358 | - **Order**: Represents transactions made by customers. 359 | 360 | ### **2. Attributes** 361 | 362 | **Definition:** 363 | **Attributes** are properties or characteristics of an entity. In a table, attributes are represented as columns. 364 | 365 | **Examples:** 366 | 367 | - **Customer Entity**: Attributes might include `CustomerID`, `Name`, `Email`. 368 | - **Product Entity**: Attributes might include `ProductID`, `ProductName`, `Price`. 369 | - **Order Entity**: Attributes might include `OrderID`, `OrderDate`, `CustomerID`. 370 | 371 | ### **3. Relationships** 372 | 373 | **Definition:** 374 | **Relationships** define how entities are connected to each other. They represent the logical association between entities. 375 | 376 | **Types of Relationships:** 377 | 378 | - **One-to-One (1:1)**: Each instance of an entity relates to exactly one instance of another entity. 379 | - **One-to-Many (1:N)**: One instance of an entity relates to multiple instances of another entity. 380 | - **Many-to-Many (M:N)**: Multiple instances of an entity relate to multiple instances of another entity. 381 | 382 | **Example Relationships:** 383 | 384 | - A **Customer** can place multiple **Orders** (One-to-Many). 385 | - An **Order** can include multiple **Products** (Many-to-Many). 386 | 387 | ### **4. Keys** 388 | 389 | **Definition:** 390 | **Keys** are attributes that uniquely identify entities and define relationships between entities. 391 | 392 | - **Primary Key**: Uniquely identifies each record within an entity. 393 | - **Foreign Key**: Establishes a link between two entities. 394 | 395 | ### **5. ER Diagram (ERD)** 396 | 397 | **Definition:** 398 | An **Entity-Relationship Diagram (ERD)** is a visual representation of the ER Model. It uses shapes like rectangles, ovals, and diamonds to represent entities, attributes, and relationships. 399 | 400 | **Components of an ER Diagram:** 401 | 402 | - **Rectangles** represent entities. 403 | - **Ovals** represent attributes. 404 | - **Diamonds** represent relationships. 405 | - **Lines** connect entities with their relationships and attributes. 406 | 407 | ### **Example ER Diagram for an E-commerce System:** 408 | 409 | Let's look at a simple ER Diagram for an e-commerce system with three entities: **Customer**, **Order**, and **Product**. 410 | 411 | ```plaintext 412 | +----------------+ +----------------+ +----------------+ 413 | | Customer | | Order | | Product | 414 | +----------------+ +----------------+ +----------------+ 415 | | CustomerID (PK)| | OrderID (PK) | | ProductID (PK) | 416 | | Name | | OrderDate | | ProductName | 417 | | Email | | CustomerID (FK)| | Price | 418 | +----------------+ +----------------+ +----------------+ 419 | | | | 420 | | (places) | (contains) | 421 | +-------------------------+----------------------------+ 422 | ``` 423 | 424 | ### **Explanation of the ER Diagram:** 425 | 426 | - **Entities**: `Customer`, `Order`, and `Product`. 427 | - **Attributes**: Each entity has attributes like `CustomerID`, `Name`, `Email` for Customer. 428 | - **Relationships**: 429 | - **Customer to Order**: One-to-Many (`Customer` places multiple `Orders`). 430 | - **Order to Product**: Many-to-Many (`Order` can contain multiple `Products`). 431 | 432 | ### **Benefits of Using the ER Model:** 433 | 434 | 1. **Clarity and Visualization**: ER Diagrams provide a clear and visual representation of data, making it easy for stakeholders to understand the database structure. 435 | 2. **Design Blueprint**: Serves as a blueprint for designing and implementing a database. 436 | 3. **Identifies Relationships**: Helps identify relationships and dependencies between different entities, improving data organization. 437 | 4. **Improves Communication**: Enhances communication between database designers, developers, and business stakeholders by providing a common point of reference. 438 | 5. **Ensures Data Integrity**: Clearly defined relationships and constraints help maintain data integrity and reduce redundancy. 439 | 440 | ## 3. Postgres, pgAdmin Installation and Basic Commands 441 | 442 | - [Download from here](https://www.postgresql.org/download/) 443 | - GUI: [pgAdmin download](https://www.pgadmin.org/download/) 444 | - CLI: SQL Shell (PSQL) setup 445 | - using in terminal: psql + Enter or psql -u postgres; you may need to copy and set the path to the environment variables 446 | 447 | ### Basic commands for Postgres 448 | 449 | - App <=> DBMS <=> Database 450 | - DBMS - XAMPP (Cross platform Apache, MySQL, PHP Perl) 451 | - first download and install the DBMS - [PostgreSQL](https://www.postgresql.org/download/) 452 | - after downloading check the version: `psql -version` 453 | - type `psql` in the command line 454 | - some common commands for Postgres: These are just a few examples of psql commands. You can find more commands and options by typing `\?` in the psql command-line interface to display the help menu. 455 | 456 | 1. **Connect to a Database**: Connect to a specific database. 457 | 458 | ```bash 459 | \c dbname 460 | ``` 461 | 462 | Replace `dbname` with the name of the database you want to connect to. 463 | 464 | 2. **List Databases**: List all databases on the server. 465 | 466 | ```bash 467 | \l 468 | ``` 469 | 470 | 3. **List Tables**: List all tables in the current database. 471 | 472 | ```bash 473 | \dt 474 | ``` 475 | 476 | 4. **Describe Table**: Display the structure of a specific table. 477 | 478 | ```bash 479 | \d table_name 480 | ``` 481 | 482 | Replace `table_name` with the name of the table you want to describe. 483 | 484 | 5. **Quit psql**: Exit the psql command-line interface. 485 | 486 | ```bash 487 | \q 488 | ``` 489 | 490 | 6. **Execute SQL File**: Execute SQL commands from a file. 491 | 492 | ```bash 493 | \i path/to/file.sql 494 | ``` 495 | 496 | Replace `path/to/file.sql` with the path to your SQL file. 497 | 498 | 7. **Toggle Expanded Display**: Toggle expanded display mode (shows long lines as multiple lines). 499 | 500 | ```bash 501 | \x 502 | ``` 503 | 504 | 8. **Show Version**: Display the version of PostgreSQL. 505 | 506 | ```bash 507 | SELECT version(); 508 | ``` 509 | 510 | or 511 | 512 | ```bash 513 | SELECT version; 514 | ``` 515 | 516 | 9. **List Roles**: List all roles (users) on the server. 517 | 518 | ```bash 519 | \du 520 | ``` 521 | 522 | 10. **Change Password**: Change the password for the current user. 523 | 524 | ```bash 525 | \password 526 | ``` 527 | 528 | ### Database, Schema, Table 529 | 530 | - Database => Schema => Table 531 | 532 | ## 4. Query and SQL 533 | 534 | ### Query 535 | 536 | A query in the context of databases refers to a request for data or information from a database table or combination of tables. It is essentially a command that is written in a structured query language (SQL) or a similar language to retrieve specific information from a database. Query Language: QUEL, QBE, SQL (Structured Query Language) 537 | 538 | Here are some common types of queries: 539 | 540 | 1. **SELECT Query**: The most commonly used type of query, the SELECT query retrieves data from one or more tables based on specified criteria. It can be used to fetch entire rows, specific columns, or calculated values. 541 | 542 | Example: 543 | 544 | ```sql 545 | SELECT * FROM customers; 546 | ``` 547 | 548 | 2. **INSERT Query**: This type of query is used to add new records (rows) to a table. 549 | 550 | Example: 551 | 552 | ```sql 553 | INSERT INTO customers (name, email) VALUES ('John Doe', 'john@example.com'); 554 | ``` 555 | 556 | 3. **UPDATE Query**: An UPDATE query is used to modify existing records in a table. 557 | 558 | Example: 559 | 560 | ```sql 561 | UPDATE products SET price = 20.99 WHERE id = 123; 562 | ``` 563 | 564 | 4. **DELETE Query**: DELETE queries are used to remove records from a table based on specified conditions. 565 | 566 | Example: 567 | 568 | ```sql 569 | DELETE FROM orders WHERE order_date < '2023-01-01'; 570 | ``` 571 | 572 | 5. **JOIN Query**: JOIN queries are used to combine rows from two or more tables based on related columns between them. 573 | 574 | Example: 575 | 576 | ```sql 577 | SELECT orders.order_id, customers.name 578 | FROM orders 579 | JOIN customers ON orders.customer_id = customers.customer_id; 580 | ``` 581 | 582 | 6. **CREATE Query**: CREATE queries are used to create new database objects such as tables, indexes, or views. 583 | 584 | Example: 585 | 586 | ```sql 587 | CREATE TABLE employees ( 588 | id INT PRIMARY KEY, 589 | name VARCHAR(100), 590 | department VARCHAR(100) 591 | ); 592 | ``` 593 | 594 | 7. **ALTER Query**: ALTER queries are used to modify the structure of existing database objects such as tables, indexes, or views. 595 | 596 | Example: 597 | 598 | ```sql 599 | ALTER TABLE employees ADD COLUMN salary DECIMAL(10, 2); 600 | ``` 601 | 602 | 8. **DROP Query**: DROP queries are used to remove database objects such as tables, indexes, or views from the database. 603 | 604 | Example: 605 | 606 | ```sql 607 | DROP TABLE employees; 608 | ``` 609 | 610 | ### SQL 611 | 612 | - Features of SQL 613 | - Statements are not case sensitive (SELECT / select) 614 | - every statement mustbe end with semicolon 615 | - SQL Statements types 616 | - **DML (DATA MANIPULATION LANGUAGE):** CRUD - SELECT, INSERT, UPDATE, DELETE 617 | - **DDL (DATA DEFINITION LANGUAGE):** CREATE, ALTER, DROP 618 | 619 | ### DDL (Data Definition Language) 620 | 621 | - SHOW DATABASE; 622 | - CREATE DATABASE college; 623 | - DROP DATABASE college; 624 | - CREATE, DROP, SHOW DATABASE 625 | 626 | ## 5. DDL - CREATE, DROP, RENAME Database & TABLE 627 | 628 | - **commands are not case sensitive** 629 | - help for psql commands `\?` 630 | - List all the PSQL Database `\l` or in pgAdmin `SELECT datname FROM pg_database;` 631 | - Create Database `CREATE DATABASE YourDatabaseName;` `CREATE DATABASE ecommerce` 632 | - Connect to PSQL Database `\c databaseName` 633 | - Drop Database `DROP DATABASE YourDatabaseName;` 634 | - list all the tables: `\d tableName` 635 | 636 | - syntax for creating table 637 | 638 | ```sql 639 | -- Drop the existing order_products table for mysql 640 | DROP TABLE IF EXISTS table_name; 641 | 642 | CREATE TABLE table_name( 643 | col_name1 data_type(size), 644 | col_name2 data_type(size), 645 | PRIMARY KEY(col_name) 646 | ... 647 | ); 648 | 649 | -- Drop the existing order_products table for psql 650 | DROP TABLE IF EXISTS table_name; 651 | 652 | CREATE TABLE table_name( 653 | col_name1 data_type(size) PRIMARY KEY, 654 | col_name2 data_type(size), 655 | ... 656 | ); 657 | ``` 658 | 659 | - RENAME TABLE old_table_name TO new_table_name; (mysql) 660 | - ALTER TABLE current_table_name RENAME TO new_table_name; (psql) 661 | - DROP TABLE table_name; 662 | 663 | ### Ecommerce Project: Create Tables 664 | 665 | For an e-commerce application, you typically need CRUD operations for various entities such as users, products, orders, and categories. Here's an outline of the CRUD operations you might need for each entity: 666 | 667 | 1. **Users**: 668 | - Create: Register a new user. 669 | - Read: Retrieve user information by ID or username. 670 | - Update: Update user information (e.g., profile details, password). 671 | - Delete: Remove a user account. 672 | 673 | 2. **Products**: 674 | - Create: Add a new product to the catalog. 675 | - Read: Retrieve product information by ID, name, category, etc. 676 | - Update: Modify product details (e.g., name, price, description). 677 | - Delete: Remove a product from the catalog. 678 | 679 | 3. **Orders**: 680 | - Create: Place a new order for a user. 681 | - Read: Retrieve order information by ID, user, date, etc. 682 | - Update: Update order status (e.g., processing, shipped, delivered). 683 | - Delete: Cancel an order. 684 | 685 | 4. **Categories**: 686 | - Create: Create a new product category. 687 | - Read: Retrieve category information by ID or name. 688 | - Update: Modify category details (e.g., name, description). 689 | - Delete: Delete a category and optionally reassign products to another category. 690 | 691 | These operations can be implemented using SQL queries or ORM (Object-Relational Mapping) frameworks depending on your technology stack. Additionally, you may need additional operations such as search, filtering, and pagination to enhance the functionality of your e-commerce application. 692 | 693 | - here's an example of SQL commands to create tables for the entities mentioned: 694 | 695 | - **Users**: 696 | 697 | ```sql 698 | 699 | 700 | CREATE TABLE Users ( 701 | userId SERIAL PRIMARY KEY, 702 | name VARCHAR(100) NOT NULL, 703 | email VARCHAR(100) UNIQUE NOT NULL, 704 | password VARCHAR(255) NOT NULL, 705 | address VARCHAR(255), 706 | image VARCHAR(255), 707 | isAdmin BOOLEAN DEFAULT FALSE, 708 | isBanned BOOLEAN DEFAULT FALSE, 709 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 710 | 711 | ); 712 | 713 | 714 | ALTER TABLE users 715 | 716 | ADD COLUMN isAdmin BOOLEAN DEFAULT FALSE, 717 | ADD COLUMN isBanned BOOLEAN DEFAULT FALSE; 718 | 719 | ``` 720 | 721 | ```sql 722 | 723 | -- Drop the existing order_products table 724 | 725 | DROP TABLE IF EXISTS users; 726 | 727 | CREATE TABLE users ( 728 | userId SERIAL PRIMARY KEY, 729 | name VARCHAR(100) NOT NULL, 730 | email VARCHAR(100) UNIQUE NOT NULL, 731 | password VARCHAR(255) NOT NULL, 732 | address VARCHAR(255), 733 | image VARCHAR(255), 734 | isAdmin BOOLEAN DEFAULT FALSE, 735 | isBanned BOOLEAN DEFAULT FALSE, 736 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 737 | ); 738 | 739 | ``` 740 | 741 | - SERIAL: In PostgreSQL, SERIAL is a pseudo data type that automatically generates a sequence of integers for each row inserted into the table. When you define a column as SERIAL, PostgreSQL will automatically create a sequence object and associate it with the column. This sequence generates unique integer values for the column whenever a new row is inserted into the table. 742 | 743 | - Image type: if you're storing the actual image files in the database, you might consider using a BYTEA (byte array) data type, which is suitable for storing binary data such as images. In some databases, there are specific data types designed for storing large binary objects (LOBs) like images, such as BLOB (Binary Large Object) in MySQL or BYTEA in PostgreSQL. 744 | 745 | - verify table creation: `\d tableName` 746 | 747 | - **Using UUID (Universal Unique Identifier) / GUID (Globally Unique Identifier)** 748 | `userId UUID PRIMARY KEY DEFAULT uuid_generate_v4(),` 749 | 750 | ```sql 751 | 752 | -- Drop the existing order_products table 753 | 754 | DROP TABLE IF EXISTS users; 755 | 756 | CREATE TABLE users ( 757 | userId UUID PRIMARY KEY DEFAULT uuid_generate_v4(), 758 | name VARCHAR(100) NOT NULL, 759 | email VARCHAR(100) UNIQUE NOT NULL, 760 | password VARCHAR(255) NOT NULL, 761 | address VARCHAR(255), 762 | image VARCHAR(255), 763 | isAdmin BOOLEAN DEFAULT FALSE, 764 | isBanned BOOLEAN DEFAULT FALSE, 765 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 766 | ); 767 | 768 | ``` 769 | 770 | To ensure that the `uuid-ossp` extension is installed and enabled in your PostgreSQL database, you can follow these steps: 771 | 772 | 1. Connect to your PostgreSQL database using a client tool or command-line interface that supports executing SQL commands. 773 | 774 | 2. Check if the `uuid-ossp` extension is already installed by running the following SQL command: 775 | 776 | ```sql 777 | SELECT * FROM pg_extension WHERE extname = 'uuid-ossp'; 778 | ``` 779 | 780 | 3. If the extension is not installed, you can install it by running the following SQL command: 781 | 782 | ```sql 783 | CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; 784 | ``` 785 | 786 | This command will install the `uuid-ossp` extension if it's not already installed. If you encounter an error indicating that you don't have permission to create extensions, you may need to perform this action as a superuser or ask your database administrator for assistance. 787 | 788 | 4. Once the extension is installed, you can enable it for your current database by running the following SQL command: 789 | 790 | ```sql 791 | CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA public; 792 | ``` 793 | 794 | Replace `public` with the name of the schema where you want to enable the extension if you're using a different schema. 795 | 796 | 5. After enabling the extension, you can verify that it's enabled by running the first SQL command again: 797 | 798 | ```sql 799 | SELECT * FROM pg_extension WHERE extname = 'uuid-ossp'; 800 | ``` 801 | 802 | You should see a row indicating that the `uuid-ossp` extension is now installed and enabled in your database. 803 | 804 | - **Categories**: 805 | 806 | ```sql 807 | 808 | DROP TABLE IF EXISTS categories; 809 | CREATE TABLE categories ( 810 | categoryID INT PRIMARY KEY AUTO_INCREMENT, 811 | name VARCHAR(100) UNIQUE NOT NULL, 812 | description TEXT 813 | ); 814 | ``` 815 | 816 | ```sql 817 | 818 | DROP TABLE IF EXISTS categories; 819 | CREATE TABLE categories ( 820 | categoryID SERIAL PRIMARY KEY, 821 | name VARCHAR(100) UNIQUE NOT NULL, 822 | slug VARCHAR(100) UNIQUE NOT NULL, 823 | description TEXT 824 | ); 825 | 826 | DROP TABLE IF EXISTS categories; 827 | CREATE TABLE categories ( 828 | categoryId UUID PRIMARY KEY DEFAULT uuid_generate_v4(), 829 | name VARCHAR(100) UNIQUE NOT NULL, 830 | slug VARCHAR(100) UNIQUE NOT NULL, 831 | description TEXT 832 | ); 833 | ``` 834 | 835 | - **Products**: 836 | 837 | ```sql 838 | 839 | DROP TABLE IF EXISTS products; 840 | CREATE TABLE products ( 841 | productID INT PRIMARY KEY AUTO_INCREMENT, 842 | name VARCHAR(255) NOT NULL, 843 | description TEXT, 844 | price DECIMAL(10, 2) NOT NULL, 845 | categoryID INT, 846 | FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID), 847 | createdAt DATETIME DEFAULT CURRENT_TIMESTAMP 848 | ); 849 | ``` 850 | 851 | ```sql 852 | 853 | DROP TABLE IF EXISTS products; 854 | CREATE TABLE products ( 855 | productID SERIAL PRIMARY KEY, 856 | name VARCHAR(255) NOT NULL, 857 | slug VARCHAR(255) NOT NULL, 858 | description TEXT, 859 | price DECIMAL(10, 2) NOT NULL, 860 | quantity INT DEFAULT 0, 861 | sold INT DEFAULT 0, 862 | image VARCHAR(255), 863 | shipping BOOLEAN, 864 | categoryID INT REFERENCES categories(categoryID), -- Combined with foreign key constraint 865 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 866 | ); 867 | 868 | ``` 869 | 870 | ```sql 871 | DROP TABLE IF EXISTS products; 872 | CREATE TABLE products ( 873 | productId UUID PRIMARY KEY DEFAULT uuid_generate_v4(), 874 | name VARCHAR(255) NOT NULL, 875 | slug VARCHAR(255) NOT NULL, 876 | description TEXT, 877 | price DECIMAL(10, 2) NOT NULL, 878 | quantity INT DEFAULT 0, 879 | sold INT DEFAULT 0, 880 | image VARCHAR(255), 881 | shipping BOOLEAN, 882 | categoryID UUID REFERENCES categories(categoryID), -- Combined with foreign key constraint 883 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 884 | ); 885 | ``` 886 | 887 | - `DECIMAL(10, 2)`: This specifies the data type of the column. `DECIMAL` is a fixed-point number with a specified precision and scale. In this case, `(10, 2)` indicates that the column can store up to 10 digits in total, with 2 digits reserved for the fractional part (decimal places). 888 | - `NOT NULL`: This constraint ensures that the column cannot contain null values, meaning every row must have a valid price value. 889 | 890 | So, `Price DECIMAL(10, 2) NOT NULL` means that the `Price` column will store decimal numbers with up to 10 digits in total, where 2 digits are reserved for the fractional part (e.g., cents). Additionally, it ensures that the `Price` column cannot be null, meaning it must always contain a valid price value. 891 | 892 | - **Orders**: 893 | 894 | ```sql 895 | CREATE TABLE orders ( 896 | OrderID INT PRIMARY KEY AUTO_INCREMENT, 897 | UserID INT, 898 | OrderDate DATETIME DEFAULT CURRENT_TIMESTAMP, 899 | status VARCHAR(20) DEFAULT 'Pending', 900 | FOREIGN KEY (UserID) REFERENCES Users(UserID) 901 | ); 902 | ``` 903 | 904 | ```sql 905 | 906 | -- Create the orders table (without junction table) 907 | 908 | CREATE TABLE orders ( 909 | orderId UUID PRIMARY KEY DEFAULT uuid_generate_v4(), 910 | orderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 911 | status VARCHAR(20) DEFAULT 'Pending', 912 | 913 | userID UUID REFERENCES Users(UserID), 914 | payment JSONB, -- Assuming payment details are stored as JSON 915 | productIDs UUID[], -- Array of product IDs 916 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 917 | ); 918 | 919 | or 920 | 921 | CREATE TYPE order_status AS ENUM ('Pending', 'Processing', 'Shipped', 'Delivered'); 922 | CREATE TABLE orders ( 923 | orderId SERIAL PRIMARY KEY, 924 | orderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 925 | status order_status DEFAULT 'Pending', 926 | payment JSONB, 927 | userId INT REFERENCES users(userId), 928 | products JSONB, -- denormalize the data and store product information directly 929 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 930 | ); 931 | 932 | -- with the junction table : normalize and no direct access to the table without foreign key 933 | CREATE TYPE order_status AS ENUM ('Pending', 'Processing', 'Shipped', 'Delivered'); 934 | CREATE TABLE orders ( 935 | orderId UUID PRIMARY KEY DEFAULT uuid_generate_v4(), 936 | orderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 937 | status order_status DEFAULT 'Pending', 938 | userID UUID REFERENCES users(userID) 939 | ); 940 | 941 | 942 | -- Create the junction table 943 | 944 | CREATE TABLE order_products ( 945 | orderID UUID REFERENCES orders(orderID), 946 | productID UUID REFERENCES products(productID), 947 | quantity INT, 948 | PRIMARY KEY (orderID, productID) 949 | ); 950 | 951 | ``` 952 | 953 | - you can create your own type: `CREATE TYPE order_status AS ENUM ('Pending', 'Processing', 'Shipped', 'Delivered');` 954 | 955 | ### ALTER, ADD & DROP 956 | 957 | - Add a new column to the table 958 | 959 | ```sql 960 | ALTER TABLE TableName 961 | ADD NewColumn DATA_TYPE(SIZE); 962 | 963 | ALTER TABLE Students 964 | ADD Hobby VARCHAR(100) DEFAULT 'Travelling'; 965 | 966 | ALTER TABLE Users 967 | ADD COLUMN isAdmin BOOLEAN DEFAULT FALSE, 968 | ADD COLUMN isBanned BOOLEAN DEFAULT FALSE; 969 | 970 | ``` 971 | 972 | - To delete a column or change the data type of a column from a table in SQL, you can use the `ALTER TABLE` statement with the `DROP COLUMN` clause. Here's the basic syntax: 973 | 974 | ```sql 975 | ALTER TABLE table_name 976 | DROP COLUMN column_name; 977 | 978 | ALTER TABLE table_name 979 | ALTER COLUMN column_name new_data_type; 980 | ``` 981 | 982 | Replace `table_name` with the name of your table and `column_name` with the name of the column you want to delete. 983 | 984 | For example, if you want to delete a column named `email` from a table named `users`, you would execute: 985 | 986 | ```sql 987 | ALTER TABLE users 988 | DROP COLUMN email; 989 | 990 | ALTER TABLE students 991 | ALTER COLUMN age FLOAT; 992 | ``` 993 | 994 | Keep in mind that dropping a column will permanently remove it and all its data from the table, so be sure to use this operation carefully. Also, make sure to back up your data before performing any alterations to your database schema. 995 | 996 | ### Truncate Table 997 | 998 | - Truncate table will not delete entire table just the records 999 | `TRUNCATE TABLE student_details` vs `DROP TABLE student_details` 1000 | 1001 | ## 6. DML - INSERT RECORDS 1002 | 1003 | - syntax for inserting records 1004 | 1005 | ```sql 1006 | -- for instering one record 1007 | INSERT INTO TABLE_NAME(COL1,COL2,...COLN) 1008 | VALUES 1009 | (VAL1, VAL2, ...VALN); 1010 | 1011 | -- for instering one record with shortcut 1012 | INSERT INTO TABLE_NAME 1013 | VALUES 1014 | (VAL1, VAL2, ...VALN); 1015 | 1016 | -- for instering multiple records 1017 | INSERT INTO TABLE_NAME 1018 | VALUES 1019 | (VAL1, VAL2, ...VALN), 1020 | (VAL1, VAL2, ...VALN), 1021 | .... 1022 | (VAL1, VAL2, ...VALN); 1023 | ``` 1024 | 1025 | ### An example of SQL commands to insert data into the tables we created 1026 | 1027 | - **Inserting data into the Users table**: 1028 | 1029 | ```sql 1030 | 1031 | INSERT INTO users (name, email, password, address, image, isAdmin, isBanned) 1032 | VALUES 1033 | ('John Doe', 'john@example.com', 'password123', '123 Main St', 'profile.jpg', TRUE, FALSE), 1034 | ('Alice Smith', 'alice@example.com', 'password456', '456 Elm St', 'avatar.png', FALSE, FALSE), 1035 | ('Bob Johnson', 'bob@example.com', 'password789', '789 Oak St', NULL, FALSE, TRUE), 1036 | ('Emily Davis', 'emily@example.com', 'passwordabc', NULL, 'default.jpg', FALSE, FALSE), 1037 | ('Michael Brown', 'michael@example.com', 'passwordxyz', '567 Pine St', 'user.png', TRUE, FALSE); 1038 | 1039 | -- or 1040 | INSERT INTO users (name, email, password, address, image, isAdmin, isBanned,createdAt) 1041 | VALUES 1042 | ('John Doe', 'john@example.com', 'password123', '123 Main St', 'profile.jpg', TRUE, FALSE,CURRENT_TIMESTAMP), 1043 | ``` 1044 | 1045 | - **Inserting data into the Categories table**: 1046 | 1047 | ```sql 1048 | INSERT INTO categories (name, slug, description) 1049 | VALUES 1050 | ('Electronics', 'electronics', 'Electronic devices and accessories'), 1051 | ('Clothing', 'clothing', 'Apparel and fashion accessories'), 1052 | ('Books', 'books', 'Fiction and non-fiction literature'), 1053 | ('Home Decor', 'home-decor', 'Decorative items for the home'), 1054 | ('Toys', 'toys', 'Children''s toys and games'); 1055 | ``` 1056 | 1057 | - **Inserting data into the Products table**: 1058 | 1059 | ```sql 1060 | INSERT INTO products (name, description, price, quantity, categoryID, createdAt) 1061 | VALUES 1062 | ('Product 1 Name', 'Product 1 Description', 10.99, 100, 1, NOW()), 1063 | ('Product 2 Name', 'Product 2 Description', 19.99, 50, 2, NOW()), 1064 | -- Add more products here... 1065 | ('Product 20 Name', 'Product 20 Description', 5.99, 200, 4, NOW()); 1066 | 1067 | 1068 | -- for serial data 1069 | INSERT INTO products (name, slug, description, price, quantity, sold, image, shipping, categoryID, createdAt) 1070 | VALUES 1071 | ('Laptop', 'laptop', 'High-performance laptop with SSD storage', 999.99, 50, 10, 'laptop.jpg', TRUE, 1, NOW()), 1072 | ('Smartphone', 'smartphone', 'Latest smartphone model with 5G connectivity', 699.99, 100, 30, 'smartphone.jpg', TRUE, 1, NOW()), 1073 | ('T-shirt', 't-shirt', 'Cotton t-shirt with trendy design', 19.99, 200, 80, 't-shirt.jpg', TRUE, 2, NOW()), 1074 | ('Jeans', 'jeans', 'Denim jeans for casual wear', 39.99, 150, 60, 'jeans.jpg', TRUE, 2, NOW()), 1075 | ('Novel', 'novel', 'Bestselling fiction novel', 12.99, 300, 120, 'novel.jpg', TRUE, 3, NOW()), 1076 | ('Cookbook', 'cookbook', 'Collection of popular recipes', 24.99, 100, 40, 'cookbook.jpg', TRUE, 3, NOW()), 1077 | ('Throw Pillow', 'throw-pillow', 'Decorative throw pillow for couch', 29.99, 50, 20, 'throw-pillow.jpg', TRUE, 4, NOW()), 1078 | ('Wall Art', 'wall-art', 'Canvas wall art for home decor', 49.99, 80, 30, 'wall-art.jpg', TRUE, 4, NOW()), 1079 | ('Action Figure', 'action-figure', 'Collectible action figure', 14.99, 120, 50, 'action-figure.jpg', TRUE, 5, NOW()), 1080 | ('Board Game', 'board-game', 'Popular board game for family fun', 29.99, 70, 30, 'board-game.jpg', TRUE, 5, NOW()), 1081 | ('Headphones', 'headphones', 'Wireless headphones with noise cancellation', 149.99, 90, 40, 'headphones.jpg', TRUE, 1, NOW()), 1082 | ('Smart Watch', 'smart-watch', 'Fitness tracker smart watch', 199.99, 60, 20, 'smart-watch.jpg', TRUE, 1, NOW()), 1083 | ('Dress', 'dress', 'Elegant dress for special occasions', 79.99, 80, 25, 'dress.jpg', TRUE, 2, NOW()), 1084 | ('Sneakers', 'sneakers', 'Stylish sneakers for everyday wear', 59.99, 120, 45, 'sneakers.jpg', TRUE, 2, NOW()), 1085 | ('Cooking Utensils Set', 'cooking-utensils-set', 'Complete set of kitchen utensils', 49.99, 100, 35, 'cooking-utensils-set.jpg', TRUE, 4, NOW()); 1086 | 1087 | -- for uuid 1088 | INSERT INTO products (name, slug, description, price, quantity, sold, image, shipping, categoryID, createdAt) 1089 | VALUES 1090 | ('Laptop', 'laptop', 'High-performance laptop with SSD storage', 999.99, 50, 10, 'laptop.jpg', TRUE, '1820433f-fd1a-44c7-a168-59dd34554ca5', NOW()), 1091 | ('Smartphone', 'smartphone', 'Latest smartphone model with 5G connectivity', 699.99, 100, 30, 'smartphone.jpg', TRUE, '1820433f-fd1a-44c7-a168-59dd34554ca5', NOW()), 1092 | ('T-shirt', 't-shirt', 'Cotton t-shirt with trendy design', 19.99, 200, 80, 't-shirt.jpg', TRUE, 'f9e6f058-6c69-4133-9638-352b2b312db8', NOW()), 1093 | ('Jeans', 'jeans', 'Denim jeans for casual wear', 39.99, 150, 60, 'jeans.jpg', TRUE, 'f9e6f058-6c69-4133-9638-352b2b312db8', NOW()), 1094 | ('Novel', 'novel', 'Bestselling fiction novel', 12.99, 300, 120, 'novel.jpg', TRUE, '1d2cab81-1424-4c14-acc5-6cdc0a2a096b', NOW()), 1095 | ('Cookbook', 'cookbook', 'Collection of popular recipes', 24.99, 100, 40, 'cookbook.jpg', TRUE, '1d2cab81-1424-4c14-acc5-6cdc0a2a096b', NOW()), 1096 | ('Throw Pillow', 'throw-pillow', 'Decorative throw pillow for couch', 29.99, 50, 20, 'throw-pillow.jpg', TRUE, 'c79a747b-7741-4b5b-904d-f7ac3a372613', NOW()), 1097 | ('Wall Art', 'wall-art', 'Canvas wall art for home decor', 49.99, 80, 30, 'wall-art.jpg', TRUE, 'c79a747b-7741-4b5b-904d-f7ac3a372613', NOW()), 1098 | ('Action Figure', 'action-figure', 'Collectible action figure', 14.99, 120, 50, 'action-figure.jpg', TRUE, 'd6e297d6-10bb-430a-a774-4d84297f4bcb', NOW()), 1099 | ('Board Game', 'board-game', 'Popular board game for family fun', 29.99, 70, 30, 'board-game.jpg', TRUE, 'd6e297d6-10bb-430a-a774-4d84297f4bcb', NOW()), 1100 | ('Headphones', 'headphones', 'Wireless headphones with noise cancellation', 149.99, 90, 40, 'headphones.jpg', TRUE, '1820433f-fd1a-44c7-a168-59dd34554ca5', NOW()), 1101 | ('Smart Watch', 'smart-watch', 'Fitness tracker smart watch', 199.99, 60, 20, 'smart-watch.jpg', TRUE, '1820433f-fd1a-44c7-a168-59dd34554ca5', NOW()), 1102 | ('Dress', 'dress', 'Elegant dress for special occasions', 79.99, 80, 25, 'dress.jpg', TRUE, 'f9e6f058-6c69-4133-9638-352b2b312db8', NOW()), 1103 | ('Sneakers', 'sneakers', 'Stylish sneakers for everyday wear', 59.99, 120, 45, 'sneakers.jpg', TRUE, 'f9e6f058-6c69-4133-9638-352b2b312db8', NOW()), 1104 | ('Cooking Utensils Set', 'cooking-utensils-set', 'Complete set of kitchen utensils', 49.99, 100, 35, 'cooking-utensils-set.jpg', TRUE, 'c79a747b-7741-4b5b-904d-f7ac3a372613', NOW()); 1105 | ``` 1106 | 1107 | - **Inserting data into the Orders table**: 1108 | 1109 | ```sql 1110 | -- without junction table: denormalize the data and store product information directly 1111 | INSERT INTO orders (orderDate, status, payment, userId, products) 1112 | VALUES 1113 | ('2024-04-20 10:00:00', 'Pending', '{"method": "credit card", "amount": 100}', 1, '[{"product_id": 1, "quantity": 3}, {"product_id": 2, "quantity": 1}]'), 1114 | ('2024-04-21 11:00:00', 'Processing', '{"method": "cash on delivery", "amount": 150}', 2, '[{"product_id": 3, "quantity": 2}]'); 1115 | 1116 | ``` 1117 | 1118 | ```sql 1119 | -- with junction table 1120 | -- Inserting a sample order with multiple products 1121 | INSERT INTO orders (orderDate, status, userID) VALUES (CURRENT_TIMESTAMP, 'Pending', 'f10b0683-6e0b-45a1-95a7-909a72aa1187'); 1122 | 1123 | -- Inserting products for the sample order 1124 | INSERT INTO order_products (orderID, productID, quantity) VALUES 1125 | ('2bb5c629-c822-4b73-b75b-9fe11c39495e', '486103e3-4d54-4f0e-b91c-96561bc8f91b', 2), 1126 | ('2bb5c629-c822-4b73-b75b-9fe11c39495e', '4897005c-ce5f-4af1-8e82-b2e2b54e8720', 1),('2bb5c629-c822-4b73-b75b-9fe11c39495e', 'c1ab6fbc-e4e5-4e5d-b75c-868c3baa28e9', 3); 1127 | 1128 | -- another method 1129 | INSERT INTO order_products (orderID, productID, quantity) 1130 | SELECT '2bb5c629-c822-4b73-b75b-9fe11c39495e', 1131 | unnest(array['486103e3-4d54-4f0e-b91c-96561bc8f91b'::uuid, '4897005c-ce5f-4af1-8e82-b2e2b54e8720'::uuid, 'c1ab6fbc-e4e5-4e5d-b75c-868c3baa28e9'::uuid]), 1132 | unnest(array[2, 1, 3]); 1133 | 1134 | -- now select the products, user based on product id 1135 | SELECT 1136 | u.name AS user_name, 1137 | u.email AS user_email, 1138 | p.name AS product_name, 1139 | p.price AS product_price, 1140 | op.quantity AS product_quantity 1141 | FROM 1142 | orders o 1143 | JOIN 1144 | order_products op ON o.orderID = op.orderID 1145 | JOIN 1146 | users u ON o.userID = u.userID 1147 | JOIN 1148 | products p ON op.productID = p.productID 1149 | WHERE 1150 | o.orderID = '2bb5c629-c822-4b73-b75b-9fe11c39495e'; 1151 | 1152 | ``` 1153 | 1154 | ## 7. DML - FIND / SELECT RECORDS 1155 | 1156 | - syntax for selecting records 1157 | 1158 | ```sql 1159 | -- find all records with specific fields/columns 1160 | SELECT COL1,COL2,...COLN 1161 | FROM table_name 1162 | -- find all records with all the fields/columns 1163 | SELECT * 1164 | FROM table_name; 1165 | ``` 1166 | 1167 | ```sql 1168 | SELECT 1169 | orderId, 1170 | orderDate, 1171 | status, 1172 | payment, 1173 | userId, 1174 | products 1175 | FROM 1176 | orders 1177 | WHERE 1178 | orderId = 1; 1179 | 1180 | If you want to extract specific information from the products JSONB array, such as the product_id and quantity, you can use JSON functions like jsonb_array_elements or jsonb_array_elements_text. Here's an example: 1181 | SELECT 1182 | orderId, 1183 | orderDate, 1184 | status, 1185 | payment, 1186 | userId, 1187 | (jsonb_array_elements(products) ->> 'product_id')::int AS product_id, 1188 | (jsonb_array_elements(products) ->> 'quantity')::int AS quantity 1189 | FROM 1190 | orders 1191 | WHERE 1192 | orderId = 1; 1193 | ``` 1194 | 1195 | - To visualize a PostgreSQL table nicely in the terminal, you can use the `\x` command in `psql` to toggle expanded display mode. 1196 | - Run the following command to enter expanded display mode `\x` 1197 | 1198 | - After enabling expanded display mode, run a query to select data from your table. For example: `SELECT * FROM your_table;` 1199 | 1200 | - To disable expanded display mode and return to the default display format, simply run: `\x` 1201 | 1202 | ### SELECT and WHERE Clause 1203 | 1204 | To perform select operations in PostgreSQL, you can use the `SELECT` statement. Here's an example of how you can retrieve data from the `Users` table: 1205 | 1206 | ```sql 1207 | -- Retrieve all columns for all users 1208 | SELECT * FROM Users; 1209 | 1210 | -- Retrieve specific columns for all users 1211 | SELECT UserID, Username, Email FROM Users; 1212 | 1213 | -- Retrieve data based on a condition (e.g., where UserID equals 1) 1214 | SELECT * FROM Users WHERE UserID = 1; 1215 | 1216 | -- Retrieve data based on multiple conditions 1217 | SELECT * FROM Users WHERE Username = 'username1' AND Email = 'user1@example.com'; 1218 | ``` 1219 | 1220 | Similarly, you can perform select operations on other tables like `Products`, `Categories`, and `Orders` using the same `SELECT` statement with appropriate column names and conditions. Here are some examples: 1221 | 1222 | ```sql 1223 | -- Retrieve all columns for all products 1224 | SELECT * FROM Products; 1225 | 1226 | -- Retrieve products belonging to a specific category (e.g., where CategoryID equals 1) 1227 | SELECT * FROM Products WHERE CategoryID = 1; 1228 | 1229 | -- Retrieve all columns for all categories 1230 | SELECT * FROM Categories; 1231 | 1232 | -- Retrieve all columns for all orders 1233 | SELECT * FROM Orders; 1234 | 1235 | -- Retrieve orders placed by a specific user (e.g., where UserID equals 1) 1236 | SELECT * FROM Orders WHERE UserID = 1; 1237 | ``` 1238 | 1239 | You can customize the select queries based on your specific requirements and the structure of your database tables. 1240 | 1241 | - where clause allows us to find records conditionally 1242 | 1243 | ```sql 1244 | SELECT COL1,COL2,...COLN 1245 | FROM table_name 1246 | WHERE codition; 1247 | 1248 | example 1249 | SELECT Name 1250 | FROM students 1251 | WHERE city='Tampere'; 1252 | ``` 1253 | 1254 | ### DISTINCT, LIMIT, ORDER BY 1255 | 1256 | - distinct command for avoiding repeated values, limit can return limited records 1257 | 1258 | ```sql 1259 | SELECT DISTINCT COL1,COL2,...COLN 1260 | FROM table_name 1261 | LIMIT 5; 1262 | 1263 | SELECT DISTINCT COL1,COL2,...COLN 1264 | FROM table_name 1265 | -- (start from record 3, how many records you want ) 1266 | LIMIT 2,5; 1267 | 1268 | -- ORDER BY helps us to sort 1269 | SELECT COL1,COL2,...COLN 1270 | FROM table_name 1271 | ORDER BY COL1, COL2,...COLN; 1272 | 1273 | -- for descending ORDER BY helps us to sort 1274 | SELECT COL1,COL2,...COLN 1275 | FROM table_name 1276 | ORDER BY COL1, COL2,...COLN DESC ; 1277 | ``` 1278 | 1279 | ## 8. DML - UPDATE STATEMENT 1280 | 1281 | ```sql 1282 | UPDATE table_name 1283 | SET COL1=VAL1, COL2=VAL2, ...COLN=VALN 1284 | WHERE condition; 1285 | 1286 | example1 1287 | UPDATE techers 1288 | SET salary=20000 1289 | WHERE ID=102; 1290 | 1291 | example2 1292 | UPDATE techers 1293 | SET salary=salary+20000 1294 | WHERE salary>=10000; 1295 | ``` 1296 | 1297 | Sure, here are examples of `UPDATE` and `DELETE` operations in PostgreSQL for the given tables: 1298 | 1299 | **UPDATE operation:** 1300 | 1301 | 1. Update the email address of a user with a specific username: 1302 | 1303 | ```sql 1304 | UPDATE Users SET Email = 'new_email@example.com' WHERE Username = 'username1'; 1305 | ``` 1306 | 1307 | 2. Update the status of an order with a specific OrderID: 1308 | 1309 | ```sql 1310 | UPDATE Orders SET Status = 'Shipped' WHERE OrderID = 123; 1311 | ``` 1312 | 1313 | These examples illustrate how to use `UPDATE` and `DELETE` statements to modify or remove records from the tables in your PostgreSQL database. 1314 | 1315 | ## 9. DML - DELETE STATEMENT 1316 | 1317 | ```sql 1318 | DELETE FROM table_name 1319 | WHERE condition; 1320 | 1321 | example 1322 | DELETE FROM techers 1323 | WHERE ID=102; 1324 | ``` 1325 | 1326 | **DELETE operation:** 1327 | 1328 | - Delete a user with a specific UserID: 1329 | 1330 | ```sql 1331 | DELETE FROM Users WHERE UserID = 1; 1332 | ``` 1333 | 1334 | - Delete all orders placed by a user with a specific UserID: 1335 | 1336 | ```sql 1337 | DELETE FROM Orders WHERE UserID = 1; 1338 | ``` 1339 | 1340 | ## 10. Assignment for practcing CRUD 1341 | 1342 | ### **Assignment: Basic CRUD Operations in PostgreSQL** 1343 | 1344 | This assignment is designed to help students practice basic SQL commands (Create, Read, Update, Delete) using PostgreSQL (`psql`). The goal is to familiarize students with fundamental database operations and query syntax. 1345 | 1346 | ### **Objective:** 1347 | 1348 | Students will create a simple database for managing information about books and perform basic CRUD operations. 1349 | 1350 | ### **Requirements:** 1351 | 1352 | 1. Create a database called `library`. 1353 | 2. Create a table called `books` with the following structure: 1354 | - `book_id` (Primary Key, Auto-incremented) 1355 | - `title` (Text, Not Null) 1356 | - `author` (Text, Not Null) 1357 | - `published_year` (Integer) 1358 | - `genre` (Text) 1359 | 3. Perform the following CRUD operations: 1360 | - Insert new records into the `books` table. 1361 | - Read and display all records from the `books` table. 1362 | - Update an existing record. 1363 | - Delete a record. 1364 | - Sort the books by title in Descending order. 1365 | 1366 | ```sql 1367 | ('To Kill a Mockingbird', 'Harper Lee', 1960, 'Fiction'), 1368 | ('1984', 'George Orwell', 1949, 'Dystopian'), 1369 | ('The Great Gatsby', 'F. Scott Fitzgerald', 1925, 'Classic'), 1370 | ('Pride and Prejudice', 'Jane Austen', 1813, 'Romance'), 1371 | ('Moby-Dick', 'Herman Melville', 1851, 'Adventure'), 1372 | ('War and Peace', 'Leo Tolstoy', 1869, 'Historical Fiction'), 1373 | ('The Catcher in the Rye', 'J.D. Salinger', 1951, 'Fiction'), 1374 | ('The Hobbit', 'J.R.R. Tolkien', 1937, 'Fantasy'), 1375 | ('Crime and Punishment', 'Fyodor Dostoevsky', 1866, 'Philosophical Fiction'), 1376 | ('Brave New World', 'Aldous Huxley', 1932, 'Science Fiction') 1377 | ``` 1378 | 1379 | ### **Assessment Criteria:** 1380 | 1381 | - Correctly creating the database and table structure. 1382 | - Successfully executing insert, read, update, and delete queries. 1383 | - Demonstrating an understanding of basic SQL commands and how they manipulate data within the database. 1384 | 1385 | ### **Submission Instructions:** 1386 | 1387 | - Submit a text file with the SQL queries you used for each step. 1388 | 1389 | ### **Further Exploration:** 1390 | 1391 | - Add constraints like `UNIQUE` and `NOT NULL` to the table. 1392 | - Experiment with more complex queries, such as filtering results or joining with other tables (if created). 1393 | - Implement additional columns such as `ISBN` and `price` and try updating them. 1394 | 1395 | This assignment will help students grasp basic database operations and understand the flow of data manipulation within a relational database system like PostgreSQL. 1396 | 1397 | ## 11. Operators 1398 | 1399 | - Arithmetic operators: + - \* / % 1400 | - Comparision or Relational operators > >= < <= = != BETWEEN 1401 | - Logical operators: AND OR NOT IN 1402 | 1403 | ## 12. RELATIONAL OPERTAORS IN SQL 1404 | 1405 | - `SELECT * FROM Users WHERE CreatedAt > '2022-01-01';` 1406 | 1407 | - BETWEEN 1408 | 1409 | ```sql 1410 | SELECT COL1,COL2,...COLN 1411 | FROM table_name 1412 | WHERE COL BETWEEN START_VALUE AND END_VALUE; 1413 | 1414 | example 1415 | SELECT ID, NAME, GPA 1416 | FROM students 1417 | WHERE ID BETWEEN 101 AND 105; 1418 | ``` 1419 | 1420 | ## 13. LOGICAL OPERTAORS IN SQL 1421 | 1422 | - OR, AND, NOT, IN, LIKE 1423 | 1424 | ```sql 1425 | SELECT COL1,COL2,...COLN 1426 | FROM table_name 1427 | WHERE FIELD_NAME=VALUE OR FIELD_NAME=VALUE ...; 1428 | 1429 | SELECT COL1,COL2,...COLN 1430 | FROM table_name 1431 | WHERE FIELD_NAME=VALUE AND FIELD_NAME=VALUE ...; 1432 | 1433 | SELECT * 1434 | FROM students 1435 | WHERE city='Tampere' 1436 | OR city='Helsinki' 1437 | OR city='Oulu' 1438 | 1439 | SELECT * 1440 | FROM students 1441 | WHERE city IN ('Tampere','Helsinki','Oulu'); 1442 | 1443 | SELECT * 1444 | FROM students 1445 | WHERE city NOT IN ('Tampere','Helsinki','Oulu'); 1446 | 1447 | -- like helps to search based on a pattern 1448 | SELECT * 1449 | FROM students; 1450 | -- find anyone name starts with s 1451 | WHERE name LIKE 's%'; 1452 | -- find anyone name ends with s 1453 | WHERE name LIKE '%s'; 1454 | -- find anyone name contains hi 1455 | WHERE name LIKE '%hi%'; 1456 | ``` 1457 | 1458 | - Retrieve users with a username containing a specific substring: 1459 | 1460 | ```sql 1461 | SELECT * FROM Users WHERE Username LIKE '%part_of_username%'; 1462 | ``` 1463 | 1464 | - Retrieve users with a username starting with a specific letter: 1465 | 1466 | ```sql 1467 | SELECT * FROM Users WHERE Username LIKE 'A%'; 1468 | ``` 1469 | 1470 | - Retrieve users with a username ending with a specific letter: 1471 | 1472 | ```sql 1473 | SELECT * FROM Users WHERE Username LIKE '%a'; 1474 | ``` 1475 | 1476 | - Retrieve users with a username starting with a specific letter and having a certain length: 1477 | 1478 | ```sql 1479 | SELECT * FROM Users WHERE Username LIKE 'A%' AND LENGTH(Username) > 5; 1480 | ``` 1481 | 1482 | - Retrieve users created after a specific date: 1483 | 1484 | ```sql 1485 | SELECT * FROM Users WHERE CreatedAt > '2022-01-01'; 1486 | ``` 1487 | 1488 | - Retrieve users created within a specific date range: 1489 | 1490 | ```sql 1491 | SELECT * FROM Users WHERE CreatedAt BETWEEN '2022-01-01' AND '2022-12-31'; 1492 | ``` 1493 | 1494 | - Select users whose full names are not null or addresses are not null: 1495 | `SELECT * FROM Users WHERE FullName IS NOT NULL OR Address IS NOT NULL;` 1496 | 1497 | These examples demonstrate various ways you can use the `WHERE` clause to filter records based on different conditions in your PostgreSQL queries. 1498 | 1499 | ## 14. Custom name with AS Keyword 1500 | 1501 | ```sql 1502 | SELECT COL1 AS 'CUSTOM_NAME' 1503 | FROM table_name; 1504 | 1505 | 1506 | example1 1507 | SELECT Roll as 'student_id' 1508 | FROM students; 1509 | 1510 | example1 1511 | SELECT Roll as id 1512 | FROM students; 1513 | ``` 1514 | 1515 | `SELECT Email AS UserEmail FROM Users;` 1516 | 1517 | ## 15. SubQueries & [UPPER and LOWER Function](https://youtu.be/95wBGq9PJZQ) 1518 | 1519 | - Sub Queries: Query inside query 1520 | 1521 | ```sql 1522 | SELECT * FROM Products 1523 | WHERE Price > (SELECT AVG(Price) FROM Products); 1524 | ``` 1525 | 1526 | ## 16. Constraint and AUTO_INCREMENT 1527 | 1528 | - When creating table we can set constraint and auto increment 1529 | - Constraints: NOT NULL, UNIQUE, PRIMARY KEY = NOT NULL + UNIQUE, DEFAULT 1530 | 1531 | ```sql 1532 | CREATE TABLE TABLE_NAME N( 1533 | ID int NOT NULL AUTO_INCREMENT, 1534 | Name NOT NULL, 1535 | ) 1536 | ``` 1537 | 1538 | ## 17. [Functions](https://youtu.be/hn6P4tBRaIE) 1539 | 1540 | - Concatenating the username and email address: 1541 | 1542 | ```sql 1543 | SELECT CONCAT(Username, '@', Email) AS UserEmail FROM Users; 1544 | ``` 1545 | 1546 | - Getting the length of the username: 1547 | 1548 | ```sql 1549 | SELECT Username, LENGTH(Username) AS UsernameLength FROM Users; 1550 | ``` 1551 | 1552 | - Extracting the year from the created date: 1553 | 1554 | ```sql 1555 | SELECT Username, EXTRACT(YEAR FROM CreatedAt) AS CreatedYear FROM Users; 1556 | ``` 1557 | 1558 | - Converting the username to uppercase: 1559 | 1560 | ```sql 1561 | SELECT UPPER(Username) AS UpperCaseUsername FROM Users; 1562 | ``` 1563 | 1564 | - Converting the username to lowercase: 1565 | 1566 | ```sql 1567 | SELECT LOWER(Username) AS LowerCaseUsername FROM Users; 1568 | ``` 1569 | 1570 | - The GREATEST and LEAST functions in SQL are typically used with numeric or date/time values. 1571 | Sure, let's consider a scenario where we want to find the user with the earliest registration date (`CreatedAt`) and the user with the latest registration date. 1572 | 1573 | Here's how you can use the `LEAST` and `GREATEST` functions in SQL for the `Users` table: 1574 | 1575 | ```sql 1576 | -- Find the user with the earliest registration date 1577 | SELECT * FROM Users 1578 | WHERE CreatedAt = (SELECT LEAST(CreatedAt) FROM Users); 1579 | 1580 | -- Find the user with the latest registration date 1581 | SELECT * FROM Users 1582 | WHERE CreatedAt = (SELECT GREATEST(CreatedAt) FROM Users); 1583 | ``` 1584 | 1585 | In these queries: 1586 | 1587 | - `LEAST(CreatedAt)` finds the minimum value of the `CreatedAt` column. 1588 | - `GREATEST(CreatedAt)` finds the maximum value of the `CreatedAt` column. 1589 | - We then use subqueries to select the user(s) whose `CreatedAt` matches the result of `LEAST` or `GREATEST`. 1590 | 1591 | These queries will return the user(s) with the earliest and latest registration dates, respectively, from the `Users` table. 1592 | 1593 | ## 18. [Aggregate Functions](https://youtu.be/dO2h-s8tv2g) 1594 | 1595 | - aggregate: one result in the end. AVG(), COUNT(), MAX(), MIN(), SUM() 1596 | 1597 | ```sql 1598 | -- Total number of users 1599 | SELECT COUNT(*) AS TotalUsers FROM Users; 1600 | 1601 | -- Average age of users (assuming there's an Age column) 1602 | SELECT AVG(Age) AS AverageAge FROM Users; 1603 | 1604 | -- Earliest registration date 1605 | SELECT MIN(CreatedAt) AS EarliestRegistrationDate FROM Users; 1606 | 1607 | -- Latest registration date 1608 | SELECT MAX(CreatedAt) AS LatestRegistrationDate FROM Users; 1609 | 1610 | -- Total number of products 1611 | SELECT COUNT(*) AS TotalProducts FROM Products; 1612 | 1613 | -- Average price of products 1614 | SELECT AVG(Price) AS AveragePrice FROM Products; 1615 | 1616 | -- Highest price of a product 1617 | SELECT MAX(Price) AS HighestPrice FROM Products; 1618 | 1619 | -- Lowest price of a product 1620 | SELECT MIN(Price) AS LowestPrice FROM Products; 1621 | 1622 | ``` 1623 | 1624 | ## 19. GroupBy 1625 | 1626 | ```sql 1627 | SELECT Country, COUNT(UserID) AS UserCount 1628 | FROM Users 1629 | GROUP BY Country; 1630 | ``` 1631 | 1632 | ## 20. Joining Tables 1633 | 1634 | ```sql 1635 | -- create student table 1636 | CREATE TABLE Students ( 1637 | StudentId INT PRIMARY KEY, 1638 | FirstName VARCHAR(50), 1639 | LastName VARCHAR(50), 1640 | Gender VARCHAR(50), 1641 | DOB DATE, 1642 | Age INT 1643 | ); 1644 | 1645 | INSERT INTO Students (StudentId, FirstName, LastName, Gender, DOB, Age) VALUES 1646 | (1, 'John', 'Doe', 'Male', '1995-05-15', 26), 1647 | (2, 'Jane', 'Smith', 'Female', '1998-08-20', 23), 1648 | (3, 'Michael', 'Johnson', 'Male', '1997-03-10', 24), 1649 | (4, 'Emily', 'Brown', 'Female', '1996-11-25', 25), 1650 | (5, 'David', 'Williams', 'Male', '1999-06-30', 22), 1651 | (6, 'Sarah', 'Jones', 'Female', '1994-09-05', 27), 1652 | (8, 'Christopher', 'Davis', 'Male', '2000-02-12', 21); 1653 | 1654 | 1655 | -- create Grade table 1656 | CREATE TABLE Grades ( 1657 | GradeID INT PRIMARY KEY, 1658 | StudentID INT, 1659 | Course VARCHAR(50), 1660 | Grade VARCHAR(2) 1661 | ); 1662 | 1663 | INSERT INTO Grades (GradeID, StudentID, Course, Grade) 1664 | VALUES 1665 | (1, 1, 'Math', 'A'), 1666 | (2, 1, 'Science', 'B'), 1667 | (3, 2, 'Math', 'B+'), 1668 | (4, 3, 'Math', 'C'), 1669 | (5, 3, 'Science', 'A-'), 1670 | (6, 7, 'Science', 'A-'); 1671 | 1672 | ``` 1673 | 1674 | ### joining based on condition 1675 | 1676 | ```sql 1677 | SELECT FirstName, LastName, Age, Course, Grade 1678 | FROM Students,Grades 1679 | WHERE Students.StudentId = Grades.StudentId; 1680 | 1681 | -- more better syntax for avoiding naming conflict by using 'fully qulaified name' 1682 | SELECT Students.FirstName, Students.LastName, Students.Age, Grades.Course, Grades.Grade 1683 | FROM Students,Grades 1684 | WHERE Students.StudentId = Grades.StudentId; 1685 | 1686 | -- shorting the name by using Custom name 1687 | SELECT s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1688 | FROM Students AS s,Grades AS g 1689 | WHERE s.StudentId = g.StudentId; 1690 | ``` 1691 | 1692 | ### joining using JOIN Clause 1693 | 1694 | ```sql 1695 | 1696 | SELECT s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1697 | FROM Students AS s JOIN Grades AS g 1698 | ON s.StudentId = g.StudentId; 1699 | ``` 1700 | 1701 | ### Inner Join 1702 | 1703 | - INNER JOIN will returned only the matched records 1704 | 1705 | ```sql 1706 | SELECT s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1707 | FROM Students AS s INNER JOIN Grades AS g 1708 | ON s.StudentId = g.StudentId; 1709 | ``` 1710 | 1711 | ### Left Join 1712 | 1713 | - LEFT JOIN will rturns all rows from the left table (Table1), and the matched rows from the right table (Table). If there is no match, the result is NULL on the right side. 1714 | 1715 | ```sql 1716 | SELECT s.StudentId, s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1717 | FROM Students AS s LEFT JOIN Grades AS g 1718 | ON s.StudentId = g.StudentId; 1719 | ``` 1720 | 1721 | ### Right Join 1722 | 1723 | - RIGHT JOIN will rturns all rows from the right table (Table2), and the matched rows from the left table (Table1). If there is no match, the result is NULL on the left side. 1724 | 1725 | ```sql 1726 | SELECT s.StudentId, s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1727 | FROM Students AS s RIGHT JOIN Grades AS g 1728 | ON s.StudentId = g.StudentId; 1729 | ``` 1730 | 1731 | ### FULL Join 1732 | 1733 | - Returns all rows when there is a match in either table. This means it returns all the rows from the left table (Table1) and all the rows from the right table (Table2), with NULLs in the columns where there is no match. 1734 | 1735 | ```sql 1736 | SELECT s.StudentId, s.FirstName, s.LastName, s.Age, g.Course, g.Grade 1737 | FROM Students AS s FULL JOIN Grades AS g 1738 | ON s.StudentId = g.StudentId; 1739 | ``` 1740 | 1741 | ### Join among all the tables 1742 | 1743 | ```sql 1744 | -- Order Table 1745 | CREATE TABLE Orders( 1746 | OrderId SERIAL PRIMARY KEY, 1747 | OrderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 1748 | Status VARCHAR(50) DEFAULT 'Pending', 1749 | UserId INT REFERENCES Users(UserId), 1750 | ProductId INT REFERENCES Products(ProductId) 1751 | ); 1752 | 1753 | INSERT INTO Orders (UserId, ProductId, Status) 1754 | VALUES 1755 | (2, 1, 'Pending'); 1756 | 1757 | INSERT INTO Orders (UserId, ProductId, Status) 1758 | VALUES 1759 | (3, 2, 'Pending'); 1760 | 1761 | INSERT INTO Orders (UserId, ProductId, Status) 1762 | VALUES 1763 | (2, 2, 'Pending'); 1764 | 1765 | SELECT u.UserId, u.Username, u.Address, o.Status 1766 | FROM Users u 1767 | INNER JOIN Orders o ON u.UserId = o.UserId; 1768 | 1769 | 1770 | SELECT o.OrderId, o.Status, u.Username, u.Address, p.Name, p.Price, p.Description 1771 | FROM Orders o 1772 | INNER JOIN Products p ON o.ProductId = p.ProductId 1773 | INNER JOIN Users u ON o.UserId = u.UserId; 1774 | ``` 1775 | 1776 | ## 21. UNION and UNION ALL, INTERSECT 1777 | 1778 | - create 2 tables: people_visited_england and people_visited_finland 1779 | - same number of columns and same sequences 1780 | - union will remove duplicates records; it is slower 1781 | - union all will not remove duplicates records; it is faster as no concerns of removing duplicates 1782 | - find people visited both countries 1783 | 1784 | ```sql 1785 | SELECT Name, Gender, Age 1786 | FROM people_visited_england 1787 | 1788 | UNION 1789 | 1790 | SELECT Name, Gender, Age 1791 | FROM people_visited_finland 1792 | ``` 1793 | 1794 | In SQL, the `INTERSECT` operator is used to retrieve the common rows that exist in two separate SELECT queries. It returns only the rows that appear in both result sets. Here's an example: 1795 | 1796 | Suppose we have two tables: `TableA` and `TableB`, each containing different sets of data. 1797 | 1798 | TableA: 1799 | 1800 | | ID | Name | 1801 | |----|---------| 1802 | | 1 | John | 1803 | | 2 | Alice | 1804 | | 3 | Bob | 1805 | 1806 | TableB: 1807 | 1808 | | ID | Name | 1809 | |----|---------| 1810 | | 2 | Alice | 1811 | | 3 | Bob | 1812 | | 4 | Sarah | 1813 | 1814 | Now, let's say we want to find the common names between these two tables. We can use the `INTERSECT` operator to achieve this: 1815 | 1816 | ```sql 1817 | SELECT Name FROM TableA 1818 | INTERSECT 1819 | SELECT Name FROM TableB; 1820 | ``` 1821 | 1822 | This query will return: 1823 | 1824 | | Name | 1825 | |---------| 1826 | | Alice | 1827 | | Bob | 1828 | 1829 | Explanation: 1830 | 1831 | - The `SELECT Name FROM TableA` statement retrieves all the names from `TableA`. 1832 | - The `SELECT Name FROM TableB` statement retrieves all the names from `TableB`. 1833 | - The `INTERSECT` operator returns only the common names that appear in both result sets, which are "Alice" and "Bob". 1834 | 1835 | This demonstrates how the `INTERSECT` operator can be used to find the intersection of two sets of data in SQL. 1836 | 1837 | ## 22. VIEW (Virtual Table) 1838 | 1839 | - view is a virtual table a copy of original table with the columns that you want to display 1840 | 1841 | ```sql 1842 | CREATE VIEW view_name AS 1843 | SELECT Name, Age 1844 | FROM original_table; 1845 | 1846 | SELECT * 1847 | FROM view_name; 1848 | ``` 1849 | 1850 | - how to drop/delete a view 1851 | `DROP VIEW view_name` 1852 | 1853 | - how to update view 1854 | 1855 | ```sql 1856 | UPDATE student_view 1857 | SET Name = 'Fahima' 1858 | WHERE Roll=101; 1859 | ``` 1860 | 1861 | - how to insert new records to the view 1862 | - how to delete records from the view 1863 | 1864 | ## 23. DATE & Time 1865 | 1866 | ```sql 1867 | // for mysql 1868 | SELECT CURDATE() 1869 | SELECT CURTIME() 1870 | SELECT NOW() 1871 | SELECT MAKEDATE(2017,312); 1872 | SELECT DAYNAME('2017-09-14'); 1873 | SELECT MONTHNAME('2017-09-14'); 1874 | 1875 | // for psql 1876 | SELECT CURRENT_DATE; 1877 | SELECT CURRENT_TIME; 1878 | SELECT NOW(); 1879 | SELECT MAKE_DATE(2017, 312); 1880 | SELECT TO_CHAR('2017-09-14'::DATE, 'Day'); 1881 | SELECT TO_CHAR('2017-09-14'::DATE, 'Month'); 1882 | 1883 | -- use DAYNAME(DATE) for DOB 1884 | SELECT DAYNAME(DOB) 1885 | FROM TableName; 1886 | 1887 | -- in psql 1888 | SELECT TO_CHAR(DOB, 'Day') AS day_of_week 1889 | FROM TableName; 1890 | ``` 1891 | 1892 | ## 24. [Indexing](https://www.postgresqltutorial.com/postgresql-indexes/postgresql-create-index/) 1893 | 1894 | Indexing is a database optimization technique used to improve the performance of queries by allowing the database engine to quickly locate rows in a table that match certain criteria. Here are some reasons why indexing is important: 1895 | 1896 | 1. **Faster Data Retrieval**: Indexes provide a quick path to the data, allowing the database engine to locate and retrieve rows more efficiently. Without indexes, the database engine would need to scan the entire table sequentially, which can be slow, especially for large tables. 1897 | 1898 | 2. **Improved Query Performance**: Queries that involve filtering, sorting, or joining data often benefit from indexes. Indexes allow the database engine to quickly identify and access the rows that satisfy the query conditions, resulting in faster query execution times. 1899 | 1900 | 3. **Support for Constraints**: Indexes are often used to enforce constraints such as primary key or unique constraints. These constraints ensure data integrity and prevent duplicate or null values in key columns. 1901 | 1902 | 4. **Optimized Join Operations**: Indexes can be used to optimize join operations between tables by providing efficient access paths to the joined columns. 1903 | 1904 | 5. **Reduced Disk I/O**: By storing index data in a separate structure, indexes reduce the amount of disk I/O required to retrieve data, which can lead to overall performance improvements, especially in disk-bound systems. 1905 | 1906 | Overall, indexing plays a crucial role in database performance tuning and is essential for improving the responsiveness and scalability of database applications. However, it's important to carefully consider the indexing strategy and avoid over-indexing, as indexes come with overhead in terms of storage space and maintenance costs. 1907 | 1908 | - create single column index: `CREATE INDEX index_name ON table_name (column_name);` 1909 | - create multiple column index: `CREATE INDEX index_name ON table_name (column1_name, column2_name);` 1910 | - better syntax 1911 | 1912 | ```sql 1913 | CREATE INDEX [IF NOT EXISTS] index_name 1914 | ON table_name(column1, column2, ...); 1915 | ``` 1916 | 1917 | - drop index: `DROP INDEX index_name;` 1918 | 1919 | - check existing indexes 1920 | 1921 | ```sql 1922 | SELECT * 1923 | FROM pg_indexes 1924 | WHERE tablename = 'users'; 1925 | 1926 | ``` 1927 | 1928 | ```sql 1929 | -- Create the Users table 1930 | CREATE TABLE users ( 1931 | userID SERIAL PRIMARY KEY, 1932 | name VARCHAR(100) NOT NULL, 1933 | email VARCHAR(100) UNIQUE NOT NULL, 1934 | password VARCHAR(255) NOT NULL, 1935 | address VARCHAR(255), 1936 | image VARCHAR(255), 1937 | isAdmin BOOLEAN DEFAULT FALSE, 1938 | isBanned BOOLEAN DEFAULT FALSE, 1939 | createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP 1940 | ); 1941 | 1942 | -- Insert records into the Users table 1943 | INSERT INTO users (name, email, password, address, isAdmin, isBanned, createdAt) 1944 | VALUES 1945 | ('Emily Wilson', 'emily@example.com', 'password123', '123 Oak St', false, false, CURRENT_TIMESTAMP), 1946 | ('James Brown', 'james@example.com', 'password456', '456 Maple St', false, false, CURRENT_TIMESTAMP), 1947 | ('Olivia Davis', 'olivia@example.com', 'password789', '789 Elm St', false, false, CURRENT_TIMESTAMP), 1948 | ('Liam Johnson', 'liam@example.com', 'passwordabc', '123 Pine St', false, false, CURRENT_TIMESTAMP), 1949 | ('Ava Garcia', 'ava@example.com', 'passworddef', '456 Oak St', false, false, CURRENT_TIMESTAMP), 1950 | ('Noah Martinez', 'noah@example.com', 'password123', '789 Maple St', false, false, CURRENT_TIMESTAMP), 1951 | ('Isabella Rodriguez', 'isabella@example.com', 'password456', '123 Cedar St', false, false, CURRENT_TIMESTAMP), 1952 | ('William Hernandez', 'william@example.com', 'password789', '456 Pine St', false, false, CURRENT_TIMESTAMP), 1953 | ('Sophia Lopez', 'sophia@example.com', 'passwordabc', '789 Cedar St', false, false, CURRENT_TIMESTAMP), 1954 | ('Benjamin Lewis', 'benjamin@example.com', 'passworddef', '123 Elm St', false, false, CURRENT_TIMESTAMP), 1955 | ('Charlotte Perez', 'charlotte@example.com', 'password123', '456 Pine St', false, false, CURRENT_TIMESTAMP), 1956 | ('Mason Gonzalez', 'mason@example.com', 'password456', '789 Cedar St', false, false, CURRENT_TIMESTAMP), 1957 | ('Amelia Moore', 'amelia@example.com', 'password789', '123 Oak St', false, false, CURRENT_TIMESTAMP), 1958 | ('Ethan Watson', 'ethan@example.com', 'passwordabc', '456 Maple St', false, false, CURRENT_TIMESTAMP), 1959 | ('Harper Cook', 'harper@example.com', 'passworddef', '789 Elm St', false, false, CURRENT_TIMESTAMP), 1960 | ('Michael Brooks', 'michael@example.com', 'password123', '123 Pine St', false, false, CURRENT_TIMESTAMP), 1961 | ('Evelyn Kelly', 'evelyn@example.com', 'password456', '456 Cedar St', false, false, CURRENT_TIMESTAMP), 1962 | ('Alexander Price', 'alexander@example.com', 'password789', '789 Oak St', false, false, CURRENT_TIMESTAMP), 1963 | ('Layla Hayes', 'layla@example.com', 'passwordabc', '123 Maple St', false, false, CURRENT_TIMESTAMP), 1964 | ('Daniel Russell', 'daniel@example.com', 'passworddef', '456 Elm St', false, false, CURRENT_TIMESTAMP); 1965 | 1966 | 1967 | -- Query without index 1968 | EXPLAIN ANALYZE SELECT * FROM users WHERE address = '123 Main St'; 1969 | 1970 | -- Create an index on the email column 1971 | CREATE INDEX idx_users_address ON users (address); 1972 | 1973 | SELECT 1974 | indexname, 1975 | indexdef 1976 | FROM 1977 | pg_indexes 1978 | WHERE 1979 | tablename = 'users'; 1980 | 1981 | 1982 | -- Query with index 1983 | EXPLAIN ANALYZE SELECT * FROM Users WHERE address = '123 Main St'; 1984 | 1985 | ``` 1986 | 1987 | ### When Should Indexes be Avoided? (collected from tutorialspoint) 1988 | 1989 | Although indexes are intended to enhance a database's performance, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered − 1990 | 1991 | - Indexes should not be used on small tables. 1992 | 1993 | - Tables that have frequent, large batch update or insert operations. 1994 | 1995 | - Indexes should not be used on columns that contain a high number of NULL values. 1996 | 1997 | - Columns that are frequently manipulated should not be indexed. 1998 | 1999 | ## 25. How to Use pgAdmin 2000 | 2001 | - you need to have access to psql dbms so make sure to have it already 2002 | - download and install pgAdmin 2003 | - create a server then connect to a database (if you do not have one then create a database) 2004 | - UI 2005 | - Run SQL 2006 | - SAVE FILE 2007 | - BROWSE OBJECT 2008 | 2009 | ## 26. PostgreSQL REST API 2010 | 2011 | - PostgreSQL is a RDBMS like MySQL 2012 | - it supports sql and json 2013 | - download PostgreSQL and node 2014 | - psql postgres://anisul_islam@localhost:5432/anisul_islam 2015 | - go to postgres database with the command psql -U postgres 2016 | 2017 | ```sql 2018 | \l -> list of all databases 2019 | \c databaseName-> move a specific databaseName 2020 | \dt -> show all the tables in a db 2021 | DROP DATABASE database_name 2022 | 2023 | CREATE DATABASE todo_database; 2024 | 2025 | --\c into todo_database 2026 | 2027 | CREATE TABLE todo( 2028 | todo_id SERIAL PRIMARY KEY, 2029 | description VARCHAR(255) 2030 | ); 2031 | 2032 | SELECT * 2033 | FROM todo; 2034 | ``` 2035 | 2036 | CRUD operations 2037 | CREATE - POST HTTP METHOD 2038 | 2039 | ```sql 2040 | INSERT INTO table_name (col1, col2, ..., coln) 2041 | VALUES 2042 | (val1, val2, ..., valN); 2043 | ``` 2044 | 2045 | READ - GET HTTP METHOD 2046 | 2047 | ```sql 2048 | SELECT (col1, col2, ..., coln) 2049 | FROM table_name 2050 | WHERE condition; 2051 | ``` 2052 | 2053 | UPDATE - PUT HTTP METHOD 2054 | 2055 | ```sql 2056 | UPDATE table_name 2057 | SET col1=val1, col2=val2, ...coln=valn 2058 | WHERE condition; 2059 | ``` 2060 | 2061 | DELETE - DELETE HTTP METHOD 2062 | 2063 | ```sql 2064 | DELETE FROM table_name 2065 | WHERE condition; 2066 | ``` 2067 | 2068 | - install express pg nodemon 2069 | - create server 2070 | - create a database 2071 | - create a table 2072 | 2073 | ## 27. Sorting vs Indexing 2074 | 2075 | - Indexing: Indexing in a database is a technique used to optimize the retrieval of data by creating data structures, called indexes, that allow for faster lookup of records. Indexes are similar to the index of a book, which helps you quickly locate information within the book. 2076 | 2077 | Here's how indexing works and its benefits: 2078 | 2079 | 1. **How Indexing Works**: 2080 | - When you create an index on a column or set of columns in a database table, the database system creates a separate data structure that contains pointers to the actual rows in the table. 2081 | - These pointers are organized in a way that allows the database engine to quickly locate the rows associated with a specific value or range of values in the indexed column(s). 2082 | - When you query the database using a condition that matches the indexed column(s), the database engine first consults the index to find the corresponding rows, significantly reducing the time required to retrieve the data. 2083 | 2084 | 2. **Benefits of Indexing**: 2085 | - Improved Query Performance: Indexes speed up data retrieval operations, especially for queries that involve filtering, sorting, or joining data based on indexed columns. 2086 | - Faster Data Access: By reducing the number of disk I/O operations needed to locate data, indexes help minimize latency and improve overall system responsiveness. 2087 | - Enhanced Concurrency: Indexes can also improve the concurrency of database operations by reducing the time it takes to acquire locks on data pages, allowing multiple transactions to access data simultaneously. 2088 | - Efficient Sorting and Grouping: Indexes facilitate efficient sorting and grouping operations, making it easier to analyze and aggregate data. 2089 | 2090 | 3. **Types of Indexes**: 2091 | - **Single-Column Index**: An index created on a single column. 2092 | - **Composite Index**: An index created on multiple columns, allowing for efficient querying based on combinations of those columns. 2093 | - **Unique Index**: Ensures that the indexed column(s) contain unique values, preventing duplicate entries. 2094 | - **Clustered Index**: Defines the physical order of rows in the table based on the indexed column(s). Each table can have only one clustered index. 2095 | - **Non-Clustered Index**: Stores the index data separately from the table data, allowing for faster retrieval but not affecting the physical order of rows in the table. 2096 | 2097 | Indexing is a crucial aspect of database performance optimization. However, it's essential to strike a balance between the benefits of indexing and the overhead it imposes on data modification operations such as inserts, updates, and deletes. Over-indexing can lead to increased storage requirements and slower write operations, so it's essential to carefully consider the indexing strategy based on the specific requirements of your database application. 2098 | 2099 | ## 28. Database security 2100 | 2101 | - Encryption 2102 | -------------------------------------------------------------------------------- /image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anisul-Islam/relational-database-sql/b70a16fa938b54c889eb1c0186810a27724ca6f8/image-1.png -------------------------------------------------------------------------------- /image-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anisul-Islam/relational-database-sql/b70a16fa938b54c889eb1c0186810a27724ca6f8/image-2.png -------------------------------------------------------------------------------- /image-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anisul-Islam/relational-database-sql/b70a16fa938b54c889eb1c0186810a27724ca6f8/image-3.png -------------------------------------------------------------------------------- /image-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anisul-Islam/relational-database-sql/b70a16fa938b54c889eb1c0186810a27724ca6f8/image-4.png -------------------------------------------------------------------------------- /image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anisul-Islam/relational-database-sql/b70a16fa938b54c889eb1c0186810a27724ca6f8/image.png --------------------------------------------------------------------------------