You are currently viewing SQL :1.3 SQL SELECT

SQL :1.3 SQL SELECT

SELECT Tutorial

In this tutorial, we’ll dive into the basics of the SQL SELECT statement. SQL (Structured Query Language) is a powerful tool used for managing and manipulating data in relational database systems. The SELECT statement is one of the most fundamental and commonly used SQL commands, allowing us to retrieve data from a database.

Prerequisites

Before we start, make sure you have:

  • Installed a relational database management system (like MySQL, PostgreSQL, SQLite, etc.)
  • A basic understanding of databases ,tables and basics of html(optional)

What is SQL SELECT?

The SQL SELECT statement is used to fetch data from a database table. It allows you to specify the columns you want to retrieve and conditions to filter rows. Here’s the basic syntax:

SELECT column1, column2, ...
FROM table_name;

Sample Database

For this tutorial, we’ll use a simple employees table with the following structure:

  • employee_id (INT)
  • first_name (VARCHAR)
  • last_name (VARCHAR)
  • department (VARCHAR)
  • salary (INT)

SQL SELECT Examples

1. Retrieve All Columns

Let’s start by selecting all columns from the employees table:

SELECT * FROM employees;
  • This query will return all rows and all columns from the employees table.

2. Retrieve Specific Columns

You can specify the columns you want to retrieve:

SELECT first_name, last_name FROM employees;
  • This query will return only the first_name and last_name columns for all rows.

3. Filtering Rows with WHERE

You can filter rows using the WHERE clause:

SELECT * FROM employees WHERE department = 'IT';
  • This query will return all columns for employees in the ‘IT’ department.

4. Using Logical Operators

Combine conditions with AND or OR:

SELECT * FROM employees WHERE department = 'IT' AND salary > 50000;
  • This query will return employees in the ‘IT’ department with a salary greater than 50000.

5. Sorting Results with ORDER BY

Sort the results using ORDER BY:

SELECT * FROM employees ORDER BY salary DESC;
  • This query will return all columns, sorted by salary in descending order.

6. Limiting Results with LIMIT

Limit the number of rows returned:

SELECT * FROM employees LIMIT 5;
  • This query will return the first 5 rows from the employees table.

7. Combining Conditions

Combine multiple conditions with logical operators:

SELECT * FROM employees WHERE department = 'HR' OR department = 'Finance';
  • This query will return employees from the ‘HR’ or ‘Finance’ departments.

Conclusion

Congratulations! You’ve learned the basics of the SQL SELECT statement. This is just the beginning of what you can do with SQL. Practice these examples on your own database to solidify your understanding. As you become more comfortable, you can explore more advanced topics like joins, aggregates, and subqueries.

Leave a Reply