“SQL Essentials: Mastering the Basics for Database Beginners”

SQL for Beginners

Neha Shukla
Ankercloud Engineering
6 min readAug 5, 2024

--

SQL

Structured Query Language (SQL) serves as the primary language for managing databases. It acts as a toolkit for interacting with stored data, enabling tasks such as creating, modifying, and retrieving information. SQL functions by issuing commands to databases, and directing their actions. This approach simplifies data organization and access, optimizing database management processes for efficiency and effectiveness.

Understanding SQL Commands:

A SQL command denotes a specific instruction or statement intended for executing particular operations on a database. These commands can be broadly categorized into four groups:

Types of SQL Commands:

  • Data Manipulation Language (DML) commands: These commands are employed to manipulate data within database tables. Examples include SELECT, INSERT, UPDATE, and DELETE.
  • Data Definition Language (DDL) commands: DDL commands are utilized to define the structure of database objects. Key commands encompass CREATE, ALTER, and DROP.
  • Data Control Language (DCL) commands: These commands regulate access to the database by granting or revoking permissions. Noteworthy commands in this category include GRANT and REVOKE.
  • Transaction Control Language (TCL) commands: TCL commands are pivotal for managing transactions within a database. They involve ROLLBACK, SAVEPOINT, COMMIT, and SET TRANSACTION.

Essential Points to Note:

SQL is case-insensitive.

SQL comments are delineated by “ — “.

It’s recommended to terminate SQL statements with a semicolon, especially for MySQL.

Let’s explore SQL clauses and operators relevant to Data Analysis and Manipulation (DML) with some examples:

Certainly! Let’s use the provided tables for students and courses in the sample database to demonstrate various SQL commands, clauses, and operators.

Table: students

| id  | Name  |
|-----|-------|
| 101 | Adam |
| 102 | Bob |
| 103 | Casey |

Table: course

| id  | course         |
|-----|----------------|
| 102 | English |
| 105 | Maths |
| 103 | Science |
| 107 | Computer Science |

SQL Database

SQL CREATE Database

CREATE DATABASE sample_database;

This command creates a new database named “sample_database”.

SQL DROP Database

DROP DATABASE sample_database;

This command deletes the “sample_database” database.

SQL RENAME Database

There isn’t a standard SQL command for renaming a database. Renaming is typically done through database management system-specific commands or tools.

SQL SELECT Database

SELECT DATABASE();

This command retrieves the name of the current database being used.

SQL Table

In SQL, a table is a structured data storage unit composed of rows and columns.

The CREATE TABLE command is used to create a new table, specifying its name and the data types of its columns. For example:

CREATE TABLE students (
id INT,
Name VARCHAR(255)
);

This command creates a table named “students” with columns for student IDs (id) and names (Name).

SQL DROP TABLE:

The DROP TABLE command is utilized to remove an existing table from the database, including its structure and all data stored within it.

SQL DELETE TABLE:

It’s important to note that there is no standard SQL command named DELETE TABLE. Instead, to remove specific rows from a table, the DELETE statement is typically used. For example:

DELETE FROM students;

SQL RENAME TABLE:

To rename an existing table, the ALTER TABLE command is employed. Here's an example of how it's used:

ALTER TABLE students RENAME TO new_students;

SQL TRUNCATE TABLE:
The TRUNCATE TABLE statement is utilized to remove all rows from a table while preserving the table’s structure. For example:

TRUNCATE TABLE course;

SQL COPY TABLE:
To copy a table in SQL using a database-independent method, you can utilize the CREATE TABLE statement in combination with a SELECT query.

CREATE TABLE new_table_name AS
SELECT * FROM course;

SQL TEMP TABLE:
The CREATE TEMPORARY TABLE command creates a temporary table that exists only for the duration of a session. Here’s an example:

CREATE TEMPORARY TABLE temp_students (
id INT,
Name VARCHAR(255)
);

SQL ALTER TABLE

ALTER TABLE students ADD COLUMN Age INT;

