Syntax error at or near alter

I'm trying to run a query to update the user password using. alter user dell-sys with password 'Pass@133'; But because of - it's giving me error like, ERROR: syntax error at or near "-"...

I’m trying to run a query to update the user password using.

alter user dell-sys with password 'Pass@133';

But because of - it’s giving me error like,

ERROR:  syntax error at or near "-"
LINE 1: alter user dell-sys with password 'Pass@133';
                       ^

Can Anyone shade a light on it?

Kai - Kazuya Ito's user avatar

asked Sep 6, 2013 at 11:18

OpenCurious's user avatar

1

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That’s why it’s giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

answered Sep 6, 2013 at 12:24

Atul Arvind's user avatar

Atul ArvindAtul Arvind

15.5k6 gold badges47 silver badges58 bronze badges

0

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

answered Sep 6, 2013 at 11:19

Clodoaldo Neto's user avatar

Clodoaldo NetoClodoaldo Neto

115k25 gold badges225 silver badges250 bronze badges

2

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; — i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

a_horse_with_no_name's user avatar

answered Apr 27, 2020 at 17:32

Walters 's user avatar

Walters Walters

611 silver badge4 bronze badges

I got the similar error below:

ERROR: syntax error at or near «)»
LINE 4: );

Because I put a trailing comma mistakenly as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20),
               -- ↑ A trailing comma
);

So, I removed the a trailing comma as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20)
               -- ↑ No trailing comma
);

Then, the error was solved:

CREATE TABLE

answered Jan 22 at 13:33

Kai - Kazuya Ito's user avatar

I’m trying to run a query to update the user password using.

alter user dell-sys with password 'Pass@133';

But because of - it’s giving me error like,

ERROR:  syntax error at or near "-"
LINE 1: alter user dell-sys with password 'Pass@133';
                       ^

Can Anyone shade a light on it?

Kai - Kazuya Ito's user avatar

asked Sep 6, 2013 at 11:18

OpenCurious's user avatar

1

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That’s why it’s giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

answered Sep 6, 2013 at 12:24

Atul Arvind's user avatar

Atul ArvindAtul Arvind

15.5k6 gold badges47 silver badges58 bronze badges

0

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

answered Sep 6, 2013 at 11:19

Clodoaldo Neto's user avatar

Clodoaldo NetoClodoaldo Neto

115k25 gold badges225 silver badges250 bronze badges

2

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; — i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

a_horse_with_no_name's user avatar

answered Apr 27, 2020 at 17:32

Walters 's user avatar

Walters Walters

611 silver badge4 bronze badges

I got the similar error below:

ERROR: syntax error at or near «)»
LINE 4: );

Because I put a trailing comma mistakenly as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20),
               -- ↑ A trailing comma
);

So, I removed the a trailing comma as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20)
               -- ↑ No trailing comma
);

Then, the error was solved:

CREATE TABLE

answered Jan 22 at 13:33

Kai - Kazuya Ito's user avatar

Содержание

  1. 8 Tips Absolute Beginners Can Use to Fix SQL Queries
  2. 1. Place Open and Close Parentheses First
  3. 2. Don’t Put a Comma at the End of a Column or Table Sequence
  4. 3. Use Partial Query Evaluation to Debug Long SQL Queries
  5. 4. Pay Attention to Column and Table Names
  6. 5. Compare Compatible Data Types Only
  7. 6. Use IS NULL When Comparing NULL Values
  8. 7. Always Include the JOIN Condition
  9. 8. Include Non-Aggregated Columns from the SELECT List in GROUP BY Columns
  10. Try It Yourself!
  11. SQL Error: «Syntax error at or near:»
  12. Overview
  13. Error Message
  14. Troubleshooting
  15. Overview
  16. Error Message
  17. Troubleshooting
  18. SQL near «SELECT»: syntax error
  19. Posts: 6
  20. 1 Topic by vaattikarjalainen 2017-08-09 23:54:38 (edited by vaattikarjalainen 2017-08-09 23:55:22)
  21. Topic: SQL near «SELECT»: syntax error
  22. 2 Reply by DriveSoft 2017-08-10 15:25:41
  23. Re: SQL near «SELECT»: syntax error
  24. 3 Reply by vaattikarjalainen 2017-08-10 22:50:46 (edited by vaattikarjalainen 2017-08-10 22:51:03)
  25. Re: SQL near «SELECT»: syntax error
  26. 4 Reply by DriveSoft 2017-08-10 22:57:29
  27. Re: SQL near «SELECT»: syntax error
  28. 5 Reply by vaattikarjalainen 2017-08-11 06:47:02
  29. Re: SQL near «SELECT»: syntax error
  30. 6 Reply by DriveSoft 2017-08-11 10:24:41
  31. Re: SQL near «SELECT»: syntax error

