<aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Fundamental SQL Syntax
-- Select all columns from a table
SELECT * FROM table_name;
-- Select specific columns from a table
SELECT column1, column2 FROM table_name;
-- Filtering rows with WHERE clause
SELECT * FROM table_name WHERE condition;
-- Sorting results with ORDER BY
SELECT * FROM table_name ORDER BY column1 ASC; -- ASC for ascending, DESC for descending
SELECT *
command is the simplest way to retrieve all data from a table. However, it is often not recommended for production queries because it can retrieve unnecessary data. It's better to select only the columns you need.WHERE
clause allows you to filter records based on specific conditions, making it a powerful tool for data retrieval. This is the foundation of SQL querying and is used to hone in on the exact data you need.ORDER BY
clause sorts the result set by one or more columns. ASC
specifies ascending order (default), while DESC
specifies descending order.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Data Querying
-- Basic SELECT statement
SELECT column1, column2 FROM table_name;
-- Using WHERE clause for filtering
SELECT * FROM table_name WHERE condition;
-- Aggregate functions: COUNT, SUM, AVG, MAX, MIN
SELECT COUNT(column_name) FROM table_name;
SELECT SUM(column_name) FROM table_name;
-- GROUP BY clause
SELECT column_name, COUNT(*) FROM table_name
GROUP BY column_name;
-- HAVING clause (used with GROUP BY)
SELECT column_name, COUNT(*) FROM table_name
GROUP BY column_name
HAVING COUNT(*) > value;
-- JOIN operations
SELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column;
SELECT
statement is the most common SQL command, used to retrieve data from one or more tables. Understanding how to write efficient SELECT
statements is key to extracting meaningful insights from your data.WHERE
clause helps you narrow down the results to only those that meet specific criteria, making your queries more targeted and relevant.GROUP BY
clause is used with aggregate functions to group the result set by one or more columns. This is useful for creating summaries, such as counting the number of records in each category.HAVING
clause is similar to WHERE
but is used to filter groups created by the GROUP BY
clause. This allows you to apply conditions to aggregated data.JOIN
operations combine rows from two or more tables based on a related column between them. Understanding different types of joins (INNER JOIN, LEFT JOIN, etc.) is crucial for working with relational databases.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Data Manipulation Language (DML)
-- Insert data into a table
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
-- Update existing data
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
-- Delete data from a table
DELETE FROM table_name
WHERE condition;
INSERT INTO
statement is used to add new records to a table. Each value must correspond to a specific column in the table. This command is fundamental for populating your database with data.UPDATE
command modifies existing records in a table. The WHERE
clause is critical here; without it, all records in the table will be updated, which is often not the desired outcome.DELETE
statement removes records from a table. Similar to UPDATE
, the WHERE
clause is necessary to target specific records. Without it, all records will be deleted.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Transactions
-- Start a transaction
BEGIN TRANSACTION;
-- Commit a transaction
COMMIT;
-- Rollback a transaction
ROLLBACK;
COMMIT
command finalizes the transaction, making all changes permanent. Once committed, the changes cannot be rolled back.ROLLBACK
command undoes all changes made during the transaction. This is essential for error handling and ensuring data integrity.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Common Error Handling
-- Handling NULL values
SELECT column_name FROM table_name
WHERE column_name IS NULL;
-- Avoiding SQL injection (parameterised queries)
SELECT column_name FROM table_name
WHERE column_name = ?;
<aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Data Definition Language (DDL)
-- Create a new table
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
-- Alter an existing table (add a column)
ALTER TABLE table_name
ADD column_name datatype;
-- Drop a table
DROP TABLE table_name;
CREATE TABLE
statement is used to create a new table in the database. Each column is defined with a name and a data type, which specifies the kind of data it can hold (e.g., INTEGER, VARCHAR, DATE).ALTER TABLE
statement allows you to modify an existing table structure, such as adding new columns. This is essential when your database evolves, and you need to accommodate new types of data.DROP TABLE
command is used to delete an entire table from the database. This is irreversible, so it’s important to use it with caution.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Advanced Queries
-- Subqueries
SELECT column1 FROM table_name
WHERE column2 = (SELECT column3 FROM another_table WHERE condition);
-- UNION operation
SELECT column1 FROM table_name1
UNION
SELECT column1 FROM table_name2;
-- CASE statement for conditional logic
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
UNION
operator combines the results of two or more SELECT
statements into a single result set. This is useful when you need to merge data from different tables or queries.CASE
statement allows you to add conditional logic to your SQL queries. This is similar to IF-THEN-ELSE
statements in programming languages, enabling dynamic results based on different conditions.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Useful SQL Functions
-- String functions
SELECT UPPER(column_name) FROM table_name;
SELECT LOWER(column_name) FROM table_name;
SELECT LENGTH(column_name) FROM table_name;
-- Date functions
SELECT CURRENT_DATE;
SELECT CURRENT_TIME;
SELECT EXTRACT(YEAR FROM date_column) FROM table_name;
-- Numeric functions
SELECT ROUND(column_name, decimals) FROM table_name;
SELECT ABS(column_name) FROM table_name;
UPPER()
converts a string to uppercase, which is useful for standardizing text data.LOWER()
converts a string to lowercase, useful for case-insensitive comparisons.LENGTH()
returns the number of characters in a string. This can be helpful for validating or analyzing text data.CURRENT_DATE
returns the current date, which is often used in reporting and scheduling queries.CURRENT_TIME
returns the current time, useful for timestamping events.EXTRACT()
retrieves a specific part of a date, such as the year or month. This is valuable for time-based analysis, such as yearly trends.ROUND()
rounds a number to a specified number of decimal places, which is essential for financial calculations.ABS()
returns the absolute value of a number, useful in situations where you need non-negative results.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Indexes and Keys
-- Create an index
CREATE INDEX index_name ON table_name (column_name);
-- Create a unique index
CREATE UNIQUE INDEX index_name ON table_name (column_name);
-- Add a primary key
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
-- Add a foreign key
ALTER TABLE table_name
ADD CONSTRAINT fk_name
FOREIGN KEY (column_name) REFERENCES other_table(column_name);
<aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> Common SQL Clauses
-- DISTINCT clause
SELECT DISTINCT column_name FROM table_name;
-- LIMIT clause
SELECT * FROM table_name LIMIT number_of_rows;
-- OFFSET clause
SELECT * FROM table_name LIMIT number_of_rows OFFSET offset_value;
DISTINCT
clause eliminates duplicate records in your result set. This is especially useful when you need to list unique values from a column.LIMIT
clause restricts the number of rows returned by a query. This is helpful for previewing large datasets or fetching a specific subset of results.OFFSET
clause, used in combination with LIMIT
, allows you to skip a specific number of rows before starting to return rows. This is useful for pagination in web applications.
</aside><aside> <img src="/icons/code_orange.svg" alt="/icons/code_orange.svg" width="40px" /> SQL Best Practices
Explanation: Well-named tables and columns reduce the cognitive load on developers and analysts, making it easier to understand the data structure and intent behind each query.
Explanation: Normalization involves organizing your data so that redundancy is minimized, typically by splitting large tables into smaller, related tables. This leads to more efficient updates and queries.
Explanation: Indexes make data retrieval faster, but they also consume space and can slow down write operations. Knowing when and where to use indexes is key to maintaining a balanced database.
Explanation: SELECT *
can lead to inefficient queries, especially in large tables. By specifying only the columns you need, you reduce the amount of data processed and transferred.
Explanation: Readable queries are easier to debug and maintain. Using subqueries and comments helps to break down complex logic, making it easier for others (and your future self) to understand.
Professional Practices: Following these best practices is essential for writing efficient, maintainable SQL code. In the full course, you’ll learn advanced techniques for query optimization, indexing strategies, and database design.
</aside>