W3. SQL Aliases Flashcards
Q: What is an SQL alias?
A: It’s a temporary name given to a table or column in a query to make names more readable.
Q: How do you create an alias in SQL?
A: Use the AS keyword, e.g., SELECT CustomerID AS ID FROM Customers;
Q: Is the AS keyword mandatory for creating aliases?
A: No, in most databases, you can omit AS, e.g., SELECT CustomerID ID FROM Customers;
Q: Write the syntax for creating an alias for a column.
SELECT column_name AS alias_name
FROM table_name;
Q: Write the syntax for creating an alias for a table.
SELECT column_name(s)
FROM table_name AS alias_name;
Q: Write a query to create aliases for CustomerID as “ID” and CustomerName as “Customer.”
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Q: How can you create an alias with spaces in it?
A: Surround the alias with square brackets or double quotes, e.g., AS [My Great Products] or AS “My Great Products”.
Q: Write a query to alias ProductName as “My Great Products” using square brackets.
SELECT ProductName AS [My Great Products]
FROM Products;
Q: How do you concatenate columns into a single alias?
A: Use the + operator (or CONCAT in MySQL), e.g., SELECT CONCAT(Address, ‘, ‘, PostalCode, ‘, ‘, City, ‘, ‘, Country) AS Address.
Q: Write a query to concatenate Address, PostalCode, City, and Country as “Address” (for MySQL).
SELECT CustomerName, CONCAT(Address, ‘, ‘, PostalCode, ‘, ‘, City, ‘, ‘, Country) AS Address
FROM Customers;
Q: How can aliases simplify SQL queries with multiple tables?
A: They make SQL statements shorter and more readable, especially when joining multiple tables.
Q: Write a query to join Customers and Orders using aliases “c” and “o” to select orders from “Around the Horn”.
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName = ‘Around the Horn’ AND c.CustomerID = o.CustomerID;
Q: When are aliases particularly useful?
A: When multiple tables are involved, functions are used, column names are long, or columns are combined.