Skip to content

SQL Basics

What is SQL?

  • SQL (Structured Query Language) is used to:
  • Store data
  • Retrieve data
  • Update data
  • Delete data from a database.

  • SQL works with relational databases like:

  • MySQL
  • PostgreSQL
  • SQL Server
  • Oracle
  • SQLite

What is a Database?

  • A database is a place where data is stored.

What is a Table?

  • A table stores data in rows and columns.
  • Example: employees table:
id name age department salary
1 Rahul 25 IT 50000
2 Anita 28 HR 45000
  • Row → one record
  • Column → one field

Basic SQL Command

SELECT Statement * Used to read data from a table.

SELECT * FROM employees;
* means all columns

Select Specific Columns

SELECT name, salary FROM employees;
WHERE Clause (Filtering Data)
SELECT * FROM employees
WHERE department = 'IT';
Using Conditions
SELECT * FROM employees
WHERE salary > 45000;
AND / OR
SELECT * FROM employees
WHERE department = 'IT' AND salary > 40000;
ORDER BY (Sorting Data) * Used to sort data in ascending (ASC) or descending (DESC) order. * Example: Sort by age (youngest first) sql SELECT * FROM students ORDER BY age; * (Default is ASC)

Oldest first

SELECT * FROM students
ORDER BY age DESC;
Sort by name alphabetically
SELECT * FROM students
ORDER BY name ASC;
LIMIT (Restrict Number of Rows) * Used to limit the output rows. * Get first 5 students
SELECT * FROM students
LIMIT 5;
Top 3 oldest students
SELECT * FROM students
ORDER BY age DESC
LIMIT 3;
ORDER BY + WHERE + LIMIT (Very Important Combo) * Get top 2 highest paid IT employees

SELECT * FROM employees
WHERE department = 'IT'
ORDER BY salary DESC
LIMIT 2;

SQL Operators (IN, BETWEEN, LIKE) * IN Operator - Used when you want to match multiple values. * Instead of:

WHERE department = 'IT' OR department = 'HR'
* Use:
 SELECT * FROM employees
 WHERE department IN ('IT', 'HR');
* BETWEEN Operator - Used for a range of values. * Example:
SELECT * FROM employees
WHERE salary BETWEEN 40000 AND 60000;
* Includes both 40000 & 60000 * LIKE Operator (Pattern Matching) - Used with text.

| Pattern | Meaning                  |
| ------- | ------------------------ |
| `%`     | Any number of characters |
| `_`     | Exactly one character    |
  • Names starting with 'A'
      SELECT * FROM students
      WHERE name LIKE 'A%';
    
  • Names ending with 'n'
      SELECT * FROM students
      WHERE name LIKE '%n';
    
  • Names with 'a' in middle
      SELECT * FROM students
        WHERE name LIKE '%a%';