This lesson teaches you to run your first SQL command and essential querying techniques for retrieving and manipulating data in a database.
In this lesson, you’ll run your first SQL command and learn essential querying techniques. Before proceeding, ensure that you add six or seven extra entries to your database. Vary the prices, is_sale Boolean values (mix of true and false), inventory numbers, and creation times. This variety in data will help you observe different query outcomes later on.
Before you begin, run the following query to verify that your products table contains all the necessary entries:
Copy
Ask AI
SELECT * FROM public.productsORDER BY id ASC;
This query displays all rows from the products table, ordered ascendingly by the id column.
Open your database (for example, a database named “FastAPI”) in PgAdmin or your preferred SQL tool. Right-click on the database, select the query tool, and enter your command in the new tab. Once you’ve written your command, hit the play button (or execute command) to run it.The basic SQL query to retrieve all data from the products table is:
Copy
Ask AI
SELECT * FROM products;
When executed, this command returns every row from the products table. Since your database currently holds only one table, this query effectively dumps every entry in the collection. If your database included multiple tables, this command would solely display data from the products table.
SELECT Keyword: Indicates that you want to retrieve data.
Asterisk (*): Specifies that you want to return every column from the table.
FROM Clause: Identifies the source table (in this case, products) for retrieving the data.
Always include a semicolon (;) at the end of every SQL command. While some tools like PgAdmin may execute commands without it, other environments (e.g., the command line interface) require the semicolon.
If you only need particular columns, you can replace the asterisk with the desired column names. For example, to retrieve solely the product names:
Copy
Ask AI
SELECT name FROM products;
For multiple specific columns—say, id, name, and price—in that order, write:
Copy
Ask AI
SELECT id, name, price FROM products;
Although SQL keywords such as SELECT and FROM are not case-sensitive, it is good practice to capitalize them to clearly distinguish SQL reserved words from user-defined identifiers.
At times, default column names can be confusing, especially when multiple tables have similar column names (like “id”). To improve clarity, you can rename columns using the AS keyword. For instance, to rename the id column to products_id and is_sale to on_sale, use:
Copy
Ask AI
SELECT id AS products_id, is_sale AS on_sale FROM products;
The output will display the renamed columns. For example:
By understanding these basic SQL commands and techniques, you can efficiently query your database and tailor the output to your needs. Experiment with selecting specific columns and renaming them to enhance data clarity. Happy querying!