Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
158 changes: 158 additions & 0 deletions docs/sql/SQL-basics/constraints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
---
id: sql-constraints
title: SQL Constraints
sidebar_label: SQL Constraints
sidebar_position: 6
tags: [sql, constraints, database, relational-databases]
description: In this super beginner-friendly guide, you’ll learn about SQL constraints—rules that keep your database data safe, accurate, and organized!
keywords: [sql, constraints, sql tutorial, sql basics, database management, relational databases, sql constraints tutorial, sql for beginners, sql in 2025]
---

## 📙 Welcome to SQL Constraints!

Hey there, new SQL learner! Imagine you are organizing a big toy box, and you want to make sure no toy gets lost or mixed up. Constraints are like special rules you set for your database tables to keep everything in order. They help stop mistakes, like adding a negative age or leaving a name blank. We’ll use a `students` table (with columns like `id`, `name`, and `age`) to show you how it works, step by step!

### 📘 What Are Constraints?

Constraints are like guardrails for your data. They are rules you add to columns in a table to:
- Stop invalid data (e.g., no negative ages like -5).
- Make sure some data is unique (e.g., no two students with the same ID).
- Keep everything consistent across your database.

There are several types of constraints, like NOT NULL, UNIQUE, CHECK, and DEFAULT. Let’s explore each one with easy examples!

> **Pro Tip**: Adding constraints when you create a table is a smart way to catch mistakes early—think of it as setting up rules before the game starts!

### 📘 NOT NULL Constraint (No Empty Spots!)

This rule makes sure a column always has a value—it can’t be empty (NULL). It’s perfect for things like names or IDs that you always need.

**How It Works**: If you mark a column as NOT NULL, you must fill it in when adding a new row. If you don’t, SQL will say, “Oops, you forgot something!”

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Creating Table with NOT NULL"
CREATE TABLE students (
id INT,
name VARCHAR(50) NOT NULL, -- Name must have a value
age INT
);
INSERT INTO students (id, name, age) VALUES (1, 'Alice', 20); -- This works!
-- This will fail: INSERT INTO students (id, age) VALUES (2, 21); -- No name!
```
</TabItem>

<TabItem value="Output" label="Output">
| id | name | age |
|----|-------|-----|
| 1 | Alice | 20 |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t skip NOT NULL on important columns like names or IDs—leaving them blank can mess up your records and make it hard to find data later!

### 🔄 UNIQUE Constraint (No Doubles Allowed!)

This rule ensures that every value in a column is different—no duplicates. It’s great for things like email addresses or student IDs.

**How It Works**: If you try to add the same value twice (e.g., two students with the same email), SQL will stop you and say, “Hey, that’s already taken!”

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Creating Table with UNIQUE"
CREATE TABLE students (
id INT,
email VARCHAR(50) UNIQUE -- No two students can have the same email
);
INSERT INTO students (id, email) VALUES (1, '[email protected]'); -- Works!
-- This will fail: INSERT INTO students (id, email) VALUES (2, '[email protected]'); -- Duplicate!
```
</TabItem>

<TabItem value="Output" label="Output">
| id | email |
|----|--------------------|
| 1 | [email protected] |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Avoid using UNIQUE on columns that might repeat naturally, like ages (e.g., two 20-year-olds)—it’ll block valid data and cause errors!

### 📘 CHECK Constraint (Set Your Own Rules!)

This lets you create a custom rule for a column, like saying “age must be 18 or older.” It’s like setting a limit on what’s allowed.

**How It Works**: You write a condition, and SQL checks it every time you add or change data. If the data doesn’t match, it won’t let you save it.

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Creating Table with CHECK"
CREATE TABLE students (
id INT,
age INT CHECK (age >= 18) -- Only ages 18 or higher are allowed
);
INSERT INTO students (id, age) VALUES (1, 20); -- Works!
-- This will fail: INSERT INTO students (id, age) VALUES (2, 16); -- Too young!
```
</TabItem>

<TabItem value="Output" label="Output">
| id | age |
|----|-----|
| 1 | 20 |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t make the CHECK rule too strict (e.g., age > 100)—you might block real data and frustrate yourself!

### 🔄 DEFAULT Constraint (Auto-Fill Magic!)

This sets a default value for a column if you don’t provide one. It’s handy for things like setting a default city.

**How It Works**: If you leave a column blank, SQL fills it with the default value you chose, saving you time.

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Creating Table with DEFAULT"
CREATE TABLE students (
id INT,
city VARCHAR(50) DEFAULT 'Unknown' -- If no city is given, it’s 'Unknown'
);
INSERT INTO students (id) VALUES (1); -- No city provided, uses default
INSERT INTO students (id, city) VALUES (2, 'Delhi'); -- Overrides default
```
</TabItem>

<TabItem value="Output" label="Output">
| id | city |
|----|---------|
| 1 | Unknown |
| 2 | Delhi |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Avoid setting a silly default (e.g., age = 0)—it could lead to confusing or wrong data later!

## ✅ What You’ve Learned

Wow, you’re doing great! You’ve learned:
- **NOT NULL**: Keeps columns from being empty.
- **UNIQUE**: Stops duplicates.
- **CHECK**: Sets custom limits.
- **DEFAULT**: Adds automatic values.

Try adding these constraints to your own tables and play around with them. Watch out for the "What NOT to Do" tips to keep your database happy and error-free!

