SQL Data Retrieval: A Beginner's Guide

Akshobya KLAkshobya KL
2 min read

When working with databases, one of the most common tasks is fetching the data, and the way we do that in SQL is by using the SELECT statement. Think of it as the starting point for any interaction with our database it allows us to request exactly the information we need.

The Basic SELECT Query

The SELECT statement is all about querying data from one or more tables. The simplest form looks like this:

SELECT column1, column2 FROM table_name;
  • column1, column2: These are the specific columns you want to retrieve.

  • table_name: This is the table you're querying from.

Example: Fetching Usernames and Emails

Let’s say we have a users table and we want to retrieve the username and email for each user:

SELECT username, email FROM users;

This query will return a list of all usernames and their corresponding emails from the users table.

Retrieving All Columns with SELECT *

If we need all the data from a table, we don’t have to specify every column. Instead we can use the character * to select all columns.

Example: Fetching All Data from a Table

SELECT * FROM users;

This will pull every column and row from the users table, giving us all the data without having to manually list each column. While SELECT * is convenient.

Filtering Data with WHERE

Fetching everything from a table is not always what we need. Often, we are interested in specific rows. That’s where the WHERE clause comes into play. It allows us to filter the rows based on conditions.

Example: Fetching Users Older Than 30

SELECT username, email 
FROM users
WHERE age > 30;

This query retrieves only those users who are over the age of 30. The WHERE clause adds a filter to our query, making sure we only get the data we care about.

Selecting Unique Values with DISTINCT

A table might contain duplicate values, and we only want to retrieve unique entries. This is where the DISTINCT keyword helps.

Example: Getting Unique Cities from a Table

SELECT DISTINCT city FROM users;

Here, if multiple users live in the same city, this query will return each city only once, filtering out duplicates. It’s useful for creating lists of unique values.

0
Subscribe to my newsletter

Read articles from Akshobya KL directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akshobya KL
Akshobya KL

Full stack developer dedicated to crafting seamless user experiences. I thrive on transforming complex problems into elegant solutions!