8 Tips Absolute Beginners Can Use to Fix SQL Queries

Code errors are common – and frustrating. And when you’re just learning SQL, it can be very challenging to find and fix your mistakes. In this post, we’ll show you eight ways to solve or eliminate common SQL coding errors.

Today, we’ll talk about some tips the SQL beginner can use to avoid several common errors. These tips work in any database environment. As we go along, we’ll be showing some error messages. The exact wording of your error messages may be a little different, but don’t worry; each database engine has their own variants, but the meaning is the same.

That being said, we won’t be focusing on error messages. Instead, we’ll pinpoint the actual cause of the problem (such as forgetting a parenthesis or a quotation mark). This way, you’ll learn how to bypass the issue in the first place.

Ready? Let’s begin!

1. Place Open and Close Parentheses First

Remembering the closing character is key to eliminating unbalanced parentheses, quotes, double quotes, or square brackets. Best practices suggest typing both characters first (open and close) and then typing whatever goes inside.

The following example shows an error when parentheses are not balanced:

Example 1: Unbalanced parentheses

2. Don’t Put a Comma at the End of a Column or Table Sequence

Commas act as a separator in SQL. There should not be any commas between FROM and the first table name or after the final table name. The same idea applies to column definition: when you create a table, be sure not to type an extra comma after the final column name.

This is a really common error.

Example 2: An extra comma

3. Use Partial Query Evaluation to Debug Long SQL Queries

Many SQL clients like Navicat or pgAdmin allow the partial execution of a query. You can do this by using your mouse to highlight part of the code. Using this divide-and-conquer technique, you can easily isolate and fix errors. Obviously, the marked part must be valid SQL.

The upcoming query has two errors. If we execute the opening line of the query, we can see the first problem. (Hint: the «llastname» column doesn’t exist.)

Example 3: An incorrect column name

However if we execute the complete SQL statement, we get an error related to unbalanced parentheses:

Example 4: Subquery with wrong parentheses

We can also mark a subquery and execute it individually, as in the next example:

Example 5: Incorrect function name

4. Pay Attention to Column and Table Names

Pay very close attention when typing column names or table names. If possible, try to copy and paste the name from a command you know is correct – preferably one that’s already executed properly. Best practices suggest copying and pasting names even if you think it’s more time-consuming than typing.

Having a misspelled column name or referring to a column in a table not in the FROM clause is very common indeed. Always look for typos in the column name, make sure the table in the FROM has this column, and make sure that the table is mentioned in FROM .

Example 6: Incorrect table name

Another good practice is to use a table alias or a table name as a column prefix. This is doubly important when you have two or more tables in the <>FROM clause. The following error can appear if you refer to two identically-named columns in different tables:

Example 7: Ambiguous column names

Example 8: Prefixed column names

To fix these errors, add the table name before the column name. (In the above example, that would be employee.depto_id and department.depto_id instead of just depto_id .)

5. Compare Compatible Data Types Only

When you write comparison conditions in the WHERE clause, make sure both data types are compatible with the comparison operator and with each other. If this is not possible, you may have to cast one of the data types. The general rule is to compare numbers against numbers, character strings against character strings, etc.

Some database systems automatically convert data types where possible; others provide enhanced data type conversions (i.e. a TIMESTAMP value can be automatically converted to a DATE before comparisons). Still other database services don’t offer conversions at all. So it is best to look out for these potential issues yourself.

Anyway, the following SQL code gets a data mismatch error because a CHAR string is being compared with an integer value:

Example 9: Mismatched data types

No operator matches the given name and argument type(s). You might need to add explicit type casts to solve this one.

6. Use IS NULL When Comparing NULL Values

If you only need to verify whether a column has a NULL value, pay special attention to which expressions you use. One common mistake is to use = NULL or <> NULL , but these expressions are not syntactically valid. Use IS NULL and IS NOT NULL clauses instead.

Let’s see the incorrect and correct samples:

Example 10: Incorrect NULL comparison

Example 11: Correct NULL comparison

7. Always Include the JOIN Condition

