Retrieving data with SQL

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.

What is the SELECT Statement?

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_namelast_name
JohnDoe
JaneSmith
MikeJohnson

Selecting All Columns

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_idfirst_namelast_namedepartmentsalary
1JohnDoeHR50000
2JaneSmithFinance60000
3MikeJohnsonIT70000

Limiting Results with LIMIT Clause

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_namelast_name
JohnDoe
JaneSmith

Pagination with LIMIT and OFFSET

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_namelast_name
JaneSmith
MikeJohnson

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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India