Introduction to SQL: Putting Database Concepts into Practice

In our previous article, we explored the fundamental concepts of relational databases.

Now, we'll see how these concepts come to life through SQL. Learning SQL is like learning a new language, and it takes practice. We'll take it step by step and relate everything to the concepts you've just learned.

What is SQL and Why Do We Use It?

"SQL" stands for Structured Query Language. It's the standard language for interacting with relational databases. Remember how we talked about tables, rows, and columns? We use SQL to create those tables, add data to them, retrieve information, and much more.

Think of SQL as a way to communicate with your database. It lets you ask the database to find, add, update, or delete information.

How to Run SQL Commands

Before we dive into specific SQL commands, let's talk about how you can actually run these commands. There are several ways to interact with a database using SQL, and we'll cover a few common methods:

1. Using pgAdmin (for PostgreSQL)

pgAdmin is a graphical user interface (GUI) for PostgreSQL. It's user-friendly and great for beginners:

  1. Open pgAdmin on your computer.
  2. Connect to your database server.
  3. In the Object Browser, right-click on your database and select "Query Tool".
  4. In the Query Editor that appears, you can type your SQL commands.
  5. To run a command, highlight it and click the "Execute" button (usually looks like a play button) or press F5.

2. Using psql (Command Line Interface for PostgreSQL)

psql is PostgreSQL's interactive terminal. It's a bit more advanced but very powerful:

  1. Open your command prompt or terminal.
  2. Type psql -U your_username -d your_database_name and press Enter.
  3. Enter your password when prompted.
  4. You'll see a prompt like your_database_name=#. This is where you can type your SQL commands.
  5. After typing a command, press Enter to execute it.
  6. Remember to end your SQL commands with a semicolon (;).

3. Using an Online SQL Editor

If you're starting out and don't want to install anything, you can use an online SQL editor:

  1. Websites like SQLFiddle (http://sqlfiddle.com) or DB Fiddle (https://www.db-fiddle.com) allow you to practice SQL online.
  2. Choose PostgreSQL as your database engine.
  3. In the left panel, you can create your tables and insert data.
  4. In the right panel, you can write and run your SQL queries.
  5. Click "Run" or "Execute" to see the results.

Tips for Running SQL Commands

  • Always end your SQL statements with a semicolon (;).
  • SQL keywords (like SELECT, FROM, WHERE) are not case-sensitive, but it's a standard convention to write them in ALL CAPS for readability. You'll see these keywords in the upcoming sections.
  • Be careful with DELETE and UPDATE commands - always double-check your WHERE clause to make sure you're affecting the right data.
  • If you're using a GUI tool like pgAdmin, you can often see the structure of your tables, which can be helpful when writing queries.

Now that you know how to run SQL commands, let's dive into some specific SQL syntax and see how it relates to the database concepts we learned earlier.

Basic SQL Commands and How They Relate to Database Concepts

Let's look at some basic SQL commands and see how they connect to the concepts we learned earlier.

To practice these skills and see it running, try running the following code snippets in your own environment.

Note: We will discuss the types and syntax of data and how/when to use them in a later section, but for now, you can copy and paste these values without totally understanding their meaning.

Creating a Table (CREATE TABLE)

Remember how we discussed tables as collections of related data? Here's how we create one using SQL. We will start with a command and then explain it after:

CREATE TABLE Students (
    StudentID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    DateOfBirth DATE,
    Grade INT,
    GPA DECIMAL(3,2),
    IsEnrolled BOOLEAN
);

Let's break this down:

  • CREATE TABLE Students: This tells the database we want to create a new table named "Students".
  • We define each column inside the parentheses, just like we discussed in the previous article.
  • StudentID INT PRIMARY KEY: Remember primary keys? This sets StudentID as our primary key.
  • Notice how we're using the data types we learned about: INT for whole numbers, VARCHAR for variable-length text with a limit of 50 characters, DATE for dates, DECIMAL for precise numeric values, and BOOLEAN for true/false values.

Inserting Data into a Table (INSERT INTO)

Once we have a table, we need to add data to it. This is how we add a single row:

INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth, Grade, GPA, IsEnrolled)
VALUES (1, 'John', 'Doe', '2005-03-15', 10, 3.75, TRUE);