There is more than one valid way to do a join in SQL. The traditional way is to list all the tables to be joined in the FROM clause and put the join conditions in the WHERE clause to build pairs of records. The other (more declarative) way is to use the JOIN clause and list the join conditions after the ON clause. Both are syntactically equivalent, but you should know how to identify the join condition for both.

Here we have two valid joins:

Example 12: Two equivalent joins

However, the tip is: Don’t forget the join condition! Every time you join two or more tables, you must write a join condition to link both tables. If you don’t specify this, you won’t get an error message; you’ll just get incorrect results. These will be wrong because every record from the first table will be joined with all records of the second table. This type of result set is called a Cartesian product of two tables, and usually is not an expected result.

Example 13: A Cartesian product – usually not the result you want

8. Include Non-Aggregated Columns from the SELECT List in GROUP BY Columns

When using aggregate functions, there are some restrictions on what columns can be included in the SELECT list (i.e. the column names after the SELECT clause). You can only include the columns specified in the GROUP BY clause, plus aggregate functions and constants. If you select only aggregate columns, any other column will generate an error. You can see this in the following example.

Example 14: Extra columns in the SELECT list

Example 15: No extra columns in the SELECT list

Sometimes we need to filter data by using an aggregation function. One of the most common mistakes is to put a condition using the aggregate function in the WHERE clause. This is shown below:

Example 16: Incorrect aggregate function in the WHERE

Remember, if you need to filter using an aggregate function, the correct way is to put the condition using the aggregate in the HAVING clause, as in the following example:

Example 17: The aggregate function is in the HAVING clause

Try It Yourself!

LearnSQL is a great place to get started with SQL. Several courses are geared for beginning learners. You can test the tips in this article on the exercises in this SQL course.

Источник

SQL Error: «Syntax error at or near:»

Last tested: Feb 2021

Overview

This SQL error generally means that somewhere in the query, there is invalid syntax.
Some common examples:

  • Using a database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD)
  • Typo in the SQL (missing comma, misspelled word, etc)
  • Missing a sql clause (missed from, join, select, etc)
  • An object does not exist in the database or is not accessible from the current query (eg referencing orders.id when there is no orders table joined in the current query, etc)

In some circumstances, the database error message may display extra detail about where the error was raised, which can be helpful in narrowing down where to look.

Error Message

SQL ERROR: syntax error at or near

Troubleshooting

This should generally be the first step to troubleshoot any SQL syntax error in a large query: iteratively comment out blocks of SQL to narrow down where the problem is.

TIP: To make this process easier, change the group by clause to use position references
eg: group by 1,2,3,4,5 instead of group by orders.status, orders.date, to_char(. ).
as well as separate the where and having clauses onto multiple lines.

So for example, say we have the following query:

We could start by running just the portion in the CTE:

Then strip out the aggregates and portions related to them

Iteratively stripping out / adding back in portions of the query until you find the minimum query to trigger the error.

Lookup functions and syntax If the query is small enough, or if we’ve narrowed the scope enough with 1, google all the functions used in the query and verify that they exist and are being used correctly.

Verify all objects exist Verify that you’ve joined all tables used in the select, where, and having clause, and that those tables exist in the db. Once we’ve narrowed things down from 1, also check that each column exists in the table specified.

Overview

This SQL error generally means that somewhere in the query, there is invalid syntax.
Some common examples:

  • Using au00a0database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD) t
  • Typo in theu00a0SQL (missing comma, misspelled word, etc) t
  • Missing a sql clause (missed from, join, select, etc) t
  • An object does not exist in the databaseu00a0or is not accessible from the current query (eg referencing orders.id when there is no orders table joined in the current query, etc)

In some circumstances, the database error message may display extra detail about where the error was raised, which can be helpful in narrowing down where to look.

Error Message

SQL ERROR: syntax error at or near

Troubleshooting

This should generally be the first step to troubleshoot any SQL syntax error in a large query:u00a0iteratively comment out blocks of SQL to narrow down where the problem is.

TIP: To make this process easier, change the group by clause to use position references
eg:u00a0 group by 1,2,3,4,5 instead of group by orders.status, orders.date, to_char(. ).
as well as separate the where and having clauses onto multiple lines.

So for example, say we have the following query:

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, sum(cte.sales_amount), count(*) from cte
join foo on cte.date = foo.date
group by status, foo.date
order by 3 desc

We could start by running just the portion in the CTE:

— WITH cte AS (
select id, status, sales_amountfrom orders
— )
— select status, foo.date, sum(cte.sales_amount), count(*)
— from cte
— join foo on cte.date = foo.date
— group by 1, 2
— order by 3 desc