---
165 changes: 165 additions & 0 deletions docs/sql/SQL-basics/operators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
---
id: sql-operators
title: SQL Operators
sidebar_label: SQL Operators
sidebar_position: 8
tags: [sql, operators, database, relational-databases]
description: In this super beginner-friendly guide, you’ll learn about SQL operators—the tools that help you do math, compare things, and make decisions in your queries!
keywords: [sql, operators, sql tutorial, sql basics, database management, relational databases, sql operators tutorial, sql for beginners, sql in 2025]
---

## 📙 Welcome to SQL Operators!

Hey there, SQL beginner! Operators are like magic symbols in SQL that let you add numbers, compare values, or combine conditions. Think of them as the plus (+) or equals (=) signs you use in math, but for databases. They’re super useful in queries, especially in WHERE clauses to filter data. We’ll use a simple `students` table (with columns like `id`, `name`, `age`, `marks`, and `city`) to explain everything with easy examples. Let’s dive in step by step!

### 📘 What Are Operators?

Operators are symbols or keywords that perform operations on data. They help you:
- Do calculations (arithmetic operators).
- Compare values (comparison operators).
- Combine conditions (logical operators).
- Check for patterns or ranges (special operators like LIKE or BETWEEN).

You’ll often use them in SELECT statements to filter or calculate results.

> **Pro Tip**: Operators make your queries smarter—practice them to find exactly the data you need!

### 📘 Arithmetic Operators (Math in SQL!)

These operators let you add, subtract, multiply, divide, or find remainders. They’re great for calculating things like total marks.

The main ones:
- **+** (Addition): Adds numbers.
- **-** (Subtraction): Subtracts numbers.
- **\*** (Multiplication): Multiplies numbers.
- **/** (Division): Divides numbers.
- **%** (Modulus): Gives the remainder.

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Using Arithmetic Operators"
-- Assume students table has marks column
SELECT id, name, marks + 10 AS bonus_marks -- Add 10 to marks
FROM students
WHERE marks > 80;
```
</TabItem>

<TabItem value="Output" label="Output">
| id | name | bonus_marks |
|----|-------|-------------|
| 1 | Alice | 95 |
| 2 | Bob | 102 |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t divide by zero (e.g., marks / 0)—it’ll cause an error. Always check for zero first!

### 🔄 Comparison Operators (Checking If Things Match!)

These help you compare values, like finding students older than 18. They’re used in WHERE to filter rows.

The main ones:
- **=** (Equal): Checks if equal.
- **!=** or **<>** (Not Equal): Checks if not equal.
- **>** (Greater Than): Bigger than.
- **<** (Less Than): Smaller than.
- **>=** (Greater Than or Equal): Bigger or same.
- **<=** (Less Than or Equal): Smaller or same.

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Using Comparison Operators"
SELECT id, name, age
FROM students
WHERE age >= 18 AND marks > 80; -- Adults with high marks
```
</TabItem>

<TabItem value="Output" label="Output">
| id | name | age |
|----|-------|-----|
| 1 | Alice | 20 |
| 2 | Bob | 22 |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t use = for strings without quotes (e.g., WHERE city = Delhi)—always quote text like 'Delhi' to avoid errors!

### 📘 Logical Operators (Combining Conditions!)

These let you mix multiple conditions, like finding students who are young OR high-scorers.

The main ones:
- **AND**: Both conditions must be true.
- **OR**: At least one condition is true.
- **NOT**: Reverses a condition (true becomes false).

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Using Logical Operators"
SELECT id, name, marks
FROM students
WHERE (marks > 90 OR age < 18) AND NOT city = 'Delhi'; -- High marks or young, not from Delhi
```
</TabItem>

<TabItem value="Output" label="Output">
| id | name | marks |
|----|-------|-------|
| 3 | Carol | 95 |
| 4 | Dave | 45 |
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t overuse AND/OR without parentheses (e.g., A AND B OR C)—it can confuse the order. Use (A AND B) OR C to be clear!

### 🔄 Special Operators (Fancy Filters!)

These are extra helpful for patterns or ranges:
- **BETWEEN**: Checks a range (e.g., marks BETWEEN 70 AND 90).
- **IN**: Checks against a list (e.g., city IN ('Delhi', 'Mumbai')).
- **LIKE**: Pattern matching (e.g., name LIKE 'A%' for names starting with A).
- **IS NULL / IS NOT NULL**: Checks for empty values.

**Example**:
:::info
<Tabs>
<TabItem value="SQL Code" label="SQL Code">
```sql title="Using Special Operators"
SELECT id, name, city
FROM students
WHERE marks BETWEEN 80 AND 90 AND name LIKE 'A%'; -- Marks 80-90, name starts with A
```
</TabItem>

<TabItem value="Output" label="Output">
| id | name | city |
|----|-------|-------|
| 1 | Alice | Mumbai|
</TabItem>
</Tabs>
:::

> **What NOT to Do**: Don’t use LIKE without % or _ wildcards (e.g., name LIKE 'Alice')—it’s the same as = and less efficient for patterns!

## ✅ What You’ve Learned

You’re a SQL operator pro now! You’ve explored:
- **Arithmetic Operators**: +, -, *, /, % for calculations.
- **Comparison Operators**: =, !=, >, etc., for checks.
- **Logical Operators**: AND, OR, NOT for combining.
- **Special Operators**: BETWEEN, IN, LIKE, IS NULL for advanced filters.

Practice by writing queries with these operators on a sample table. Avoid the "What NOT to Do" tips to keep your queries error-free and fast!

---
Loading
Loading