This command adds a new student to our Students table. Each piece of data corresponds to a column in the order we list them.

As you can see, we list StudentID first, so the first argument we pass to values (1) is the value passed to this column.

Querying Data (SELECT)

Now that we have data in our table, let's retrieve it. This is where the SELECT command comes in:

SELECT * FROM Students;

This command retrieves all columns (* means "all") and all rows from the Students table. It's like asking to see everything in the table.

Updating Data (UPDATE)

Sometimes we need to change existing data. Here's how we do that:

UPDATE Students
SET Grade = 11
WHERE StudentID = 1;

This updates the Grade to 11 for the student with StudentID 1. Remember how we said primary keys uniquely identify each row? That's why we use StudentID in the WHERE clause, ensuring we're updating the right student.

Deleting Data (DELETE)

If we need to remove data, we use the DELETE command:

DELETE FROM Students WHERE StudentID = 1;

This removes the student with StudentID 1 from the table.

Always be careful with deleting. There is no undo button.

Applying More Advanced Concepts

Let's look at how we implement some of the more advanced concepts we discussed.

Foreign Keys

Remember how we said foreign keys create relationships between tables? Here's how we might create a Courses table that relates to our Students table:

CREATE TABLE Courses (
    CourseID INT PRIMARY KEY,
    CourseName VARCHAR(100),
    StudentID INT,
    FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

The FOREIGN KEY and REFERENCES line establishes the relationship between Courses and Students.

Indexes

We talked about indexes as a way to speed up data retrieval. Here's how we create an index:

CREATE INDEX idx_lastname ON Students(LastName);

This creates an index on the LastName column, which can make searching by last name much faster.

Constraints

Remember the different types of constraints we discussed? Here's how we implement them:

CREATE TABLE Students (
    StudentID INT PRIMARY KEY,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(100) UNIQUE,
    Age INT CHECK (Age >= 18),
    EnrollmentStatus VARCHAR(20) DEFAULT 'Active'
);
  • NOT NULL: FirstName and LastName can't be empty.
  • UNIQUE: No two students can have the same Email.
  • CHECK: Age must be at least 18.
  • DEFAULT: If no EnrollmentStatus is specified, it defaults to 'Active'.

Practicing What We've Learned

Now that we've seen how SQL implements the database concepts we learned, let's practice using a modern scenario. Imagine you're building a simple social media application. We'll create a basic structure for user profiles and posts. Try writing SQL commands to do the following:

  1. Create a Users table with UserID, Username, Email, DateJoined, and IsActive columns.

  2. Create a Posts table with columns for PostID, UserID (to link to the Users table), Content, PostDate, and Likes.

  3. Insert a few users into the Users table.

  4. Insert some posts for those users into the Posts table.

  5. Retrieve all posts from a specific user.

  6. Update the number of likes for a particular post.

  7. Find all users who joined in the last 30 days.

  8. Delete a specific post.

Here's a starting point for the Users table to help you get going:

CREATE TABLE Users (
    UserID INT PRIMARY KEY,
    Username VARCHAR(50) NOT NULL UNIQUE,
    Email VARCHAR(100) NOT NULL UNIQUE,
    DateJoined DATE DEFAULT CURRENT_DATE,
    IsActive BOOLEAN DEFAULT TRUE
);

Try to write the SQL commands for the rest of the tasks. Don't worry if you're unsure how to do all of these. The goal is to start thinking about how you'd use SQL to work with data in a real-world scenario.

Some things to consider:

  • How will you ensure that each user has a unique identifier?
  • How can you link posts to users?
  • What data type would be appropriate for the Content of a post?
  • How might you query to find recent users or popular posts?

Our next article will examine how we would have created this.

Remember, learning SQL is a journey. It's okay if everything doesn't click right away. Keep practicing with scenarios like this; soon, you'll be designing and querying databases for your web applications!

DatabasePostgresqlBeginner
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.