Then strip out the aggregates and portions related to them

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, — sum(cte.sales_amount), count(*)
from cte
join foo on cte.date = foo.date
— group by 1, 2
— order by 3 desc

Iteratively stripping out / adding back in portions of the query until you find the minimum query to trigger the error.

    t

Lookup functions and syntax u00a0If the query is small enough, or if we’ve narrowed the scope enough with 1, google all the functions used in the query and verify that they exist and are being used correctly. t t
t

Verify all objects exist u00a0Verify that youu2019ve joined all tables used in the select, where, and having clause, and that those tables exist in the db. Once we’ve narrowed things down from 1, also check that each column exists in the table specified. t

Источник

SQL near «SELECT»: syntax error

You must login or register to post a reply

Posts: 6

1 Topic by vaattikarjalainen 2017-08-09 23:54:38 (edited by vaattikarjalainen 2017-08-09 23:55:22)

  • vaattikarjalainen
  • Member
  • Offline
  • Registered: 2017-05-03
  • Posts: 10

Topic: SQL near «SELECT»: syntax error

Доброго времени!
Объясните пожалуйста, что я делаю не правильно!?

+++.zip 336.42 kb, 419 downloads since 2017-08-10

2 Reply by DriveSoft 2017-08-10 15:25:41

  • DriveSoft
  • Administrator
  • Offline
  • Registered: 2014-02-14
  • Posts: 10,294

Re: SQL near «SELECT»: syntax error

Ошибка из за вычисляемого поля «Imya.Поле»
при использовании запросов в вычисляемом поле, его необходимо взять в скобки. Также запрос должен возвращать только один столбец и только одно значение, пример правильного выч. поля для вашего примера

3 Reply by vaattikarjalainen 2017-08-10 22:50:46 (edited by vaattikarjalainen 2017-08-10 22:51:03)

  • vaattikarjalainen
  • Member
  • Offline
  • Registered: 2017-05-03
  • Posts: 10

Re: SQL near «SELECT»: syntax error

Благодарю за очень полезное замечание!
Хочу заметить, что для отладки SQL запроса очень удобно использовать сторонний менеджер, например DB Browser for SQLite.
Как добавить SQL запрос в скрипт (на моем примере)? И что почитать, какой инструментарий лучше использовать?
Заранее, спасибо!

4 Reply by DriveSoft 2017-08-10 22:57:29

  • DriveSoft
  • Administrator
  • Offline
  • Registered: 2014-02-14
  • Posts: 10,294

Re: SQL near «SELECT»: syntax error

Как добавить SQL запрос в скрипт (на моем примере)? И что почитать, какой инструментарий лучше использовать?
Заранее, спасибо!

для использования SQL запросов в скрите предусмотрены функции SQLExecute и SQLQuery
Инструментарий для чего?

5 Reply by vaattikarjalainen 2017-08-11 06:47:02

  • vaattikarjalainen
  • Member
  • Offline
  • Registered: 2017-05-03
  • Posts: 10

Re: SQL near «SELECT»: syntax error

Как добавить SQL запрос в скрипт (на моем примере)? И что почитать, какой инструментарий лучше использовать?
Заранее, спасибо!

для использования SQL запросов в скрите предусмотрены функции SQLExecute и SQLQuery
Инструментарий для чего?

Имею ввиду паскаль!

6 Reply by DriveSoft 2017-08-11 10:24:41

  • DriveSoft
  • Administrator
  • Offline
  • Registered: 2014-02-14
  • Posts: 10,294

Re: SQL near «SELECT»: syntax error

какого либо отдельного инструментария для скриптов не предусмотрено.

Источник

Syntax errors are quite common while coding.

But, things go for a toss when it results in website errors.

PostgreSQL error 42601 also occurs due to syntax errors in the database queries.

At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.

Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.

What causes error 42601 in PostgreSQL?

PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.

Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.

But what causes error 42601?

PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.

Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.

In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.

How we fix the error?

Now let’s see how our PostgreSQL engineers resolve this error efficiently.

Recently, one of our customers contacted us with this error. He tried to execute the following code,

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;

But, this ended up in PostgreSQL error 42601. And he got the following error message,

ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)

Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,

RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;

This resolved the error 42601, and the code worked fine.

[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]

Conclusion

In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:
  • Pycharm ошибка 103
  • Syntax error all expressions in a derived table must have an explicit name
  • Pycharm как изменить папку проекта
  • Synology ошибка вентилятора
  • Pycharm как изменить дизайн