This module covers CRUD Operations, Sorting and Limiting, Aliases and Expressions.
In this chapter, we will explore the core **CRUD** operations in SQL: `SELECT`, `INSERT`, `UPDATE`, and `DELETE`. These operations are essential for interacting with relational databases. We'll also cover how to filter data using `WHERE` clauses along with various comparison operators like `IN`, `LIKE`, and `BETWEEN`.
The `SELECT` statement is used to retrieve data from one or more tables in a database.
SELECT column1, column2 FROM table_name;
The `WHERE` clause is used to filter records based on specific conditions.
SELECT * FROM customers WHERE age > 25;
The `IN` operator is used to check if a value exists in a specified list of values.
SELECT * FROM employees WHERE department IN ('Sales', 'Marketing');
The `LIKE` operator is used to search for a specified pattern in a column.
SELECT * FROM customers WHERE name LIKE 'S%';
The `BETWEEN` operator is used to filter values within a range.
SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
The `INSERT INTO` statement is used to add new records to a table.
INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');
The `UPDATE` statement is used to modify existing records in a table.
UPDATE users SET email = 'john.new@example.com' WHERE id = 1;
The `DELETE` statement is used to remove records from a table.
DELETE FROM users WHERE id = 1;
Sorting and limiting data is a fundamental aspect of working with databases. In SQL, we use the `ORDER BY` clause to sort records in ascending or descending order, and the `LIMIT`, `TOP`, or `FETCH` clauses to control the number of rows returned. These operations are essential for efficiently retrieving and presenting data.
The `ORDER BY` clause is used to sort records in a result set based on one or more columns. By default, the sorting is done in ascending order (`ASC`). To sort in descending order, you can use the `DESC` keyword.
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC;
You can sort by multiple columns and specify different orders for each column:
SELECT column1, column2
FROM table_name
ORDER BY column1 DESC, column2 ASC;
By default, `NULL` values are treated as the lowest possible value when sorting. You can control this behavior using the `NULLS FIRST` or `NULLS LAST` clauses (supported in PostgreSQL and other modern databases).
SELECT column1
FROM table_name
ORDER BY column1 ASC NULLS LAST;
The `LIMIT` clause is used to restrict the number of rows returned by a query. It's commonly used together with `OFFSET` to implement pagination.
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC
LIMIT 10 OFFSET 20;
This query returns rows 21 to 30 (10 rows total) from the sorted result set.
Different database systems may use different syntax for limiting results:
-- Get the top 5 highest-paid employees
SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
-- Paginate through results (showing rows 21-30)
SELECT product_id, product_name, price
FROM products
ORDER BY price ASC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
In SQL, **aliases** allow you to temporarily rename columns or tables in your query results. This can improve readability or help avoid column name conflicts. **Expressions** enable you to perform calculations or manipulations on data within the query.
The `AS` keyword is used to rename columns or tables in the result set. It's optional, but recommended for clarity.
SELECT customer_name AS FullName,
order_date AS OrderDate
FROM customers;
The `CASE` statement allows you to create conditional expressions within your SQL queries, similar to an if-else structure.
SELECT product_name,
CASE
WHEN price < 10 THEN 'Cheap'
WHEN price BETWEEN 10 AND 50 THEN 'Moderate'
ELSE 'Expensive'
END AS PriceCategory
FROM products;
SQL provides many built-in functions for string manipulation, rounding numbers, converting data types, and more.
SELECT
LENGTH(first_name) AS NameLength,
ROUND(price * 1.075, 2) AS TaxInclusivePrice,
LOWER(last_name) AS LowercaseName
FROM users;
The `||` operator is used for string concatenation in SQL.
SELECT first_name || ' ' || last_name AS FullName
FROM users;
The `GREATEST` and `LEAST` functions allow you to find the maximum or minimum value among multiple expressions.
SELECT LEAST(price, discounted_price) AS FinalPrice
FROM products;
Question 1 of 15