This command modifies an existing table by adding a new column.
These SQL commands allow you to manage tables within a database, including creating, modifying, and deleting them according to your requirements.

Let’s explore SQL clauses and operators relevant to Data Analysis and Manipulation (DML) with some examples:

  • SELECT :

To retrieve data from the table, we can use a SELECT statement:

SELECT * FROM students;
  • WHERE:

Comparison Operators

Greater than: >

Greater than or equal to >=

Less than: <

Less than or equal to: <=

Equal: =

Not equal: <>

Not equal: !=

If we want to filter products belonging to a specific category, we can use the WHERE clause:

SELECT * FROM students
WHERE id > 101;
  • ORDER BY:

To sort the products based on their prices in descending order, we can use the ORDER BY clause:

SELECT * FROM students 
ORDER BY Name ASC;
  • LIMIT:

If we want to retrieve only the top 5 most expensive products, we can combine the ORDER BY clause with the LIMIT clause:

SELECT * FROM students LIMIT 2;
  • GROUP BY:

The GROUP BY clause in SQL is utilized to categorize rows based on values in one or more columns. Each unique value in the specified column(s) forms a group, and SQL computes summary statistics for each group. These statistics include:

  • SUM: Represents the total sum of values in a numeric column.
  • AVG: Represents the average value for numeric column values.
  • COUNT: Indicates the total count of non-null values in a column.
  • MAX/MIN: Denotes the maximum or minimum value in a column, respectively.
SELECT course, COUNT(*) AS num_students 
FROM course
GROUP BY course;
  • HAVING:

If we want to filter the categories having an average price greater than $500, we can use the HAVING clause:

SELECT course, COUNT(*) AS num_students 
FROM course
GROUP BY course
HAVING AVG(price) > 500;

SQL Wildcard Characters:

In SQL, wildcard characters play a crucial role in pattern matching within strings when used alongside the LIKE operator. They enable users to match parts of a value based on specific patterns. Here’s an overview of commonly used wildcard characters in SQL:

  1. % (Percent Sign): Represents zero, one, or multiple characters in a string.
-- Example: Selecting all courses that start with the letter 'M':
SELECT * FROM course WHERE course LIKE 'M%';

2. _ (Underscore): Represents a single character in a string.

-- Example: Selecting all courses with a name of exactly six characters:
SELECT * FROM course WHERE course LIKE '______';

3. [] (Square Brackets): Used to specify a range or set of characters.

-- Example: Selecting all courses that start with the letters 'A', 'B', or 'C':
SELECT * FROM course WHERE course LIKE '[A-C]%';

4. [^] (Negation within Square Brackets): The caret (^) inside square brackets negates the character set.

-- Example: Selecting all courses that do not start with the letter 'M':
SELECT * FROM course WHERE course LIKE '[^M]%';
  • JOIN:

A SQL JOIN operation combines rows from multiple tables based on a related column, facilitating comprehensive data retrieval and analysis across tables Various types of joins include:

Types of Joins:

INNER JOIN: Retrieves data from related tables based on a specified condition, dropping rows without matching values in both tables.

Example:

SELECT students. Name, course.course
FROM students
INNER JOIN course ON students.id = course.id;

LEFT JOIN Retrieves data from multiple tables based on a specified condition, including all rows from the left table and NULL values for unmatched rows from the right table.

Example:

SELECT students. Name, course.course
FROM students
LEFT JOIN course ON students.id = course.id;

RIGHT JOIN: Includes all rows from the right table and NULL values for unmatched rows from the left table.

Example:

SELECT students. Name, course.course
FROM students
RIGHT JOIN course ON students.id = course.id;

FULL OUTER JOIN: Retrieves data from both tables, including all rows from both tables, along with NULL values for unmatched rows.

Example:

SELECT students. Name, course.course
FROM students
FULL OUTER JOIN course ON students.id = course.id;

These joint operations are crucial for combining data from different tables based on related columns, offering a comprehensive view of interconnected information for analysis and decision-making.

--

--