Retrieving Data with SELECT (DQL)

Introduction

Data Query Language (DQL) is a subset of SQL used to retrieve and manipulate data stored in databases. The SELECT statement is the most commonly used DQL command, allowing users to fetch specific data from tables based on various conditions.

1. Basic SELECT Statement

The SELECT statement is used to retrieve data from one or more tables.

Syntax:

SELECT column1, column2, ... FROM table_name;

Example:

SELECT first_name, last_name FROM employees;

This query retrieves the first_name and last_name columns from the employees table.

2. Retrieving All Columns

To select all columns from a table, use *:

SELECT * FROM employees;

This will return all columns for every row in the employees table.

3. Using WHERE Clause to Filter Data

The WHERE clause is used to filter records based on conditions.

Syntax:

SELECT column1, column2 FROM table_name WHERE condition;

Example:

SELECT * FROM employees WHERE department = 'IT';

This retrieves all employees working in the IT department.

4. Sorting Data with ORDER BY

The ORDER BY clause is used to sort query results in ascending (ASC) or descending (DESC) order.

Example:

SELECT * FROM employees ORDER BY salary DESC;

This retrieves all employees sorted by salary in descending order.

5. Limiting the Number of Rows

The LIMIT clause restricts the number of rows returned by a query.

Example:

SELECT * FROM employees LIMIT 5;

This returns only the first 5 records from the employees table.

6. Using DISTINCT to Remove Duplicates

The DISTINCT keyword ensures unique values are retrieved.

Example:

SELECT DISTINCT department FROM employees;

This query fetches a unique list of departments from the employees table.

7. Combining Conditions with AND, OR, and NOT

  • AND: Both conditions must be true.

  • OR: At least one condition must be true.

  • NOT: Negates a condition.

Example:

SELECT * FROM employees WHERE department = 'IT' AND salary > 60000;

This retrieves IT employees earning more than 60,000.

8. Using Aliases for Readability

Aliases rename columns or tables for better readability.

Example:

SELECT first_name AS Name, salary AS Salary FROM employees;

This renames first_name to Name and salary to Salary in the result set.

Conclusion

The SELECT statement is a powerful tool in SQL, allowing users to retrieve, filter, sort, and manipulate data efficiently. Understanding its various clauses will help in extracting meaningful insights from databases.

Next Steps:

  • Practice writing SELECT queries on sample databases.

  • Learn about JOINs to retrieve data from multiple tables.

  • Explore aggregate functions like COUNT, SUM, AVG, etc.

Stay tuned for more SQL learning! ๐Ÿš€

ย