Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have two tables `Products` and `Keywords`, joined by common `ID`.
```
PRODUCTS KEYWORDS
Prod_id Prod_name Prod_id Keyword
-------------------- ------------------
1 Broccoli 1 kw1
2 Caulifower ... | First, you don't seem to need the `products` table, if you only want the `id`. Then, you can do what you want basically by adding a `group by` and `having` clause to your query:
```
SELECT k.Prod_id
FROM keywords k
WHERE k.keyword IN ('kw1' ,'kw2')
GROUP BY k.Prod_id
HAVING COUNT(DISTINCT k.keyword) = 2;
``` | Use this:
```
select * from Keywords
where Keyword = 'kw1' and Prod_id in(
select Prod_id from Keywords where Keyword = 'kw2'
)
``` | SQL Server : select rows with all specified values in another table | [
"",
"sql",
"sql-server",
""
] |
I'm not even sure how to word this question but here goes. I need to be able to loop through a result set, within the same SQL script, and use the results in more SQL.
For example
```
begin
SELECT (SELECT ColumnA, ColumnB from SomeTable) as x
loop through x(
INSERT ColumnA into TableA
INSERT ColumnB into Tab... | The usual way to handle obtaining the identity in a set based manner is through the [`OUTPUT`](https://msdn.microsoft.com/en-us/library/ms177564.aspx) clause:
```
INSERT INTO TableA (ColumnA, ColumnB)
OUTPUT inserted.Id, inserted.ColumnA, inserted.ColumnB
SELECT ColumnA, ColumnB
FROM MyTable;
```
The problem here... | In `SQL` it is called `CURSORS`. The basic structure of `CURSOR` is:
```
DECLARE @ColumnA INT, @ColumnB INT
DECLARE CurName CURSOR FAST_FORWARD READ_ONLY
FOR
SELECT ColumnA, ColumnB
FROM SomeTable
OPEN CurName
FETCH NEXT FROM CurName INTO @ColumnA, @ColumnB
WHILE @@FETCH_STATUS = 0
BEGIN
... | Looping through SELECT result set in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have written a plugin that fires off when new record is created (post). This plugin simple runs a SSIS package that moves newly created record details in to SQL table. I'm having to deploy this plugin as none isolation mode.
What I want to know is that is there any better solution to live sync CRM records with SQL t... | If you want to run this in sandbox mode you will not be able to directly target SQL (or run an SSIS package.)
The correct solution would be to target a web service.
Create a standard .NET web service (WebApi, ASP.NET old school, WCF, etc. - pick your poison) to which you can post the fields. That web service should t... | As a possible alternative I see that plugin can use ADO Connection/Command e.t.c. to push data directly to external DB. | How to copy newly created CRM contact record to SQL table | [
"",
"sql",
"plugins",
"dynamics-crm-2011",
"synchronization",
""
] |
I am trying to delete the last three charecters of the postcode, but the the issue is that the postcode could be eneter the field type is `varchar(max)` any idead how I can't delete the last there characters in the text value.
Currently when I try runing the code I get the follwoing error
> Invalid length parameter p... | This will exclude the last 3 characters:
```
SELECT
c.[postcode],
ltrim(substring( c.postcode , -2, len(c.postcode))) code
FROM [testing].[dbo].[canidateinfo] as c
```
Example:
```
DECLARE @t table(postcode varchar(20))
INSERT @t values('1234567'),('32'),('abcde'),(' aa123'),(' aa ')
SELECT
postcod... | Would something like this do the trick:
```
SELECT LEFT(PostCode, CHARINDEX(' ', Postcode)+1) PostCodeSector
FROM testing.dbo.canidateinfo
```
\*\* Update \*\*
```
CREATE TABLE #postcodeTest (postcode varchar(max))
insert into #postcodeTest
Values
('AB3 4FY'),
('AB34FY'),
('M504FY'),
('M50 4FY')
SELECT DISTINCT
... | Delete last three characters of test in SQL Server 2008 R2 | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
SQL is having an issue with the WHERE clause of this script:
```
SELECT
ITEM_ID, ITEM_PRICE, DISCOUNT_AMOUNT, QUANTITY,
(ITEM_PRICE*QUANTITY) AS price_total,
(DISCOUNT_AMOUNT*QUANTITY) AS discount_total,
((ITEM_PRICE-DISCOUNT_AMOUNT)*QUANTITY) AS item_total
FROM ORDER_ITEMS
WHERE item_total > 500
ORDER BY i... | > **An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING
> clauses to refer to the column.**
>
> **Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is
> evalua... | You cannot use the column name which is used as alias one in the query
Reason:
The query will first checks for runtime at that time the column name "item\_total" is not found in the table "ORDER\_ITEMS" because it was give as alias which is not stored in anywhere and you are assigning that column in desired output on... | SQL not recognizing column alias in where clause | [
"",
"sql",
"oracle",
"column-alias",
""
] |
I have an existing query to select some payments
I want to filter out any payments that are for clients that have an active alert in another table called ClientAlert
So I figured I would do a left join and check if the ClientAlertId is null.
```
select *
from payments p
left join client c on c.clienti... | 1. If they can have multiple alerts, theoretically. However since you are excluding payments with alerts, this should not be a problem. If you were including them it could be. If this was a problem, you should use a "not in" subquery instead of left outer join since that can cause duplicate records if it's not 1:1.
2. ... | 1. You could get multiples per payment record if it links to more than one Client record. Based on the WHERE clause though, I don't see how multiple ClientAlert records could cause duplication.
2. `LEFT JOIN` records return NULLs across all their columns when there is no match. Adding `ca.ClientAlertSubjectId = 1 and c... | sql left join criteria in join vs where clause | [
"",
"sql",
"sql-server",
""
] |
So I have these three tables:
```
WORKERS( WNO, WNAME, ZIP, HDATE )
CUSTOMERS( CNO, CNAME, STREET, ZIP, PHONE )
ORDERS( ONO, CNO, WNO, RECEIVED, SHIPPED )
```
I want to find the workers who have **ONLY** made sales to customers who lives in the same zip code as the workers. Until now I have this code:
```
SELECT e... | I think your original query will work with the addition of just a `NOT EXISTS` clause:
```
SELECT e.wno
FROM workers e, orders o, customers c
WHERE e.wno = o.wno
AND o.cno = c.cno
AND c.zip = e.zip
AND NOT EXISTS ( SELECT 1 FROM orders o1, customers c1
WHERE o1.wno = e.wno
... | Try this:
```
SELECT e.wno
FROM ORDERS o join CUSTOMERS c on o.cno = c.cno
join WORKERS e on o.wno = e.wno
Group by e.wno,c.zip
having count(*)=1
``` | Oracle SQL query about only extracting certain items | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I want to modify a column name to new name present in a table
but here problem i want to manually modify the `column name` present in `Triggers` or `SP's`.
Is there a any better way of doing it.
To `rename` a column am using this
```
sp_RENAME 'Tablename.old_Column', 'new_column' , 'COLUMN';
```
similarly how can ... | Well, there are a bunch of 3rd party tools that are promising this type of "safe rename", some for free and some are not:
* ApexSQL has a [free tool](http://solutioncenter.apexsql.com/rename-column-without-breaking-sql-database/) for that, as [MWillemse](https://stackoverflow.com/users/411860/mwillemse) wrote in his a... | 1. Renaming the Table column
2. Deleting the Table column
3. Alter Table Keys
Best way use Database Projects in Visual Studio.
Refer this links
[link 1](https://msdn.microsoft.com/library/xee70aty%28v=vs.100%29.aspx)
[link 2](https://www.mssqltips.com/sqlservertutorial/3001/creating-a-new-database-project/) | Renaming a column without breaking the scripts and stored procedures | [
"",
"sql",
"sql-server",
"triggers",
"rename",
""
] |
I have a `person` table where the `name` column contains names, some in the format "first last" and some in the format "first".
My query
```
SELECT name,
SUBSTRING(name FROM 1 FOR POSITION(' ' IN name) ) AS first_name
FROM person
```
creates a new row of first names, but it doesn't work for the names which only have... | Just use [**`split_part()`**](http://www.postgresql.org/docs/current/interactive/functions-string.html):
```
SELECT split_part(name, ' ', 1) AS first_name
, split_part(name, ' ', 2) AS last_name
FROM person;
```
[**SQL Fiddle.**](http://www.sqlfiddle.com/#!12/080a8/2)
Related:
* [Split comma separated column d... | 1.
```
select
substring(name from '^([\w\-]+)') first_name,
substring(name from '\s(\w+)$') last_name
from person
```
2.
```
select (regexp_split_to_array(name, ' '))[1] first_name
, (regexp_split_to_array(name, ' '))[2] last_name
from person
``` | Seperate first and last names from single column | [
"",
"sql",
"postgresql",
"substring",
"delimiter",
""
] |
I am trying to find the best way to compare between rows in the same table.
I wrote a self join query and was able to pull out the ones where the rates are different. Now I need to find out if the rates increased or decreased. If the rates increased, it's an issue. If it decreased, then there is no issue.
My data look... | You can achieve this with a select..case
```
select case when a.rate > b.rate then 'issue' else 'no issue' end
from yourTable a
join yourTable b using(id)
where a.date > b.date
```
See [documentation for CASE expressions](http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm). | Sounds like a case for `LAG()`:
```
with sample_data as (select 1010 id, to_date('02/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual union all
select 1010 id, to_date('03/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual union all
select 1010 id, to_date('04/02/2014', 'mm/dd/yyyy'... | Comparing between rows in same table in Oracle | [
"",
"sql",
"oracle",
"compare",
""
] |
I have some user-created stored procedures and functions in this legacy database. How do I list all procedures and functions of one specific schema, let's say, SCHEMA1, for instance. | Schema and user are somewhat synonymous in Oracle.
If you want to list down all the procedures and functions in a specific schema, then query:
1. **user\_objects** : If you are logged in as the user you want to query the object list.
2. **all\_objects** : You need to filter with **OWNER**.
For example,
```
SELECT *... | If you want to look up the list of all procedures then -
```
SELECT * FROM ALL_PROCEDURES WHERE OWNER = 'SCHEMA1';
```
This of course assumes that you have permissions to see the procedures/functions/packages of SCHEMA1.
If however you have the DBA privilege, then you can also do -
```
SELECT * from DBA_PROCEDURES ... | How to get a list of all user-created stored procedures and functions in a specific schema of Oracle 9i? | [
"",
"sql",
"database",
"oracle",
""
] |
I have a database that stores search criteria entered by users and want to analyse how often certain words have been used. The "problem" is that many searches have similar meaning but have one or more words that accompany them. Example (in this example "foo" is the interesting word):
```
bar
foo 2015
show me foo
germa... | Expanding on this [This Answer](https://stackoverflow.com/questions/11018076/splitting-delimited-values-in-a-sql-column-into-multiple-rows) (Credit to Aaron Bertrand for Function), you can do this by creating a Split Function and using a `Cross Apply` to it with a `Group By`:
```
CREATE FUNCTION dbo.SplitStrings
(
... | I think this is an idea problem to use the full text search feature of sql server. Solving this problem is what that full text search does.
<https://msdn.microsoft.com/en-us/library/ms142571.aspx>
To quote from that page:
> Full-Text Search Queries
>
> After columns have been added to a full-text index, users and
> ... | Full text search for MS SQL | [
"",
"sql",
"sql-server",
"full-text-search",
""
] |
I need some help with my query.
I need to select data that is not selected in another query.
So what is mean is:
Table 1 have 50 Questions
Table 2 have selected 32
Then there are 18 not used.
I only need to select that 18 not used questions.
Hope you can help me!
Edit:
Table with all Questions:
Id - Inp... | You can use `LEFT JOIN`:
```
SELECT T1.*
FROM Table1 T1 LEFT JOIN
Table2 T2 ON T1.Id=T2.Id
WHERE T2.required IS NULL
```
**Explanation:**
When we join those tables with `LEFT JOIN`, it will select all records from Table1 and corresponding records from Table2 (if any). And we are excluding the questions which ar... | ```
SELECT
aq.*
FROM
all_questions aq
LEFT JOIN selected_questions sq ON sq.Id = aq.Id
WHERE sq.Id IS NULL
``` | Mysql Get rows that are not used yet | [
"",
"mysql",
"sql",
""
] |
I have a long table like the following. The table adds two similar rows after the id changes. E.g in the following table when ID changes from 1 to 2 a duplicate record is added. All I need is a SELECT query to skip this and all other duplicate records only if the ID changes.
```
# | name| id
--+-----+---
1 | abc | 1
... | So I achieved it by using the following query in SQL server.
```
select #, name, id
from table
group by #, name, id
having count(*) > 0
``` | You could use `NOT EXISTS` to eliminate the duplicates:
```
SELECT *
FROM yourtable AS T
WHERE NOT EXISTS
( SELECT 1
FROM yourtable AS T2
WHERE T.[#] = T2.[#]
AND T2.ID > T.ID
);
```
This will return:
```
# name ID
------------------
. ... | Query to skip first row after id changes in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
According the instructions [here](https://stackoverflow.com/a/7945958/1500111) I have created two functions that use `EXECUTE FORMAT` and return the same table of `(int,smallint)`.
Sample definitions:
```
CREATE OR REPLACE FUNCTION function1(IN _tbl regclass, IN _tbl2 regclass,
IN field1 integer)
RETURNS TABLE(id i... | > Is there a way to get only the 2nd field of each function result, to batch compare them?
All of the following answers assume that rows are returned in ***matching*** order.
## Postgres 9.3
With the quirky feature of exploding rows from SRF functions returning the *same* number of rows in parallel:
```
SELECT coun... | The order in which the rows are returned from the functions is not guaranteed. If you can return the [`row_number()`](http://www.postgresql.org/docs/current/static/functions-window.html) (`rn` in the below example) from the functions then:
```
select
count(f1.dist is null or f2.dist is null or null) as diff_count
... | Compare result of two table functions using one column from each | [
"",
"sql",
"postgresql",
"postgresql-9.3",
"set-returning-functions",
""
] |
Given a table with two columns col1 and col2, how can I use the Oracle CHECK constraint to ensure that what is allowed in col2 depends on the corresponding col1 value.
Specifically,
* if col1 has A, then corresponding col2 value must be less than 50;
* if col1 has B, then corresponding col2 value must be less than 10... | You need to use a case statement, eg. something like:
```
create table test1 (col1 varchar2(2),
col2 number);
alter table test1 add constraint test1_chk check (col2 < case when col1 = 'A' then 50
when col1 = 'B' then 100
... | add `check constraint` using `case` statement
```
CREATE TABLE tbl
(
col1 varchar(10),
col2 numeric(4),
CONSTRAINT check_cols_ctsr
CHECK (CASE WHEN col1='A' THEN col2 ELSE 1 END <50 AND
CASE WHEN col1='B' THEN col2 ELSE 1 END <100 AND
CASE WHEN col1='C' THEN col2 ELSE 1 END <150)
);
``` | Add multiple CHECK constraints on one column depending on the values of another column | [
"",
"sql",
"oracle",
"constraints",
""
] |
```
String sql="select * from offerpoolride
WHERE date >= '1997-05-05'";
```
I am a beginner and Can anyone please help me how to retrieve those? | ```
use backtick for date
SELECT * FROM `offerpoolride` WHERE `date` >= '1997-05-05';
``` | I'm not 100% sure about ANSI-SQL, but in T-SQL you would use the following:
```
SELECT * FROM TABLE WHERE [date] >= '19970505'
```
So the date is input in format 'yyyyMMdd'. I am assuming your field is called date... | I can't retrieve the Date greater than or equal to a specific date in Sql. | [
"",
"mysql",
"sql",
""
] |
I am working with two tables(`student_class` and `class`) in my database. I have a query below that shows `class` that have `students`. But it is not quite what I am looking for. How to display classes that have students but show the results so maximum seats is descending. Would count be needed?
```
SELECT
class.... | Just use an order by statement:
```
SELECT class.class_name FROM class INNER JOIN student_class ON class.class_id = student_class.class_id
ORDER BY class.max_seats_available DESC
``` | You would not need a count. Just do an `ORDER BY MAX_SEATS_AVAILABLE DESC`.
```
SELECT class.class_name, class.max_seats_available FROM class INNER JOIN
student_class ON class.class_id = student_class.class_id ORDER BY
class.MAX_SEATS_AVAILABLE DESC;
```
this might be helped. | Using Inner join and sorting records in descending order | [
"",
"sql",
""
] |
So the below query on an oracle server takes around an hour to execute.
Is it a way to make it faster?
```
SELECT *
FROM ACCOUNT_CYCLE_ACTIVITY aca1
WHERE aca1.ACTIVITY_TYPE_CODE='021'
AND aca1.ACTIVITY_GROUP_CODE='R12'
AND aca1.CYCLE_ACTIVITY_COUNT='999'
AND
EXISTS
(
SELECT 'a'
FROM ... | Rewrite the query using explicit joins, and not with EXISTS.
Basically these two lines
```
WHERE aca1.account_id = aca2.account_id
AND (aca2.cycle_ctr > aca1.cycle_ctr)
```
are the join condition for joining the first and second select, and this one joins the first and the third.
```
WHERE aca3.account_id = aca1... | I would probably start with use of the WITH statement to hopefully reduce the number of times that the data is selected, and make it more readable. The other thing i would recommend is replacing the exists by some sort of join.
```
with base as
(
select *
from account_cycle_activity
where activity_type_co... | make this sql query faster or use pl sql? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have the following sql that will display test score values:
```
SELECT s.dcid, s.lastfirst, s.student_number, s.grade_level, s.schoolid,
(SELECT stc.numscore
FROM studenttestscore stc
JOIN testscore ts ON stc.testscoreid = ts.id
JOIN test t on ts.testid = t.id
JOIN studenttest st ON stc.studenttestid =... | You simply nest your Select in a Derived Table (aka Inline View) and then you can use the aliased columns in WHERE:
```
SELECT *
FROM
(
SELECT s.dcid, s.lastfirst, s.student_number, s.grade_level, s.schoolid,
(SELECT stc.numscore
FROM studenttestscore stc
JOIN testscore ts ON stc.testscoreid =... | Using Common Table Expressions, you can reference fields from the CTE select statements in the where clause of the main query. They also clean up the structure a little and the reuse limits the number of times you need to copy+paste common predicates (e.g. - AND st.termid LIKE '24%')
```
WITH TermTestData AS (
SEL... | Referring back to selected value in WHERE clause | [
"",
"sql",
"oracle",
""
] |
This return single-row query subquery returns more than one row
```
select E.NO_ENCAN, E.NOM_ENC, TE.DESC_TYPE_ENC as TYPE_ENC,
(select sum(ITEM.MNT_VALEUR_ITE) from ENCAN left join ITEM on ITEM.NO_ENCAN = ENCAN.NO_ENCAN group by ENCAN.NO_ENCAN) as SOMME_ITEMS,
count(distinct INV.NOM_UTILISATEUR_INVITE)... | You want a correlated subquery rather than a `group by` in the subselect. This also means that the subquery is not needed. So, this is probably what you are trying to write:
```
select E.NO_ENCAN, E.NOM_ENC, TE.DESC_TYPE_ENC as TYPE_ENC,
(select sum(ITEM.MNT_VALEUR_ITE)
from ITEM
where ITEM.NO_E... | If I am correctly understanding what you are trying to accomplish, I believe the subquery is unnecessary. You should just put an analytic on the SUM() call.
```
SELECT e.no_encan
,e.nom_enc
,te.desc_type_enc AS type_enc
,SUM(item.mnt_valeur_ite) OVER (PARTITION BY e.no_encan) somme_items
,COUNT... | SQL oracle error on select inside select | [
"",
"sql",
"oracle",
"subquery",
""
] |
Input:
```
ID CREATED_TIME CANCELED_TIME
1 4 10
1 8 2
1 6 -1
1 3 7
2 5 null
2 4 8
```
Desired output:
```
ID CREATED_TIME CANCELED_TIME
1 3 2
2 4 null
```
so I ... | If you want `canceled_time` where `created_time` has the maximum value, I would suggest the `substring_index()`/`group_concat()` trick:
```
select id, min(created_time),
substring_index(group_concat(canceled_time order by created_time desc), ',', 1) as canceled_time
from table
group by id;
```
This will not wo... | Use a sub-query to find each id's max created\_time:
```
SELECT
ID,
created_time,
MIN(CANCELED_TIME) AS MinTimeCanceled
FROM
tableName t1
WHERE created_time = (select max(created_time) from tableName t2
where t1.ID = t2.ID)
GROUP BY
ID, created_time
``` | how to display min of a column and use max of the same column to filter other attributes in mysql? | [
"",
"mysql",
"sql",
"postgresql",
"group-by",
""
] |
At work we have three SQL Server 2008 R2 database environments: production, test and development.
In the production environment, different parts of our system run on 3 different database servers (let's call them `PROD1`, `PROD2` and `PROD3`), while in the development environment we have all the databases running on th... | As already mentioned, you do need to use the dynamic SQL. But you can use it for the object creation: simply to create the synonym in the dynamic SQL for all objects which need to be accessed from the another server and / or another database.
In this case all your code will be static and only during the installation /... | For cross database references your best bet might be using [synonyms](https://msdn.microsoft.com/en-us/library/ms187552.aspx). The definition of the synonyms will be different between DEV and PROD, but the definition of the complex objects (views, SPs etc) that use the synonyms can remain unchanged. | Is it possible to conditionally specify the database in a fully qualified table name in T-SQL? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
""
] |
I have 3 tables and my query is :
```
SELECT BRAND, AMOUNT FROM
(
SELECT BRAND, AMOUNT FROM SALES1
UNION
SELECT BRAND, AMOUNT FROM SALES2
UNION
SELECT BRAND, AMOUNT FROM SALES3
)
```
`SALES 1` TABLE HAS BRAND: *A* AND AMOUNT: *50*
`SALES 3` TABLE HAS BRAND: *A* AND AMOUNT: *100*
I want to get the amount 50 and dis... | If you want the first occurrence, you should use `union all` rather than `union`. This is important for performance reasons, because `union` does unnecessary duplicate elimination.
Then use the `not exists` clauses for each subquery:
```
(SELECT BRAND, AMOUNT
FROM SALES1
) UNION ALL
(SELECT BRAND, AMOUNT
FROM SALE... | ```
SELECT BRAND, AMOUNT
FROM
( SELECT BRAND, AMOUNT, 1 AS priority
FROM SALES1
UNION ALL
SELECT BRAND, AMOUNT, 2 AS priority
FROM SALES2
UNION ALL
SELECT BRAND, AMOUNT, 3 AS priority
FROM SALES3
)
ORDER BY pr... | Mysql union Priority | [
"",
"mysql",
"sql",
""
] |
I have a `varchar` column which has a variation of the following string:
`Stations, FlightName, FlightWeeks, BindTo, SpotLength, foo, bar, etc...`
I need to change it to `Stations` to `Station`, `FlightName` to `Flight Name`, `BindTo` to `Bind To` etc to eventually come out like this:
`Station; Flight Name; Weeks; B... | Creating CLR function is a solution for calling multiple REPLACE functions by replacing a single function. Yes there are some performance considerations using CLR functions but if you are dealing with low number of data, then it would be fine.
For creating CLR functions,
* [Enabling CLR](https://msdn.microsoft.com/en... | You could write your own Transformation-Function in TSQL but i think it will not be as performant as a multi-replace.
You should avoid using your multi-replace in WHERE/ORDER-clauses | Is there a better way to do multiple replace on a string? | [
"",
"sql",
"sql-server",
""
] |
I've tried to use this, but it throws syntax error.
```
SET @deletedRepliesCount = (DELETE FROM reply WHERE type = 3 AND id IN (SELECT id FROM `like`
WHERE commentId = :commentId)) + @deletedRepliesCount;
```
> "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the... | Try this:
```
DELETE FROM reply WHERE type = 3 AND id IN (SELECT id FROM `like`
WHERE commentId = :commentId));
SET @deletedRepliesCount = SELECT ROW_COUNT() + @deletedRepliesCount
``` | Try below as per [link](https://stackoverflow.com/questions/10070406/how-to-store-query-result-in-variable-using-mysql)
```
SET @deletedRepliesCount := (DELETE FROM reply WHERE type = 3 AND id IN (SELECT id FROM like WHERE commentId = :commentId)) + @deletedRepliesCount;
``` | How to save delete result to variable in mysql? | [
"",
"mysql",
"sql",
""
] |
I have an annoying problem which is stopping me from generating some data; The SQL job has 23 steps in total and fails on the 21st.
```
-- Step 21 Create the table z1QReportOverview
-- Create z1QReportProjectOverview.sql
-- Project Overview - By Category (Part 4).sql
USE database
SELECT z1QReportProjectOverview1.[ERA ... | You can use `CASE` as to check if the dividing value is `0` or not.
```
CASE WHEN CONVERT(decimal(18,0),[Lost]) <> 0 THEN
CONVERT(decimal(18,0),[Lost])/CONVERT(decimal(18,0),[Total Projects Signed])
ELSE 0 END AS [Loss Ratio],
z1QReportProjectOverview2.[Completed],
CASE WHEN CONVERT(decimal(18,0),([Comp... | Use `NULLIF` to handle divide by zero error
```
........
Isnull(CONVERT(DECIMAL(18, 0), [Lost]) / NULLIF(CONVERT(DECIMAL(18, 0), [Total Projects Signed]), 0), 0) AS [Loss Ratio],
Isnull(CONVERT(DECIMAL(18, 0), ( [Completed] + [Implemented] )) /
NULLIF(CONVERT(DECIMAL(18, 0), ( [Completed] + [Im... | SQL Divide by Zero Error | [
"",
"sql",
"sql-server",
"divide",
""
] |
So I have these three tables
```
Persons {id, name}
{1, "Jim"}
{2, "Kim"}
{3, "Tim"}
{4, "Brim"}
Knows {id_A, id_B}
{1,2}
{1,3}
{1,4}
{2,3}
{4,2}
Hates {id_A, id_B}
{1,4}
{2,1}
{3,1}
{3,2}
{4,2}
```
And I want to get data using NOT EXIST to get names of all Pers... | Written another way, give me all people that knows someone they do not hate:
```
SELECT * FROM Persons p
WHERE EXISTS
(
SELECT 0 FROM Knows k
WHERE k.personA_id = P.id
AND NOT EXISTS
(
SELECT 0 FROM Hates h
WHERE k.personA_id = h.personA_id
)
)
``` | you are not using the other tables in sub-query. You should do somthing like this:-
```
SELECT DISTINCT P.name FROM Persons P, Hates H, Knows K
WHERE K.A_id = P.id AND H.A_id = P.id
AND NOT EXISTS
(SELECT * FROM Persons P, Hates H, Knows K WHERE H.A_id = P.id and H.B_id <> K.B_id)
``` | SQL NOT EXISTS (Person hates everybody they know) EDITED | [
"",
"sql",
""
] |
So I have these three tables:
```
Persons {id, name}
Knows {A_id, B_id} - (Person A knows Person B)
Smoking {id} - (id -> Persons{id})
Persons:
{1, "Tim"}
{2, "Kim"}
{3, "Jim"}
{4, "Rim"}
Knows:
{1, 2}
{1, 3}
{3, 2}
{3, 4}
Smoking:
{3}
```
And I need {3, "Jim"} to be returned since he doesn't know anyone who smok... | ```
SELECT p.name
FROM Persons p
WHERE NOT EXISTS ( -- there does not exist
SELECT * FROM Knows k -- a person I know
JOIN smokes s ON s.id = k.b_id -- who smokes
WHERE k.A_id = p.id
);
``` | Allow me to explain how to think about your problem in set theory / SQL terms:
1. You need an aggregated sum of the total number of people that any given person knows who smokes.
2. Then filter for people where that aggregated value is zero.
That leads to:
```
select P.Name
from Persons P inner join Knows K on K.A... | SQL NOT IN (Do not know anyone who smokes) | [
"",
"sql",
""
] |
I'm wondering whats wrong with that Statement.
```
INSERT INTO Table1(Myname,category )
SELECT TOP 1 thenames
FROM tNames
WHERE DateAdded > DATEADD(Day, -10, GETDATE()
ORDER BY NEWID(),@ccategory)
```
I want to pick one random value from table tnames and put it in table 1 with category values that i got from SP.
... | You have 2 Columns you want to insert in (Myname, category)
but your select list only contains 1 column! (thenames)
What about "@category"? At least in your posted code this variable is never declared or assigned...
Maybe you should do something like this:
```
DECLARE @category varchar(20)
SET @category = 'some cat... | You are selecting One Column from Select statement and There are Two Columns specified in insert statement
```
INSERT INTO Table1(Myname)
SELECT TOP 1 thenames
FROM tNames
WHERE DateAdded > DATEADD(Day, -10, GETDATE()
ORDER BY NEWID(),@ccategory)
``` | SQL Select In Select for insert Stement | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
How can I find duplicate data because of bad data entry?
I want to find Customers that have the same PhoneNumber.
I need to list both customers FirstName and LastName
Any thoughts?
Thanks
**Edit**
When I run this query:
```
Select FirstName, LastName, PhoneNumber
From Customer
```
I get this result:
```
Person O... | You need to join CUstomers table to itself via Phone Number field like this:
```
SELECT
c1.Name as Name1,
c1.Surname as Surname1,
c2.Name as Name2,
c2.Surname as Surname2,
c.Phone
FROM
Customers c1 INNER JOIN
Customers c2 ON c1.Phone = c2.Phone AND c1.id < c2.id
```
Note: Unlike other answers this wi... | This query would give you the duplicata
```
select firstname, lastname
from customers
group by phonenumber, firstname, lastname
having count(phonenumber) > 1
```
* Group all results by phonenumber.
* Display only those who appear more then one time (duplicate). | Find bad/duplicate data in same table | [
"",
"sql",
""
] |
I have the following code that returns an error message if my value is invalid. I would like to give the same error message if the value given is not numeric.
```
IF(option_id = 0021) THEN
IF((value<10000) or (value>7200000) or /* Numeric Check */)THEN
ip_msg(6214,option_name); -- Error Message
... | ```
REGEXP_LIKE(column, '^[[:digit:]]+$')
```
returns TRUE if column holds only numeric characters | From `Oracle DB 12c Release 2` you could use **[VALIDATE\_CONVERSION](http://docs.oracle.com/database/122/SQLRF/VALIDATE_CONVERSION.htm#SQLRF-GUID-DC485EEB-CB6D-42EF-97AA-4487884CB2CD)** function:
> VALIDATE\_CONVERSION determines whether expr can be converted to the specified data type. If expr can be successfully co... | How can you tell if a value is not numeric in Oracle? | [
"",
"sql",
"oracle",
"plsql",
"isnumeric",
""
] |
Assume I have a table called `Person` with columns `name, surname and age.`
I want to add two columns when performing a SELECT statment, probably something like this:
```
SELECT a FROM Person a WHERE a.name + a.surname LIKE ...
```
How can I do this correctly? | You do not add string values, like names. Presumably, you want to concatenate them, so you use the `concat()` function:
```
where concat(a.name, a.surname) like . . .
``` | ```
SELECT a FROM Person a WHERE CONCAT(a.name, a.surname) LIKE ...
``` | How to perform a SELECT by adding two columns? | [
"",
"mysql",
"sql",
""
] |
I have the following plsql block
```
for holder in (
select pm.product_holder
, cast(
collect(
product_table(pm.product_no,pm.product_catalogue)
order by pm.product_catalogue
, pm.product_no
) as t_prod_cat_... | You should be able to do this like that:
```
loop
if holder.product_holder is null or
holder.product_cats_nos is null
then
exit;
end if;
test_proc(
holder.product_holder,
holder.product_cats_nos
);
end loop;
```
Exit will break the loop.
For more information look up the docs: ... | product\_cats\_nos can't be null (it can contain nulls or be empty, but that's a different concept: the collection is not null by the time it is initialized as the first step of collect aggregation function) and you can only have the last **one**(you're grouping by that field) occurrence of pm.product\_holder (because ... | Conditional execution of loop | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a table in which I inserted a large batch of records. All these records have a certain column in which one character is missing: they're missing a slash `/` at the beginning. Is there a way to add this character to the beginning of this column in every row, using purely SQL?
It wouldn't be a problem in PHP, but... | Simply use this:
```
UPDATE the_table t
SET the_column =
CONCAT('/', the_column )
``` | Your version might work. But you really just want to do:
```
UPDATE the_table t
SET the_column = CONCAT('/', the_column)
``` | Adding a character to every row in a MySQL database | [
"",
"mysql",
"sql",
"database",
""
] |
how can I simplify this query? unfortunately this is not working
```
$Query = mysqli_query($conn, "SELECT * FROM order_number where trans_id NOT IN (SELECT order_no from billing)
AND NOT IN(SELECT order_no from pending)
AND NOT IN(SELECT ord... | ```
SELECT * FROM order_number
where trans_id NOT IN
(
SELECT order_no from billing
union
SELECT order_no from pending
union
SELECT order_no from on_process
union
SELECT order_no from finished
)
```
or as you tried it
```
SELECT * FROM order_number
where trans_id NOT IN (SELECT order_no from... | There is no reason to "simplify" the query. With proper indexes on the tables in the four subqueries, it should be quite efficient. If `orderno` could be `NULL` in any of the tables, then I would recommend using `not exists` instead:
```
SELECT *
FROM order_number o
WHERE NOT EXISTS (select order_no from billing wher... | Simplified way to use NOT IN statements for multiple tables | [
"",
"mysql",
"sql",
"database",
""
] |
Just opened the Oracle SQL Developer and i'm getting this error:
> Failed to create naming Context for db connections at url: file:/C:/Users/.../AppData/Roaming/SQL Developer/system3.2.20.09.87/o.jdeveloper.db.connection.11.1.1.4.37.59.48/connections.xml
>
> SEVERE 95 69513 oracle.jdevimpl.db.adapter.DefaultContextWra... | I ran into the same problem. Here is what worked for me.
connections.xml file just contained repetitive string NULL
I simply deleted this file and created a new connection which went through fine. | * STEP 1: Deleting the file `connections.xml` under the path: `C:\Users\tejgm\AppData\Roaming\SQL Developer\system2.1.1.64.45\o.jdeveloper.db.connection.11.1.1.2.36.55.30`.
* STEP 2: Start up the SQL newly. | DatabaseConnections has no JNDI context so cannot list connections | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I need to update records that will match a specific query, so I'm currently trying to figure out how to find a list of duplicate values where one column differs in value.
I have the following table definition
```
DocumentId (BIGINT)
NotePopupId (INT)
IsPopup (BIT)
Note (NVARCHAR(100))
```
My table might have data as... | I am inclined to handle a question like this using `group by` and aggregation:
```
select documentId
from table
group by documentId
having min(cast(isPopup as int)) = 0 and max(cast(isPopup as int)) = 1;
``` | Find `Distinct Count` and filter the group's whose count is more than 1. Try this.
```
select DocumentId
from yourtable
group by DocumentId
having count(Distinct IsPopup)>1
```
If you want to return documentId when there is only one IsPopup then use this
```
select DocumentId
from yourtable
group by DocumentId ... | Find duplicates where another column have different columns | [
"",
"sql",
"sql-server",
""
] |
I have the following slash-delimited example strings and need to split them:
```
Record---String
1--------ABC
2--------DEF/123
3--------GHI/456/XYZ
```
The strings will always have 1 - 3 parts; no more, no less.
To split them I have been using this function:
```
CREATE FUNCTION [dbo].[Split] (
@chunk VARCHAR(4000)
... | The following fixes your "SPLIT" function. Add the following line just before the WHILE.
```
SET @chunk = @chunk + '/'
``` | I would move the charindex to before the while:
```
alter FUNCTION [dbo].[Split] (
@chunk VARCHAR(4000)
,@delimiter CHAR(1)
,@index INT
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @curIndex INT = 0
,@pos INT = 1
,@prevPos INT = 0
,@result VARCHAR(1000)
SET @pos = CHARINDEX(@delimiter, @chunk, @prevPos);
if @... | Split delimited string in SQL Server | [
"",
"sql",
"sql-server",
"string",
"t-sql",
"sql-server-2012",
""
] |
Bellow is an example table.
```
ID FROM TO DATE
1 Number1 Number2 somedate
2 Number2 Number1 somedate
3 Number2 Number1 somedate
4 Number3 Number1 somedate
5 Number3 Number2 somedate
```
Expected result is to get 1 row for each unique pair of TO and FROM ... | SQL fiddle isn't working for some reason so in the mean time you will need to help me to help you.
Assuming that the following statement works
```
SELECT
LEAST(to,from) as LowVal,
GREATEST(to,from) as HighVal,
MAX(date) as MaxDate
FROM table
GROUP BY LEAST(to,from), GREATEST(to,from)
```
then you cou... | This answer was originally inspired by [Get records with max value for each group of grouped SQL results](https://stackoverflow.com/questions/12102200/get-records-with-max-value-for-each-group-of-grouped-sql-results)
but then I looked further and came up with the correct solution.
```
CREATE TABLE T
(`id` int, `fr... | SQL How to group by two columns | [
"",
"mysql",
"sql",
""
] |
I'm trying to add a new column to an existing table which will be populated by a unique Guid value. I'm trying the following code:
```
IF NOT EXISTS(select * from sys.columns
where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
PRINT 'Creating new GUID column in dbo.Product table'... | The statement doing the update must be compiled after the column is added.
The way this is usually done is wrapping the statements in an `EXEC`:
```
EXEC(' UPDATE dbo.Product
SET Product_Guid = NEWID()
ALTER TABLE dbo.Product
ALTER COLUMN Product_Guid uniqueidentifier NOT NULL
')
``` | It seems like you want to set the default value and have the column be not null. You'll get the same effect if you just set the default value to NEWID()
```
IF NOT EXISTS(select * from sys.columns
where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
PRINT 'Creating new GUID column... | SQL: multiple statements within a BEGIN and END | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to create a table using SQL view. It suppose to add a column to each row in questions table that will have an integer value of answers given to that question. This is what I have so far:
```
CREATE VIEW [dbo].[Question]
AS
SELECT
COUNT(answer.Id) as 'Answers',
question.Id,
question... | My favorite, correlated sub-query to get count:
```
CREATE VIEW [dbo].[Question]
AS
SELECT (select COUNT(*) from Answers
where QuestionId = question.Id) as 'Answers',
question.Id,
question.CreatorId,
question.Title,
question.Content,
question.CreationDate
FROM Questions AS qu... | This not creating a table,you are joining
```
var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";
```
using (SqlCommand command = new SqlCommand(commandS... | Add rows count in SQL view | [
"",
"sql",
"database",
"view",
""
] |
Given these simplified multiple choice tables where sometimes more than one answer is correct:
```
STUDENT_ANSWERS
AnswerID | StudentID | QuestionID | Answers
-------------------------------------------
1 | 1 | 1 | C,D
QUESTION_ANSWERS
QuestionID | Answer | Text
-------------------------------... | Your problem is the structure of table `STUDENT_ANSWERS`. It should have one row per answer:
```
AnswerID | StudentID | QuestionID | Answer
-------------------------------------------
1 | 1 | 1 | C
2 | 1 | 1 | D
```
---
Now, assuming you can't do anything to change (re... | This is full working example using only `T-SQL` statements. I will recommend to you to create separate function for splitting `CSV` that returns row set. Also, if you are working with huge amount of data, you may want to create a `CLR` function for splitting the values. Take a look to [this article](https://msdn.micros... | Join multiple values from one column, selected from another table | [
"",
"sql",
"sql-server",
"t-sql",
"csv",
"join",
""
] |
I have a simple employee table

and here is the data

When I try to run a query with string parameter it doesn't return anything although it has correct parameter
, '|' + empid + '|'
from employee
```
This will provide information about unexpected characters that you might not see. The length ... | You could have a special char, like a carriage return, at the end of the value.
Use the query below to check if there are some of those cases in your table.
```
SELECT
EmpId,
-- convert(int, EmpId) AS EmpId_INT,
LEN(EmpId) AS Len_EmpId
FROM
Employee
-- WHERE
-- LEN(EmpId) <... | Unable to return correct query when using string parameter in SQL Server | [
"",
"sql",
"sql-server-2012",
""
] |
I am newbie to database
I want to delete top 10 records form table without any condition on column. | Just execute this one-line command :
```
DELETE FROM table LIMIT 10
``` | Use below query to `delete` Top ten records from `Mysql`,
```
DELETE FROM table_name limit 10;
```
It deletes top 10 records from table. You can Also modify number to change number of records. | Delete Top 10 record from table | [
"",
"mysql",
"sql",
"database",
""
] |
I have the following stored procedure that selects comments from a SQL Server database for a selected photo. I'm using the `OFFSET` and `FETCH` in order to select a numer of posts (10) on load and then to have a button that will prepend more posts to a DIV using AJAX.
```
CREATE PROCEDURE [dbo].[SD_PhotoCmt]
@IDph... | Do OFFSET/FETCH first, then order the RESULT, something like:
```
select * from
(SELECT
photoCmt.IDphotoCmt,
photoCmt.photoCmt,
photoCmt.IDuser,
photoCmt.photoCmtDate, //the date and time when the comment was added
photoCmt.IDphoto,
FROM photoCmt
WHERE photoCmt.IDphoto = @IDphoto
ORDER BY photoCmt.photoCmtD... | Try this,
Essentially, use the descending order to get the page into a sub-query, then reorder the page in the outer query.
I would caveat my advice, using a different display order to page order could be very confusing to the user.
[**Fiddle Here**](http://sqlfiddle.com/#!6/b1ed3/2)
```
CREATE PROCEDURE [dbo].[SD_... | Getting the right order using ORDER with OFFSET and FETCH in a stored procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
**Scenario:** I need to convert an existing query using (+) outer join syntax to ANSI syntax.
**Reason**: One of the JOINS requires an OR operand, which is not allowed with the (+) operator, but is allowed with LEFT OUTER JOIN. (At least I'm assuming this is correct.)
**Goal of the Query:** Table D contains that name ... | You have two date literals as outer join conditions in your first query, but you leave them in the `where` clause in the second query. To change the syntax properly, those criteria need to be left as part of the join criteria. It's also bad form to combine the two join syntax (i.e. having comma seperated tables and the... | (Posting my comment as answer in case this was what you wanted)
OR is same as a UNION. In oracle syntax, you can do
```
SELECT * FROM TABLE1, TABLE2 WHERE B1=C1(+)
union
SELECT * FROM TABLE1, TABLE2 WHERE B2=C2(+)
```
This is the same as -
```
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON (B1=C1 OR B2=C2)
```
(Maybe ... | Oracle LEFT OUTER JOIN on 3+ tables - (+) Syntax versus ANSI Syntax | [
"",
"sql",
"oracle",
""
] |
The Queries are working perfectly each one separatedly:
```
SELECT asf.surface_name, am.*
FROM atp_matchs_to_surfaces m2s
LEFT JOIN atp_surfaces asf ON m2s.surfaces_id = asf.surfaces_id
LEFT JOIN atp_matchs am ON am.matchs_id = m2s.matchs_id;
SELECT att.tournament_type_name, am.*
FROM atp_matchs_to_tournament_type m2... | OK, this is your current schema. As you can see, one match can be played on multiple surfaces and one match can be played within multiple tournament types.

If this schema is OK, you can get your result with this query:
```
SELECT am.*, asu.surface_name, att... | ```
SELECT asf.surface_name, am.*
FROM atp_matchs_to_surfaces m2s
LEFT JOIN atp_surfaces asf ON m2s.surfaces_id = asf.surfaces_id
LEFT JOIN atp_matchs am ON am.matchs_id = m2s.matchs_id
LEFT JOIN(
SELECT att.tournament_type, am.*
FROM atp_matchs_to_tournament_type m2s
LEFT JOIN atp_tournament_type att AS Q1 ON m2s.surf... | How to joint Two customs Queries with two Joins in only One Query in MySQL | [
"",
"mysql",
"sql",
"select",
"subquery",
"left-join",
""
] |
Good Morning,
I am on a SQL learning tour and trying to create a small database with a few queries to gain experience.
Two databases where used, Person {id, name, age} and Knows {id, guest1\_id → Persons, guest2\_id → Persons}
The query should result in a list of names of people that do not know anyone from the datab... | Try this :
```
SELECT P.*
FROM Persons P
LEFT JOIN Knows K ON K.guest1_id = P.id
WHERE K.id IS NULL
```
This will give you `Persons` that know nobody.
You can also try this :
```
SELECT *
FROM Persons
WHERE NOT EXISTS(SELECT 1 FROM Knows WHERE guest1_id = P.id)
``` | Your question doesn't really make sense, nor does the look of the query. But, If you are looking for all people who don't know anyone, then that in summary means the person is in neither the guest1 or guest2 ID column within the Knows table.
If that is the case, you can do a double-left-join to the knows table and jus... | LEFT OUTER JOIN does not work | [
"",
"sql",
"left-join",
"notin",
""
] |
Problem statement:
> given a range `x -> y` of unsigned integers
> where `x` and `y` are both in the range `0 -> 2``n`
> and `n` is `0 -> 32` (or 64 in alternate cases)
> find the minimum available value
> not equal to `x` or `y`
> that is not in an existing set
> where existing sets are arbitrary subsets ... | In this case no recursion is needed, because we have `LEAD` function.
I will think about the problem in terms of "gaps" and "islands".
I will focus at first on IPv4, because it is easier to do arithmetic with them, but idea for IPv6 is the same and in the end I'll show a generic solution.
To start with, we have a fu... | After a lot of thinking, I believe a query as simple as this will do:
```
with a as(
-- next ip address
select n.next_address, i.subnet_sk
from ip_address i
CROSS APPLY (SELECT convert(binary(4), convert(bigint, i.address) + 1) AS next_address) as n
where n.next_address NOT IN (SELECT address FROM ip_address... | With sql find next available integer within range that is not present in existing integer subset(s) | [
"",
"sql",
"math",
"sql-server-2012",
"network-programming",
"range",
""
] |
I can give a result set consisting of a single value, say `1`, as follows:
```
SELECT 1 as column;
```
and it gives me the result set:
```
column
------
1
```
But I have a list of such values represented as a string `(1, 4, 7, ...)` and I need to produce the following result set:
```
column
------
1
4
7
... | If those are constant values, you can use the `values` clause:
```
select *
from (
values (1), (4), (7)
) as t(id);
```
If your values are inside a string literal, you can use this:
```
select *
from unnest(string_to_array('1,2,3,4', ',')) as id;
``` | You could `unnest` it as an [array](http://www.postgresql.org/docs/9.4/static/functions-array.html):
```
SELECT UNNEST(ARRAY[1, 4, 7])
``` | How to select multiple row in postgresql? | [
"",
"sql",
"postgresql",
"select",
"resultset",
""
] |
I have an address in column `iad_Line1 = 415 W 10th St S` and want to split the `415` to column `ad_housenumber` and `'W 10th St S'` to column `iad_street`.
Is this possible in SQL as a mass update for multiple rows? | Check this
```
DECLARE @ADDRESS AS NVARCHAR(50)
SET @ADDRESS = '415 W 10th St S'
SELECT
SUBSTRING(@ADDRESS, 0, charindex(' ',@address) ) as ad_housenumber ,
RTRIM(SUBSTRING(@ADDRESS, charindex(' ',@address)+1,LEN(@ADDRESS) - 3)) AS iad_street
```
**Updated answer with update statement:**
```
declare @sour... | Try like this,
```
DECLARE @t TABLE
(
AlphaColumn VARCHAR(30),
DOORNO INT,
ADDRESS1 VARCHAR(30)
)
INSERT INTO @t
(AlphaColumn)
VALUES ('415 W 10th St S'),
('34 St S'),
('415 h St SAVC'),
('123 d'),
('ww 1')
SELECT *
FROM @t... | Convert address in two columns | [
"",
"sql",
"sql-server-2012",
""
] |
I'm trying to update medical data from one table to another after switching from one system to another. We have two tables, for simplicity I'll make this a simple example. There are many columns in these tables in reality (not just 5).
**Table1**:
```
name, date, var1, var2, var3
```
**Table2**:
```
name, date, var... | You can `INSERT` into `TABLE2` all values from `TABLE1` that do not already exist in `Table2`:
```
INSERT INTO Table2 (date, var1a, var2a, var3a)
SELECT date, var1, var2, var3
FROM Table1 t1
WHERE NOT EXISTS (SELECT 1 FROM Table2 t2 WHERE t2.date = t1.date)
```
Already existing values are specified by comparing the ... | You could use an `update with a join`. And you dont need to update the `date column` since that's what you are using to find the matches in the 2 tables.
Either you generate a dynamic query based on the empty/null valued columns, or you could do something like the below, which puts the same value in the column if it e... | SQL: Add multiple rows from one table to another when no data for that date in new table | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Can I make an update using common table expression in oracle database?
I am getting error `ORA-00928: missing SELECT keyword` when I am trying this:
```
with average as (SELECT avg(salary) FROM instructor)
update instructor
set salary = case
when salary <= average then salary * 1.05 ... | Since `average salary` just a *scalar value* you can do
```
update instructor
set salary = case
when salary <= (select avg(t.salary) from instructor t) then salary * 1.05
else salary * 1.03
end
```
In that case Oracle first *compute the average* (say `1234.456... | > Can I do something like this in oracle database?
Well, it is not about whether you could do it or not. It is about whether you need to do it or not. In your query I don't see any filter criteria. You want to update all the rows? I don't see a need of **CTE** in your case.
When do you need a **CTE**, i.e. a with cla... | Oracle: Using CTE with update clause | [
"",
"sql",
"oracle",
"common-table-expression",
""
] |
I am having the syntax error in my code on a update statement, after reading multiple posts about it I cant figure out what is causing the error.
The code is as follows:
```
if request.querystring("do")="customer" then
New_customer = request.Form("customer")
openconn con
sSQL="SELECT RelationNumber FRO... | Three things:
1. Read about Sql Injections
2. To debug sql statement "live", use
```
sSQL3="UPDATE Bookings ...
Response.Write(sSQL3)
'con.execute(sSQL3) -- comment it out
```
run page, and test resulted sql query against database
3. If ID has string datatype (char, varchar, etc) then you should qu... | Be aware of the reserve words of database management system.
Here you are using `Order`, which is a reserved one.
So use this if you using **MySQL**:
```
sSQL3="UPDATE Bookings SET `Order`=" & Ordernumber_update & " WHERE ID=" & request("ID") &";"
```
Or in case of **SQL Server**:
```
sSQL3="UPDATE Bookings SET [Or... | Syntax error in Update Statement ASP Classic | [
"",
"sql",
"ms-access",
"asp-classic",
"sql-update",
""
] |
I'm trying to convert my Date which is (eg. 2012-04-20 05:54:59) format in into mm-yyyy. I came across some solutions that says you would need to convert into varchar . Is there any way using the Convert function ?
Thanks :) | You can use `FORMAT` function, available from SQL Server 2012 onwards:
```
DECLARE @myDate DATETIME = '2012-04-20 05:54:59'
SELECT FORMAT(@myDate, 'MM-yyyy')
```
**Output:**
```
04-2012
``` | There might be a more graceful way to pull this off, but the below works.
```
Declare @dt datetime = GETDATE()
SELECT LEFT('0' + CAST(MONTH(@dt) as varchar(2)),2) + '-' + CAST(YEAR(@dt) as char(4))
```
btw my normal Date Conversion cheat sheet is [here](http://rdsrc.us/0WQlRn), but I'm not seeing MM-YYYY as one of... | Convert SQL Server Date to mm-yyyy | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014",
""
] |
I've this data:
```
Id Date Value
'a' 2000 55
'a' 2001 3
'a' 2012 2
'a' 2014 5
'b' 1999 10
'b' 2014 110
'b' 2015 8
'c' 2011 4
'c' 2012 33
```
I want to filter out the **first** and the **last** value (when the table is sorted on the Date column), and only keep the other values. In case there are ... | You can do this with `EXISTS`:
```
SELECT *
FROM Table1 a
WHERE EXISTS (SELECT 1
FROM Table1 b
WHERE a.ID = b.ID
AND b.Date < a.Date
)
AND EXISTS (SELECT 1
FROM Table1 b
WHERE a.ID = b.ID
A... | You can use `row_number` twice to determine the `min` and `max` dates and then filter accordingly:
```
with cte as (
select id, [date], value,
row_number() over (partition by id order by [date]) minrn,
row_number() over (partition by id order by [date] desc) maxrn
from data
)
select id, [date], value
fr... | How to filter out the first and last entry from a table using RANK? | [
"",
"sql",
"group-by",
"rank",
""
] |
I am using an a join query between three tables. My query doesn't display entirely my desired result. There are three tables `team`, `school` and `game`. For example, how can I display the total wins Lawrence North High School(`school_id = 11111`) has?
Current query:
```
SELECT school.school_name
FROM school
INNER ... | Try this
```
SELECT count(*) as Total_wins FROM school INNER JOIN team ON school.school_id = team.school_id INNER JOIN game ON team.team_id = game.game_id WHERE school.school_id = 11111 and game.r = 'W'
``` | You can use the `COUNT` With `Where` clause with `Group By` on the `schoolname`.
```
SELECT school.school_name, COUNT(game.R) as TotalWins
FROM school INNER JOIN team
ON school.school_id = team.school_id
INNER JOIN game
ON team.team_id = game.game_id
WHERE
school.school_id = 11111
AND gam... | JOIN 3 tables and COUNT for result | [
"",
"sql",
""
] |
What is the necessary condition to have the same result from a `JOIN` and a `Cartesian Product` ?
I don't think it is possible, if anyone can clear me will be great, thanks.I've searched but I couldn't an answer to my question. | If you are using SQL Server, the `CROSS JOIN` join type can achieve the same thing as a cartesian product. It matches every row from the left table to every row in the right. This is illustrated in the following SO question:
[What is the difference between Cartesian product and cross join?](https://stackoverflow.com/q... | All three queries return the same result:
```
select *
from t1 cross join t2
select *
from t1,t2
select *
from t1 join t2
on 1=1
``` | Same results with cartesian product and JOIN | [
"",
"sql",
""
] |
I have a dataset with a column of phone numbers. I want to filter this dataset using PROC SQL `WHERE` the length of the numbers is **at least** 7 digits.
In normal SQL I can just apply a length function around a number and it works, however in SAS it won't let me apply it to a numerical column.
My first instinct is t... | Since you have not posted the sample dataset , so I have created one for myself
Creating the sample dataset. Taking `phonenum` as `numeric` same as in your case.
```
data test;
infile datalines;
input phonenum : 8.;
datalines;
123
1234
12345
123456
1234567
12345678
123456789
12345678910
;
run;
```
You are right in t... | In SAS, `length()` takes a character string as argument(only).
You would have to convert the numeric variable to character:
```
proc sql;
select length(put(x,32. -l)) from test;
quit;
```
to use that function. The `-l` left aligns the result (so the extra spaces are ignored). You can arbitrarily choose 32 (as th... | How to find the length of a numerical variable using PROC SQL | [
"",
"sql",
"sas",
"numerical",
"string-length",
"proc-sql",
""
] |
I have a database that contains data for multiple divisions within a company. Each division is given a code that allows certain data elements to be exclusive to them. This code is housed in the 'agency' column. Not all tables have an agency column, but I do not know which ones do or do not have this column.
One of the... | Your second option (generating the scripts) seems like the best one.
Now, as for your error. Is your agency code a string? Then that is probably the problem: you need to enclose it in quotation marks. Since you are building a string, they will need to be doubled:
```
select 'update dbo.' + t.TABLE_NAME +
' ... | `value1` and `value1a` are a string values so they need to be enclosed in quotes, otherwise your script is considering them to be column names, as specified in the error.
So try:
```
select 'update dbo.' + t.TABLE_NAME +
' set agency = ''value1'' where agency = ''value1a'''
``` | Update values in column across multiple tables using where | [
"",
"sql",
"sql-server",
"where-clause",
""
] |
I have used the always true statement e.g. `1 = 1` in case statement of where clause in MYSQL with following syntax:
```
select * from tablename where
(case when tablefield is not null then
then tablefield = 'value'
else 1 = 1 end)
```
I want to know how can i use else `1 = 1` (always true statement) in sqlserver/... | Sorry I just mixed up the query,I was intended to ask for a condition when parameter variable is null instead of tablefield
In that case query may look like this :
select \* from tablename where
(case when parameterfield\_or\_variable is not null then
then tablefield = 'value'
else 1 = 1 end)
or when using parameterf... | you would not use case you would just write a multi conditional statement. In your case it would look like
```
Where (tablefield = 'value'
OR tablefield is null)
``` | Case statement in sqlserver in where clause with else as always true | [
"",
"mysql",
"sql",
"sql-server",
"t-sql",
"case",
""
] |
I have a varchar2 column named NAME\_USER. for example the data is: JUAN ROMÄN but I try to show JUAN ROMAN, replace Á to A in my statement results. How Can I do that?. Thanks in advance. | Use **convert** function with the appropriate charset
```
select CONVERT('JUAN ROMÄN', 'US7ASCII') from dual;
```
below are the charset which can be used in oracle:
```
US7ASCII: US 7-bit ASCII character set
WE8DEC: West European 8-bit character set
WE8HP: HP West European Laserjet 8-bit character set
F7DEC: DEC Fre... | You could use `replace`, `regexp_replace` or `translate`, but they would each require you to map all possible accented characters to their unaccented versions.
Alternatively, there's a function called `nlssort()` which is typically used to override the default language settings used for the `order by` clause. It has a... | how replace accented letter in a varchar2 column in oracle | [
"",
"sql",
"oracle",
""
] |
my question is if there is any way to do this:
```
INSERT INTO t1 (c1, c2, c3, c4, c5)
VALUES (SELECT c1 FROM t2, 15, 2, 'Name', SELECT c5 FROM t4);
```
I know I have the `INSERT INTO t1 FROM SELECT`, but I can't use it for this special case, and I wanted to know if it would be possible to add selects in the insert v... | Sub query use with **`parenthesis`** use right there like:
```
INSERT INTO t1 (c1, c2, c3, c4, c5)
VALUES ((SELECT c1 FROM t2), 15, 2, 'Name', (SELECT c5 FROM t4));
``` | Yes it is possible, but not in the syntax you mention:
```
INSERT INTO t1 (c1, c2, c3, c4, c5)
SELECT t2.c1 , 15, 2, 'Name', t4.c5
FROM t2, t4
WHERE t2.some_field = t4.some_other_field
```
The `t2` and `t4` tables should have some logical join between them or a `WHERE` condition of their own. | SELECT on INSERT's VALUES | [
"",
"mysql",
"sql",
"insert",
"sql-update",
""
] |
Using mysql, is it possible to iterate through results to further results.
I think what I'm trying to do is group by other id grouped by transid, but apparently that isn't what this type of sorting is called.
**Sample Data**
```
id transid other id
------------------------------
|1 |1 |1 |
... | ```
select id,transid,other_id from table group by transid,other_id;
```
If your first column meant transid col ...
Grouping all those rows with same values of transid,other\_id | Of course, you can use `GROUP BY` on multiple columns.
```
SELECT DISTINCT ON (id), transid, other_id GROUP BY transid, other_id;
``` | How to group mysql first column and again by second id not losing unique combinations | [
"",
"mysql",
"sql",
""
] |
```
SQL> desc invoices
Name Null? Type
----------------------------------------- -------- ----------------------------
INVOICE_ID NOT NULL NUMBER(6)
COMPANY_ID NUMBER(6)
STUDENT_ID ... | you have to enter an existed `STUDENT_ID` from `students` table and an existed `COMPANY_ID` from `compaies` table to invoices.
Consider you have data like next
```
COMPANY_ID COMPANY_NAME ADDRESS CONTACT_NO NO_OF_EMP
----------- ------------ -------- ---------- ---------
1 Bl... | You need to first enter companies in "companies", and students in "students". Then use those ID's for [what1] and [what2] | How to insert data into tables that have foreign keys | [
"",
"sql",
"database",
"oracle",
"database-administration",
""
] |
Consider a table named "Books" every one hour new entry will be created in UTC format. I want to fetch last 24 hours data (24 entries) in my local timezone.
I tried this
```
select * from books where created_at >= DATE_SUB(NOW(),INTERVAL 24 HOUR);
```
How do I fetch records at runtime for the past 24 hours without s... | (**EDITED**) Try this :
```
select * from books
where DAYOFMONTH(DATE(created_at))<>DAYOFMONTH(NOW())
order by DATE(created_at) desc
limit 24;
```
Now If you want to change the Time zone, for a session use this query :
```
SET GLOBAL TIME_ZONE = 'ASIA/CALCUTTA'
```
But the only disadvantage is you ha... | Try this:
```
SELECT * FROM books WHERE created_at > DATE_SUB(NOW(),INTERVAL 24 HOUR);
``` | Dynamic sql query for broken hours data | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
I have a table called `MyTextstable (myTextsTable_id INT, myTextsTable_text VARCHAR(MAX))`. This table has around 4 million records and I am trying to remove any instance of the `ASCII` characters in the following range(s) the `VARCHAR(MAX)` column `myTextsTable_text`.
* 00 - 08
* 11 - 12
* 14 - 31
* 127
I have writt... | This is a [known issue](https://connect.microsoft.com/SQLServer/feedback/details/708179/indefinite-hang-with-replace-statement-on-varbinary-max) on SQL Server 2008 with LOB datatypes and certain collations.
It is easy to reproduce
```
/*Hangs on 2008*/
DECLARE @VcMax varchar(max)= char(0) + 'a'
SELECT REPLACE(@VcMa... | For anyone reading this in future, the following ways worked fine.
Way 1. Changing the `COLLATION` on the `VARCHAR(MAX)` column in the `UPDATE SQL` query to `BINARY COLLATION` as Martin Smith suggested (please see the accepted answer).
> REPLACE(myTextsTable\_text COLLATE Latin1\_General\_100\_BIN2, CHAR(0),...
The ... | SQL query working fine in SQL Server 2012, but failed to execute in SQL Server 2008 R2 | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
I am trying to execute a batch insert as below:
```
SQL> INSERT INTO Z (q, w, e, r)
VALUES
('7', 'A', '3', 'A'),
('8', 'B', '4', 'An'),
('9', 'C', '5', 'And');
*
ERROR at line 1:
ORA-00933: SQL command not properly ended
```
However it keeps failing. Could someone help me out why?
Thanks! | ```
INSERT INTO cellphone (phone_id, model, data, os)
select '99997', 'Galaxy S IV', '4g', 'Android' from dual
union all select '99998', 'Galaxy S V', '4g', 'Android' from dual
``` | You can do this with one statement if you use `insert . . . select`:
```
INSERT INTO cellphone (phone_id, model, data, os)
SELECT '99997', 'Galaxy S IV', '4g', 'Android' FROM DUAL UNION ALL
SELECT '99998', 'Galaxy S V', '4g', 'Android' FROM DUAL UNION ALL
SELECT '99999', 'Galaxy S VI', '4g', 'Android' FRO... | Batch SQL Insert is Failing | [
"",
"sql",
"oracle",
"insert",
""
] |
how to write query to get today's date data in `SQL server` ?
```
select * from tbl_name where date = <Todays_date>
``` | The correct answer will depend on the type of your `datecolumn`. Assuming it is of type `Date`:
```
select * from tbl_name
where datecolumn = cast(getdate() as Date)
```
If it is `DateTime`:
```
select * from tbl_name
where cast(datecolumn as Date) = cast(getdate() as Date)
```
**Please note**: In SQL Server, a `... | Seems Mitch Wheat's answer isn't [sargable](http://blog.sqlthoughts.com/2014/03/13/what-makes-a-query-sargable/), although I am not sure this is true.
Please note: a `DATEDIFF()` (or other calculation) on LHS is NOT Sargable, whereas as `Cast(x to Date)` is.
```
SELECT *
FROM tbl_name
WHERE date >= cast(getdate() a... | how to get current/Todays date data in sql server | [
"",
"sql",
"sql-server",
"current-time",
""
] |
How to I write a SQL script that return all the site IDs that are in all my tables:
Tables in this image:

And this is what I want returned:

...because only site 1 & 2 are in all... | ```
select SiteID
from table1 t1
join table2 t2 on t1.SiteID = t2.SiteID
join table3 t3 on t2.SiteID = t3.SiteID
join table4 t4 on t3.SiteID = t4.SiteID
join table5 t5 on t4.SiteID = t5.SiteID;
``` | You can do this with a `join`:
```
select t1.id
from table1 t1 join
table2 t2
on t1.id = t2.id join
table3 t3
on t1.id = t3.id join
table4 t4
on t1.id = t4.id;
``` | How to return IDs that are in each table | [
"",
"sql",
"azure-sql-database",
""
] |
I have one table called 'ratings'
```
ID RATING
1 5
1 2
2 5
3 1
3 4
3 4
```
And i want to find the average rating of each restaurant (same id) that is greater than or equal to than the overall average rating (avg rating of all the restaurants combined)
So for example, restauran... | use `having` clause:
```
SELECT x.id, AVG(x.rating) AS average
FROM ratings x
GROUP BY x.rid
Having AVG(x.rating)>(select AVG(rating) from ratings);
``` | This is a good use-case for windowed function!
`avg(rating) over () as global_avg` will return the overall average as a new column.
Here the solution, using sub queries as well to "split steps":
```
select * from (
select id, avg(rating) as user_avg, global_avg
from (
select id, rating, avg(... | SQL: Compare avg to overall avg | [
"",
"sql",
""
] |
I have inherited two tables, where the data for one is in hours, and the data for the other is in days.
One table has planned resource use, the other holds actual hours spent
```
Internal_Resources
| PeopleName | NoOfDays | TaskNo |
|------------|----------|--------|
| Fred | 1 | 100 |
| Bob |... | Okay - this works:
```
SELECT people.name, COALESCE(PlannedDays, 0) as planned, COALESCE(ActualDays, 0) as actual
FROM ( SELECT PeopleName as name FROM Internal_Resources WHERE TaskNo = 100
UNION
SELECT DISTINCT UserName as name FROM TimeSheetEntries WHERE TaskNumber = 100
ORDER BY Name) AS people
LEFT JOIN ( ... | Invert the logic to read from `Internal_resources` in the outer query:
```
SELECT ir.UserName, NoOfDays as PlannedDays,
(SELECT SUM ( Round( PaidHours / 7 , 2 ))
FROM TimeSheetEntries e
WHERE e.TaskNo = ? AND ir.PeopleName = e.UserName
) as ActualDays
FROM Internal_Resources ir
WHERE ir.T... | Combining SQL grouped and ungrouped results with a cross join? | [
"",
"sql",
"subquery",
"filemaker",
""
] |
How to return rows where a column has 2 words (that is, strings separated by a space) in it?
It must be purely using SQL.
```
SELECT * FROM table WHERE name (has 2 strings in it);
``` | > I dont know the names when querying. Its a big dataset. I only have to check if the name contains a spacebar basically *(from a comment)*.
If you want to distinguish names that have two parts from one-part and three-plus-part names, you can use [regular expression](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#... | **This perfectly works for me**
You can use 'AND' condition and Like Operator with wildcards (%).
```
SELECT * FROM table_name WHERE name LIKE '%Word1%' AND name LIKE '%Word2%'
``` | Query to check if a certain row has 2 words | [
"",
"mysql",
"sql",
""
] |
I'm trying to clean up some incorrect data:
```
id | name
-------------
1 | C
2 | A
3 | A
4 | B
5 | B
6 | B
7 | B
8 | X
9 | X
10 | A
11 | A
12 | A
13 | X
14 | X
15 | B
16 | C
17 | C
18 | X
19 | A
20 | A
```
What has ... | We need to join our duplicates into chain, it easy to reach by:
```
select *
from updateTable t1
left join updateTable t2 on t1.name = t2.name and t1.id+1 = t2.id
;
+----+------+------+------+
| id | name | id | name |
+----+------+------+------+
| 1 | C | NULL | NULL |
| 2 | A | 3 | A |
| 3 | A | ... | User variables to mimic a row number per each name.Tested on my machine
```
SELECT @var:=name,@no:=0 FROM t ORDER BY id;
UPDATE t join
(select ID,NAME,(CASE WHEN NAME=@var THEN @no:=@no+1 ELSE @no:=1 AND @var:=NAME END) BLAH
from T
order by ID)X
on T.ID=X.ID
SET T.NAME= NULL
where X.BLAH<>0
``` | MySQL - Update rows where value in column is the same as previous row | [
"",
"mysql",
"sql",
""
] |
I have a table "logintracking" and fields are "attemptresult" and "attemptdate".
```
attemptdate attemptresult
2007-12-18 14:33:24.000 LOGOUT
2007-12-18 14:33:38.000 SUCCESS
2007-12-18 14:35:36.000 LOGOUT
2007-12-18 14:46:50.000 SUCCESS
2007-12-18 16:52:48.000 TIMEOUT
2007-12-18 16:57:33.000 SUCCESS
2007-1... | Without knowing how to compute for the Login count, here is what I came up:
The idea is to generate hourly intervals of all dates in `LoginTracking`. Then `LEFT JOIN` that into the `LoginTracking` to achieve the result:
```
CREATE TABLE LoginTracking(
AttemptDate DATETIME,
AttemptResult VARCHAR(10)
)
I... | Attempt Result is not so clear.you should explain why on 14th logincount=1 and why on 16th it is 0.
Try this,
```
DECLARE @LoginTracking TABLE(
AttemptDate DATETIME,
AttemptResult VARCHAR(10)
)
INSERT INTO @LoginTracking VALUES
('2007-12-18 14:33:24.000', 'LOGOUT'),
('2007-12-18 14:33:38.000', 'SUCCES... | sql server datetime hourly interval | [
"",
"sql",
"sql-server",
""
] |
I have a very long `CASE` statement and it makes the query very long. Is there an alternative way? Does the long `CASE` statement impact the performance? I see people are recommending `COALESCE` but I'm not sure if this is a good alternative in my query.
The example below, a, b, c, d, e, f are columns from a table but... | I don't expect any performance issues from the `CASE` statement itself. Since your one query is making one pass at the data, it might perform much better than multiple queries for each product ID.
The query may perform better with a `WHERE` clause-- if that is even possible with your long query.
If the table is large... | If the `UPDATE` doesn't need to run against every record, you can use `WHERE` to filter. As for your `CASE` expression, nothing springs to mind, I took out the nested `CASE` just out of my own preference, but don't think it has any performance impact:
```
UPDATE table
SET totalAmt = CASE WHEN product_id = 1 THEN a*b*c... | SQL Server: Alternative of long CASE statement | [
"",
"sql",
"sql-server-2008",
""
] |
I am following an online course on databases. However, I really don't know what the next step is and how I can answer this question. Can anyone please help?
This is what I have so far.
```
SELECT P.name
FROM Persons P
LEFT JOIN Knows K ON K.personA_id = P.id
WHERE K.age >= P.age
```

```
SELECT distinct P1.name
FROM Persons P1
INNER JOIN Knows K ON K.personA_id = P1.id
INNER JOIN Persons P2 ON K.personB_id = P2.id AND P1.age - P2.age > 5
```
It will output everybody that knows 1 person or more (personA) and that every person known is mo... | The title of the question referred to using `ALL/EXISTS`. Here's are approaches that actually do that:
```
/* all */
select p.name
from Persons as p
where p.age - 5 > all (
select p2.age
from
Knows as k inner join
Persons as p2
on p2.person_id = k.personB_id
where p2.id = p.id
)... | FOR ALL/EXIST Queries | [
"",
"mysql",
"sql",
"exists",
"forall",
""
] |
I'm trying to create a new column in a table. I want to make it not nullable. And I don't want to use a default constraint.
I tried the following query. But it fails.
Please correct me here or suggest if a better option exists.
```
ALTER TABLE [dbo].[UCBCluster]
ADD PBXClusterId INT NULL;
UPDATE [dbo].[UCBCluster... | yo have to keep default costraint then only you can change to not null
```
ALTER TABLE [dbo].[UCBCluster]
add constraint cnt_column Default '' for PBXClusterId
ALTER TABLE tb_TableName
ALTER COLUMN PBXClusterId int NOT NULL
``` | You can't run all of this in a single batch, because SQL Server will parse it at the start of execution, and at that time, no `PBXClusterId` column exists yet.
You need to run this in **three separate batches** - either by just highlighting it in Management Studio, or if you want to run it as one, you need to put `GO`... | creating a sql column updating it | [
"",
"sql",
"sql-server-2008",
""
] |
The table I am working with uses two rows to record each 'transaction': one row to identify the party acting, the second row to identify the party acted upon. The data contents differ only in the value of one field, a logical flag of 'Y' or 'N'. For example, I might have this:
```
E-num E-date Client Actor
12... | just join the table on the `E-num` and pick the rows as required.
If you are using MySQL, the Query would be
```
SELECT
t1.E-num,
t1.E-date,
t1.Client AS 'For',
t2.Client AS Against
FROM
`transaction` t1
INNER JOIN
`transaction` t2
ON
t1.E-num = t2.E-num
WHERE
t... | An ORACLE version: use a self-join of your table:
```
SELECT t1."E-num", t1."E-date", t1."Client" as "For", t2."Client" as "Against"
FROM transaction t1, transaction t2
WHERE t1."E-num" = t2."E-num"
AND t1."E-date" = t2."E-date"
AND t1."Actor" = 'Y'
AND t2."Actor" = 'N';
``` | SQL to combine two records into one | [
"",
"sql",
"oracle11g",
""
] |
I have some complex join statement and want to make it easier.(or stay it but make working right :))
```
CREATE TABLE #Temp1
(
ID INT IDENTITY,
Name1 VARCHAR(100),
Value1 INT
)
CREATE TABLE #Temp2
(
ID INT IDENTITY,
Name2 VARCHAR(100),
Value2 INT,
Value1 INT
)
INSERT IN... | This simple join work:
```
UPDATE #Temp2
SET Value1 = a.Value1
FROM #Temp1 AS a
INNER JOIN #Temp2 AS b
ON b.ID BETWEEN (a.ID*6-4) AND (a.ID*6+1)
``` | You could try this which should solve your problem:
```
DECLARE @Counter int = 0,
@Rows int
Set @Rows = (Select count(*) from #Temp1)
While (@Counter < @Rows)
Begin
Update #Temp2
Set Value1 = (Select Value1 from #Temp1 where ID = @Counter + 1)
Where ID between 2 + (@Counter * 6) and 7 + (@Counte... | Complex update/join in sql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to pull all data for the last 24 hours but starting from the current time. If the current date-time is 5/3 and the time is 11:30 then i want to pull the last 24 hours from 11:30. The data type for date field is `datetime` and it has only the date and time values without the seconds. Here is my current query... | To be more explicit with your intentions, you may want to write your query like so:
```
select Name, Location, myDate from myTable where myDate>= DATEADD(hh, -24, GETDATE())
```
[SQL Server DATEADD](https://msdn.microsoft.com/en-us/library/ms186819.aspx) | I believe the issue is with:
```
select Name, Location, myDate from myTable where myDate>= getdate()-24
```
The -24 as this would be -24 days
try:
```
select Name, Location, myDate from myTable where myDate>= getdate()-1
```
An alternative would be to use the date add function:
<http://www.w3schools.com/sql/func_... | How to get last 24 hours from current time-stamp? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a question about writing a sub-query in Microsoft T-SQL. From the original table I need to return the name of the person with the second most pets. I am able to write a query that returns the number of perts per person, but I'm not sure how to write a subquery to return rank #2.
Original table:
```
+—————————-... | You are using TSQL So:
```
WITH C AS (
SELECT COUNT(Pet) OVER (PARTITION BY Name) cnt
,Name
FROM PetTable
)
SELECT TOP 1 Name, cnt AS NumPets
FROM C
WHERE cnt = 2
``` | This is how you could use ROW\_NUMBER to get the result.
```
SELECT *
FROM(
SELECT ROW_NUMBER() OVER (ORDER BY COUNT(name) DESC) as RN, Name, COUNT(NAME) AS COUNT
FROM PetTable
GROUP BY Name
) T
WHERE T.RN = 2
``` | SQL subquery to return rank 2 | [
"",
"sql",
""
] |
In my db2 database I have three tables.
1. Computer
2. Computer\_Software
3. Software
This stores the relationship that each computer has multiple software items installed. So Computer\_Software just has a foreign key to Computer and Software.
I need a query that returns for a given set of computers, the list of sof... | If your `computer_software` table has a column `computer_id` and `software_id` and there is one row per computer and software on that computer -- as I imagine -- then you can count the rows where the computer is either 1/2/5, group by computer\_id, having a count equal to 3 (the software appears on all the 3 computers)... | John,
I'm a bit rusty but using a subclause with the IN statement should do the trick e.g.
```
select software.id from software
where software.id in
(
select computer_software.softwareid from computer_software
where computer_software.computerid in (1,2,5)
)
```
This won't be the most efficient way to get a result.... | SQL to find set of children with common parents | [
"",
"sql",
"db2",
""
] |
I have to find the highest price from three different tables but I do not know how to get the max of P now.
PC(model,speed,ram,hd,price)
Laptop(model,speed,ram,hd,screen,price)
Printer(model,color,type,price)
```
SELECT model
FROM ((SELECT MAX(price)
FROM PC)
UNION
(SELECT MAX(price)
FROM La... | If you want the model, use `union all` and `order by`. You don't specify the database, so here is the ANSI standard solution:
```
SELECT model, price
FROM ((SELECT model, price FROM PC)
UNION ALL
(SELECT model, price FROM Laptop)
UNION ALL
(SELECT model, price FROM printer)
) p
ORDER BY pr... | If you want to get only 1 record with highest price you should use `TOP 1`. Something like that:
```
SELECT TOP 1 model
FROM ((SELECT MAX(price)
FROM PC)
UNION
(SELECT MAX(price)
FROM Laptop)
UNION
(SELECT MAX(price)
FROM Printer)) AS P
WHERE MAX(P)
ORDER BY P DESC;
``` | Finding the highest price from three different tables | [
"",
"sql",
"max",
""
] |
I'm trying to develop a query to validate user data entry and I'm stuck. Basically, we're working with information about a daily 24 hour composite water sample. The user will enter the "COLDATE" which is the end of the composite and is stored in DATETIME format like "2015-03-02 04:00:00.000". Then they will enter the "... | Finally figured it out. Here is the query that gives me what I was looking for:
```
set dateformat mdy;
With CTE1 as
(
Select S1.SAMPNO as SAMPNO1
,S1.COLDATE as COLDATE1
,S1.LOCCODE as LOCCODE1
,CAST( U1.Compstartdate +' '+ U1.Compstarttime as datetime) as Compstart1
From [SAMPLE] as S1 join... | I think you are getting confused - there is no need to loop through the table - that's effectively what the join does.
Sadly SQLFiddle seems to be having difficulties at the moment. This is what I was going to set up as an example:
```
create table SAMPLE (
SAMPNO int,
LOCCODE char(1),
LOCDESCR char(1),
LO... | Tricky data entry validation SQL query | [
"",
"sql",
"sql-server-2008",
"while-loop",
"cursor",
"logic",
""
] |
For pagination purposes, I need a run a query with the `LIMIT` and `OFFSET` clauses. But I also need a count of the number of rows that would be returned by that query without the `LIMIT` and `OFFSET` clauses.
I want to run:
```
SELECT * FROM table WHERE /* whatever */ ORDER BY col1 LIMIT ? OFFSET ?
```
And:
```
SE... | **Yes.** With a simple window function.
### Add a column with the total count
```
SELECT *, count(*) OVER() AS full_count
FROM tbl
WHERE /* whatever */
ORDER BY col1
OFFSET ?
LIMIT ?
```
Be aware that the cost will be substantially higher than without the total number. Postgres has to actually *count all qualif... | While [Erwin Brandstetter](https://stackoverflow.com/users/939860/erwin-brandstetter)'s answer works like a charm, it returns the total count of rows **in every row** like following:
```
col1 - col2 - col3 - total
--------------------------
aaaa - aaaa - aaaa - count
bbbb - bbbb - bbbb - count
cccc - cccc - cccc - cou... | Run a query with a LIMIT/OFFSET and also get the total number of rows | [
"",
"sql",
"postgresql",
"count",
"pagination",
"limit",
""
] |
I'm getting this error when I'm putting outside the loop in side casting working .
> Msg 137, Level 15, State 2, Line 2
> Must declare the scalar variable "@numCount"
Can you please tell me what I'm doing wrong ??
Thanks
```
create table #myTemp
(
rowid int identity (1,1),
Name varchar(200),
emai... | Declaring and setting in the same statement is perfectly valid in SQL Server 2008 R2. The issue is your GO
```
GO -- < -- starts a new batch and thus the declaration on @NumCount is totally unrealted to this Print.
PRINT 'My String' + CAST(@numCount AS VARCHAR) + '***'
``` | It has to do your variable being only accessible in your batch. Get rid of **"GO"**. And it should work.
```
create table #myTemp (rowid int identity (1,1), Name varchar(200),email varchar(200),flag bit)
select * from #myTemp
declare @name varchar(200),@email varchar(200)
declare @numCount int = 20
while (1 <= @num... | Must declare the scalar variable "@numCount" | [
"",
"sql",
"database",
"sql-server-2008",
"stored-procedures",
""
] |
I'm using Oracle.
Having a table as:
```
Year Type Value
2011 1 500
2011 2 550
2011 3 600
...
...
2012 1 600
2012 2 750
2012 3 930
```
I needed to subtract all the values from different types, grouped by year.
The operation would be:
For 2011 -> 1-2-3 (500-550-600... | The determination of whether the number should be treated as positive or negative needs to happen inside of your aggregation `SUM()`. So:
```
select sum(case when type = 1 OR type = 2 then value else - value end)
from table t
group by year;
```
Because both 1 and 2 are positive in your 1+2-3-4-5-6... formula (the 1 b... | For sake of completeness, two alternate solutions:
```
select sum(case when type in (1, 2) then value else -value end)
from t
group by year;
```
Or, using a simple case expression:
```
select sum(case type
when 1 then value
when 2 then value
else -value
end)
from t
g... | SQL Conditional aggregation | [
"",
"sql",
"oracle",
"conditional-aggregation",
""
] |
I am maintaining a web project using Java & mysql.
One mysql table has over 10 million records, I did partition the table by date, so that to reduce rows in each partition. Indexes are also added properly according to queries.
In most query, only the first 1 or 2 partition is used, and the sum of records in those use... | There are several other things you can do for performance improvement.
* Analyze the query and introduce indexes as required.
* Identify data access pattern of the application and you can cache only the frequently accessed data to reduce disk I/O. | I would shoot for doing some pre-aggregations and store them as tables if the old data is static. Then have your initial queries based on the pre-aggregate tables and once someone wants more detail, then go to the granular level of the data. You could create many different summary / aggregate tables, even if you do gro... | Mysql - query table with over 10m data | [
"",
"mysql",
"sql",
"bigdata",
""
] |
I have a table that looks something like this:
```
date | product | price
--------------------------------
17/01/2015 | milk | 2.54
18/01/2015 | milk | 2.47
23/01/2015 | milk | 2.61
21/01/2015 | eggs | 1.35
04/02/2015 | eggs | 1.36
27/01/2015 | eggs | 1.31
```
What I need is a select that retu... | Use a correlated subquery to find each product's last date:
```
select date, product, price
from table t1
where date = (select max(date) from table t2
where t1.product = t2.product)
```
(After reading Damien\_The\_Unbeliever's comment I want to add that if several entries exist with same max date for a ... | Try like this:
```
select max(date), product,price
from table
group by product, price
``` | Return rows with maximum value of a column | [
"",
"sql",
"t-sql",
""
] |
How does Min function work on dates ? If 2 records have the same date and time stamp , the min function returns 1. Does it pull records based on when it was put into the table ? | [`MIN`](https://msdn.microsoft.com/en-us/library/ms179916.aspx) is an aggregate function so it will return 1 record in your question's case. Since the two records have the same date and timestamp it doesn't matter which date and timestamp are returned (they're the same). Finally, the time the records were inserted is n... | MIN() returns the smallest of all selected values of a column. It seems to me that your statement may simply be asking if a minimum exists.
Please post your sql statement.
possibly this is what you need:
```
SELECT MIN (date) AS "Min Date"
FROM tablename;
``` | SQL Min function on Date | [
"",
"sql",
""
] |
I have a `mail` table that looks like this:
```
CREATE TABLE `mail` (
`id` int(20) NOT NULL auto_increment,
`userto` varchar(30) collate utf8_unicode_ci NOT NULL,
`userfrom` varchar(30) collate utf8_unicode_ci NOT NULL,
`message` longtext collate utf8_unicode_ci NOT NULL,
`seen` int(1) NOT NULL,
PRIMARY KE... | You have to use `DISTINCT` for non repeative record like
```
SELECT DISTINCT userfrom FROM mail
WHERE userto = "admin"
```
Check [DISTINCT](http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html) | I believe you need to use the DISTINCT keyword.
Useful link => <http://www.w3schools.com/sql/sql_distinct.asp> | How do I get a list of unique row values? | [
"",
"sql",
""
] |
I have some problems with joining two tables when foreign key is no set directly.
I have two tables:
TABLE A
```
{A.ID} {A.NAME} {Parentid} {A_FK} (foreign key)
A.ID1 A.NAME1 NULL A_FK1
A.ID2 A.NAME2 NULL A_FK2
A.ID3 A.NAME3 A.ID2 NULL
A.ID4 A.NAME4 NULL A.FK4 ... | If your parent-child relationship can be of multiple levels, then you need to write a recursive query something like this:
```
CREATE TABLE TableA(ID INT, Name VARCHAR(10), ParentID INT NULL, FK INT NULL );
CREATE TABLE TableB( ID INT, Code VARCHAR(50));
INSERT INTO TableA VALUES (1, 'Name1', NULL, 1);
INSERT INTO Tab... | You could first get all rows to be joined on `TableB` using `FK` and `UNION ALL` them with rows to be joined on `TableA` using `ParentID`:
**SAMPLE DATA**
```
CREATE TABLE TableA(
ID INT,
Name VARCHAR(10),
ParentID INT NULL,
FK INT NULL
)
CREATE TABLE TableB(
ID IN... | Joining two tables with reference to foreign key | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I am following an online course on databases. However, I don't know how to proceed with this question. Can anyone help? This is my code:
```
SELECT distinct name
FROM Persons P, Knows K
WHERE K.personA_id = P.id AND K.personB_id = P.id
GROUP BY name
HAVING SUM(K.id) = 2
```

GROUP BY name
HAVING COUNT(K.personB_id) = 2
``` | ```
SELECT P.name
FROM Persons P
WHERE ( SELECT COUNT(*)
FROM Knows K JOIN Persons P2 ON K.personB_id = P2.id
WHERE K.personA_id = P.id
AND P2.age >= 60
) = 2
```
but if you want to know how use the having
```
SELECT P.name
FROM Persons P JOIN Knows K ON K.personA_id = P.id
JOIN... | Problems with HAVING query | [
"",
"mysql",
"sql",
"exists",
"forall",
""
] |
I am querying a table that contains a comments section. The comments section can contain part numbers of variable lengths. If, within the comments section I ensure that the part numbers are wrapped in quotes ("partnumberA"), is it possible query that field to pull everything in between the quotes (even if the part numb... | You can use a combination of `substring` and `charindex` functions.
```
declare @Comments varchar(50)
set @Comments = '3/6/2015 (blujo) - "3490-0001023-02" PO46709 Due 3/10 (RW24718)'
select substring(@Comments,
charindex('"',@Comments)+1,
charindex('"',@Comments,
ch... | Here's a sample using a variable. Of course your query would reference a table column instead:
```
declare @x varchar(256) = '3/6/2015 (blujo) - "3490-0001023-02" PO46709 Due 3/10 (RW24718)';
select
substring(
@x,
charindex('"', @x) + 1,
charindex('"', @x, charindex('"', @x) + 1) - charind... | Want to pull variable info from a Comments section | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I apologize if this is fairly basic MySQL, but I'm at a loss. I have two tables: `users` and `us_geolocations` and I would like to create a View of the geolocations of the users.
My first issue is that I have multiple `lat` and `long` entries for some cities (and even some zip codes) in my `us_geolocations`. And my se... | Is this what you're looking for?
```
CREATE VIEW `active_us_geolocations` AS
SELECT DISTINCT
`users`.`city` AS `city`,
`users`.`state` AS `state`,
`users`.`zip` AS `zip`,
`us_geolocations`.`lat` AS `lat`,
`us_geolocations`.`long` AS `long`
... | ```
CREATE VIEW `active_us_geolocations` AS
SELECT DISTINCT
`users`.`city` AS `city`,
`users`.`state` AS `state`,
`users`.`zip` AS `zip`,
`us_geolocations`.`lat` AS `lat`,
`us_geolocations`.`long` AS `long`
FROM
(`users`
LEFT JOIN `us_geolocations`
... | How to I join two tables with two required parameters and one optional parameter? | [
"",
"mysql",
"sql",
""
] |
I have a table that looks like this
```
[UniqueID]-[1]-[2]-[3]-[etc... to 250
------------------------------
00000A | 0 | 0 | 1 |
00000B | 0 | 1 | 0 |
00000C | 0 | 1 | 1 |
```
I pivoted that table from another table with two columns, the unique ID and the number (1, 2, 3, etc.)
I have another table which ha... | Target table is not normalized because `[1], [2], ..., [150]` are nothing more than a repeating group of columns ([1](https://stackoverflow.com/questions/23194292/normalization-what-does-repeating-groups-mean), [2](https://www.simple-talk.com/sql/learn-sql-server/facts-and-fallacies-about-first-normal-form/)). This mea... | ```
Update t1
Set t1.value = t2.value
FROM
t1
INNER JOIN t2 ON t1.KEY = t2.KEY
``` | T-SQL: Can I update a table using rows from another table? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have tables as follows:
```
inverter [ id, address, ... ]
string [ id, inverter_id (foreign key), ... ]
```
I want to select all "inverters", together with the number of "strings" attached to them.
I tried this query here, but it gives me empty result, so how can I do this?
```
SELECT inverter.*, COUNT(string.*) ... | It seems SQLite3 chokes on `count(s.*)` so try this instead:
```
select i.*, count(s.id)
from inverter i
left join string s on i.id = s.inverter_id group by i.address;
```
This gives:
```
2|A1|North side|0
3|A2|Broken inverter|2
4|A3||1
5|A4|South-west corner|0
``` | Using an aggregate always means that you are grouping, and if you don't specify the grouping it will be a single group containing all records. Group on the fields that you get from the `inverter` table. Also use a single field in the count instead of `string.*`:
```
select
inverter.id, inverter.address, count(string... | Count rows from another table referencing current row by foreign key | [
"",
"sql",
"sqlite",
""
] |
I have a SQL with some conditions, for example:
```
SELECT
CASE WHEN RIGHT(CAST(COLUMN_A as nvarchar(max)),1) = '.' THEN
SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 4, 4) ELSE
SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 3, 4) END AS COL_1
```
In the same select I have others check using the rule above and I hav... | You can use nested SELECT command like this:
```
SELECT CASE
WHEN x.COL_1 LIKE 'AAAA' OR
x.COL_1 LIKE 'BBBB' OR
x.COL_1 LIKE 'CCCC' OR
x.COL_1 LIKE 'DDDD' THEN 1 ELSE 0 END AS Code
FROM (
SELECT
CASE WHEN RIGHT(CAST(COLUMN_A as nvarchar(max)),1) = '.' THEN
SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 4, 4) ... | ```
SELECT *
FROM (
SELECT list_of_columns
, CASE WHEN this=cool THEN 1 ELSE 0 END As computed_column
FROM ...
) As a_subquery
WHERE computed_column = 1
``` | Shorten SQL conditions | [
"",
"sql",
"sql-server-2008-r2",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.