? Unlock the Power of SQL Indexing with Simple Query Examples!
Karan Nayyar
Data Engineer at Kmart Group AU | Big Data | Snowflake | AWS | Py-Spark | SQL | Python | Kafka , IBM Certified Big Data Engineer
Indexing is one of the most effective ways to boost query performance, especially when working with large datasets. Here are a few practical examples of how to use indexing to improve your day-to-day SQL queries:
?? 1. Indexing a Frequently Queried Column
If you often search based on a specific column, indexing that column can drastically speed up your queries.
-- Create an index on the 'last_name' column
CREATE INDEX idx_last_name ON employees(last_name);
-- Query to fetch employees by last name
SELECT * FROM employees WHERE last_name = 'Smith';
?? 2. Indexing a Foreign Key for Faster Joins
When joining tables, foreign keys are frequently used. Indexing them can speed up JOIN operations significantly.
-- Create an index on the foreign key 'department_id'
CREATE INDEX idx_department_id ON employees(department_id);
-- Query to fetch employees and their department details
SELECT e.*, d.department_name
FROM employees e
JOIN departments d ON
e.department_id = d.department_id;
?? 3. Indexing a Column Used in ORDER BY
Sorting large datasets can be time-consuming, but adding an index to the column used in the ORDER BY clause helps improve performance.
领英推荐
-- Create an index on the 'salary' column
CREATE INDEX idx_salary ON employees(salary);
-- Query to fetch employees sorted by salary
SELECT * FROM employees ORDER BY salary DESC;
?? 4. Composite Indexes for Multiple Columns
When querying multiple columns, creating a composite index helps optimize searches.
-- Create a composite index on 'first_name' and 'last_name'
CREATE INDEX idx_name ON employees(first_name, last_name);
-- Query to fetch employee by full name
SELECT * FROM employees WHERE first_name = 'John' AND last_name = 'Doe';
?? Why Indexing Matters:
Are you already using indexes to boost your query performance? Share your experience below!??
#DataEngineering #SQL #DatabaseOptimization #PerformanceTuning #SQLIndexing #TechTips #DataManagement
Software Engineer | ReactJs | Redux | RTK | Javascript | Typescript | RTL | Jest
5 个月really informative ??