Changing a column name in a table

  1. How do use ALTER TABLE to change the name of an existing column in an SQL table?

  2. Why would an SQL user use
    SELECT name AS ‘______’ FROM movies;
    instead of just changing the name of the column in the table to begin with?

  1. have you checked documentation? https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

  2. mysql can also do sum(), lets say we want to see how much money we made we can do:

// not a real example
SELECT sum(price) FROM movies

this will gives use a column named sum(prices), which is not a nice name, i would certainly use AS for aliasing.

i am sure there are plenty more examples for aliasing, sometimes to teach a concept, the exercise starts with a simple example to keep it simple. The drawback of this approach is that in that particular case aliasing isn’t very useful, while aliasing can be very useful.

Thanks for the quick reply. The link for commands is extremly helpful. I was trying to find a resource just like that.

In your “not real example” does sum(price) refer to the sum of all the values in the hypothetical colum price? And if so would the result not be a sinlge value and not a column of values?

yes, very good :slight_smile:

Seems i made to big a leap, it will be a single value. However, SQL is often not used on its own, we use other languages as well. To then access the value of the column we need to do: row->column_name (so row->sum(price)), while if we used an alias, we could just do:

row->profit

assuming:

SELECT sum(price) AS profit FROM movies;

another good example would be if you have two tables with the same column name, and you would do a join operation, you need aliases as well, otherwise you have problem (i experienced this in python, php and more).

Then again, using only SQL without any additional programming language is really uncommon, so certain things might only start falling into place when you do some projects where SQL is used in combination with another language (c#, python, php, ruby, golang or something else)

When you typed ‘row->profit’ is the ‘-’ a subtraction sign? If so then ‘->’ seems like an odd pairing. Does it mean subtract only if it is greater than price?

what syntax would you prefer then? i know to many:

row.profit
row['profit']

anyway, row is usually a kind of object/dictionary, and then we use the column name (profit) as property/key to get the value.