Retrieving data is one of the most fundamental operations you will perform in SQL. This chapter covers everything you need to know about querying data from a database, from the basics of the SELECT statement to advanced techniques like subqueries, joins, and aggregate functions.
Demo Key: The SELECT statement is used to query the database and retrieve data. It allows you to specify which columns you want to retrieve and from which table.Demo Value
SELECT column1, column2, ...
FROM table_name;
SELECT first_name, last_name FROM employees;
SELECT
: Specifies the columns to retrieve.first_name, last_name
: The columns to retrieve.FROM
: Specifies the table to query.employees
: The table to query.first_name | last_name |
---|---|
John | Doe |
Jane | Smith |
Mike | Johnson |
To retrieve all columns from a table, use the asterisk (*) wildcard.
SELECT * FROM employees;
SELECT
: Indicates that you want to retrieve data from the database.*
: Wildcard character that represents all columns.FROM
: Specifies the table from which to retrieve the data.table_name
: The name of the table from which to retrieve the data.employee_id | first_name | last_name | department | salary |
---|---|---|---|---|
1 | John | Doe | HR | 50000 |
2 | Jane | Smith | Finance | 60000 |
3 | Mike | Johnson | IT | 70000 |
The LIMIT clause is used to specify the number of records to return.
SELECT column1, column2, ...
FROM table_name
LIMIT number;
SELECT first_name, last_name FROM employees LIMIT 2;
LIMIT 2
: Limits the result set to 2 records.
first_name | last_name |
---|---|
John | Doe |
Jane | Smith |
To implement pagination, you can use the LIMIT clause with an OFFSET clause.
SELECT column1, column2, ...
FROM table_name
LIMIT number OFFSET offset;
SELECT first_name, last_name FROM employees LIMIT 2 OFFSET 1;
LIMIT 2 OFFSET 1
: Returns 2 records starting from the second record.
first_name | last_name |
---|---|
Jane | Smith |
Mike | Johnson |
Retrieving data with SQL is a fundamental skill for anyone working with databases. This chapter covered the basics of the SELECT statement and limiting results with the LIMIT clause. Understanding these concepts will enable you to effectively query and analyze data stored in relational databases. Happy coding !❤️