Querying with SQL
Useful tools in SQL
Please do not copy without permission. © ExploreAI 2023.
Useful tools in SQL
Useful tools
Often, SQL result sets are made to examine a subset
of data. Here are two handy tools we can use to make
them readable, and save results for future use.
We often draw upon different databases and tables
which may have complex column names. The SQL
keyword AS is a handy tool to rename columns in a
query result.
At times, it is useful to save results so we can access
them later. INSERT INTO can be used to save a query
as well. Instead of specifying VALUES, we use a query.
Useful tools in SQL
Aliasing
| Aliasing is a technique that uses the AS keyword to temporarily rename a table or column in a
query for simplification and readability.
Syntax: SELECT col_name_in_db AS new_col_name FROM db.table;
Table_2 Results
col1 col2 col3 SELECT Initials col2 col3
col1 AS Initials
z 68 s z 68 s
col2,
x 1 l col3, x 1 l
FROM
w 7 l db.Table_2; w 7 l
y 56 m y 56 m
Data Query Language
Aliasing
You cannot rename a column with AS and use
the alias in a WHERE clause.
AS creates an alias or shortcut name for a
column in a SQL results set. Renaming
columns in a results set makes the table more
readable.
Always choose descriptive names such as
first_name, last_name instead of name,
and is_subscribed instead of sub.
Useful tools in SQL
Saving a results set in a table
| To save useful results as a table, we can use INSERT INTO to save the results of a query to an
existing table.
Syntax: INSERT INTO table_name(col_name(s)) SELECT col(s) FROM db_name.table_name;
CREATE TABLE
Saved_table(
Initials VARCHAR(255),
Table_2 Cost INT Saved_table
);
col1 col2 col3 INSERT INTO
Initials Cost
z 68 s Saved_table( z 68
Initials,
x 1 l Cost x 1
w 7 l ) w 7
SELECT
y 56 m col1,
y 56
col2
FROM
db.Table_2;
Useful tools in SQL
Saving a results set in a table
This involves three steps:
1. Create a new table called Saved_table, with Initials
CREATE TABLE
Saved_table( and Cost as the column names.
Initials VARCHAR(255),
Cost INT
);
INSERT INTO
Saved_table(
Initials,
Cost 2. Query the columns/data we want to save (SELECT col1
)
and col2).
SELECT
col1,
col2
FROM
db.Table_2;
3. Insert the results of the query (col1 and col2) into the
new table (Initials and Cost) – INSERT INTO.